[go: up one dir, main page]

0% found this document useful (0 votes)
30 views46 pages

PYTHON REPOT Final Master - Removed - PDF Print Final

Uploaded by

renuvprajapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views46 pages

PYTHON REPOT Final Master - Removed - PDF Print Final

Uploaded by

renuvprajapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Table Of Contents

Chapter 1: Introduction 1-2


1.1 Python
1.2 Scripting Language
1.3 Object Oriented Programming
1.4 History of python
1.5 Behind the Scene of Python

Chapter 2: Downloading & Installing Python 3-9


2.1 Downloading Python
2.2 Installing Python
2.3 Setup path of variable
2.4 Running The Python IDE
2.5 Python code Execution

Chapter 3: Data Types & Operator 10-11


3.1 Data Type
3.2 Variables
3.3 String
3.4 Python Operator
3.4.1Arithmetic Operator

Chapter 4: Tuple & List 12-15


4.1 Tuple
4.1.1 Accessing Tuple Values
4.1.2 Built in Operation
4.2 List
4.2.1 Accessing List Values
4.2.2 Built in Operation
4.2.3Built in Functions

Chapter 5: Loops & Conditional Statements 16-17


5.1 Loops
5.3 Function
5.3.1 Syntax & Examples
Chapter 6: Function and String 18-22
6.1 Python Functions
6.2 String

Chapter 7: File Handling 23-25


7.1 File Handling
7.2 Python read file
7.3 Python Read/ Create file
7.4 Python Delete file

Chapter 8: Python MySQL 26-29


8.1 Python MySQL
8.2 MySQL Database
8.3 Install MySQL Driver

Chapter 9: Python Matplotlib 30-42


9.1 What is Matplotlib
9.2 Installation of Matplotlib
9.3 Pyplot
9.4 Matplotlib Plotting

Conclusion 43
Reference 44
CHAPTER 1
INTRODUCTION
1.1 Python

Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its
design philosophy emphasizes code readability, and its syntax allows programmers to express concepts
in fewer lines of code than would be possible in languages such as C++ or Java. The language provides
constructs intended to enable clear
programs on both a small and large scale.
Python supports multiple programming paradigms, including object-oriented, imperative and
functional programming or procedural styles. It features a dynamic type system and automatic memory
management and has a large and comprehensive standard library. Python interpreters are available for
installation on many operating systems, allowing Python code execution on a wide variety of systems.

1.2 Scripting Language

• A scripting or script language is a programming language that supports scripts, programs written
for a special run-time environment that automate the execution of tasks that could alternatively
be executed one-by-one by a human operator.
• Scripting languages are often interpreted (rather than compiled). Primitives are usually the
elementary tasks or API calls, and the language allows them to be combined into more complex
programs. Environments that can be automated through scripting include software applications,
web pages within a web browser, the shells of operating systems (OS), embedded systems, as
well as numerous games.
• A scripting language can be viewed as a domain-specific language for a particular
environment; in the case of scripting an application, this is also known as an extension
language. Scripting languages are also sometimes referred to as very high-level
programming languages, as they operate at a high level of abstraction, or

• as control languages.

1.3 Object Oriented Programming Language

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects",


which may contain data, in the form of fields, often known as attributes; and code, in the form of
procedures, often known as methods. A distinguishing feature of objects is that an object's procedures
can access and often modify the data fields of the object with
which they are associated (objects have a notion of "this" or "self").
In OO programming, computer programs are designed by making them out of objects that interact with
one another. There is significant diversity in object oriented programming, but most popular languages
1
are class-based, meaning that objects are instances of classes, which typically also determines their
type.
1.4 History

Python was conceived in the late 1980s, and its implementation was started in December
1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language (itself
inspired by SETL) capable of exception handling and interfacing with the Amoeba operating system.
Van Rossum is Python's principal author, and his continuing central role in deciding the direction of
Python is reflected in the title given to him by the Python community,
benevolent dictator for life (BDFL).

2
CHAPTER 2
DOWNLOADING & INSTALLING PYTHON

2.1Downloading python

If you don’t already have a copy of Python installed on your computer, you will need to open
Up your Internet browser and go to the Python download page
(http://www.python.org/download/).

Now that you are on the download page, select which of the software builds you would like to
download. For the purposes of this article we will use the most up to date version available
(Python 3.4.1).

3
Once you have clicked on that, you will be taken to a page with a description of all the new updates and
features of 3.4.1, however, you can always read that while the download is in process. Scroll to the
bottom of the page till you find the “Download” section and click on the
link that says “download page.”

Now you will scroll all the way to the bottom of the page and find the “Windows x86 MSI installer.”
If you want to download the 86-64 bit MSI, feel free to do so. We believe that even if you have a
64-bit operating system installed on your computer, the 86-bit MSI is preferable. We say this
because it will still run well and sometimes, with the 64- bit architectures, some of the compiled
binaries and
Python libraries don’t work well.

2.2Installing Python

Once you have downloaded the Python MSI, simply navigate to the download location on your
computer, double clicking the file and pressing Run when the dialog box pops up.

4
If you are the only person who uses your computer, simply leave the “Install for all users” option
selected. If you have multiple accounts on your PC and don’t want to
install it across all accounts, select the “Install just for me” option then press “Next.”

If you want to change the install location, feel free to do so; however, it is best to leave it as is and
simply select next, Otherwise...
Scroll down in the window and find the “Add Python.exe to Path” and click on the small red “x.”
Choose the “Will be installed on local hard drive” option then press “Next.”

5
Now that you have completed the installation process, click on “Finish.

2.3 Setup the Path Variable

Begin by opening the start menu and typing in “environment” and select the option called “Edit the system
environment variables.”

6
When the “System Properties” window appears, click on “Environment Variables…”

Once you have the “Environment Variables” window open, direct your focus to the bottom half. You
will notice that it controls all the “System Variables” rather than just this associated with your user.
Click on “New…” to create a new variable for
Python.

Simply enter a name for your Path and the code shown below. For the purposes of this example

we have installed Python 2.7.3, so we will call the path: “Pythonpath.” The string that you will

need to enter is:

“C:\Python27\;C:\Python27\Scripts;”

2.4 Running The Python IDE

Now that we have successfully completed the installation process and added our

“Environment Variable,” you are ready to create your first basic Python script. Let’s begin by opening
Python’s GUI by pressing “Start” and typing “Python” and selecting
the “IDLE (Python GUI).”

7
Once the GUI is open, we will begin by using the simplest directive possible. This is the “print” directive
which simply prints whatever you tell it to, into a new line. Start by typing a print directive like the one
shown in the image below or copy and paste

this text then press

“Enter”: print (“Congratulations on executing your first print directive !”)

2.5 Python Code Execution

8
Python’s traditional runtime execution model: source code you type is translated to byte code, which is then
run by the Python Virtual Machine. Your code is automatically compiled,

but then it is interpreted.

Source code extension is .py

Byte code extension is .pyc (compiled python code)

9
CHAPTER 3
DATA TYPES & OPERATOR

3.1 Data Type

(this is called dynamic typing). Data types determine whether an object can do something, or whether
it just would not make sense. Other programming languages often determine whether an operation
makes sense for an object by making sure the object can never be stored somewhere where the
operation will be performed on the object (this type system is called static typing). Python does not do
that. Instead it stores the type of an object with the object, and checks when the operation is performed
whether that operation makes sense for
that object

• Python has many native data types. Here are the important ones:
• Booleans are either True or False.
• Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions (1/2 and 2/3), or even complex numbers.
• Strings are sequences of Unicode characters, e.g. an HTML document.
• Bytes and byte arrays, e.g. a JPEG image file.
• Lists are ordered sequences of values.
• Tuples are ordered, immutable sequences of values.
• Sets are unordered bags of values.

3.2 Variable

Variables are nothing but reserved memory locations to store values. This means that when you create a variable
you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or
characters in these variables.

Ex: counter = 100 # An integer

assignment miles = 1000.0 # A floating

point name = "John" # A string

10
3.3 String

In programming terms, we usually call text a string. When you think of a string as a collection of letters, the
term makes sense.

All the letters, numbers, and symbols in this book could be a string. For that

matter, your name could be a string, and so could your address.

3.4 Python Operator

3.4.1 Arithmetic Operator

Operator Meaning Example

+ Add two operands or unary plus x+y


+2

- Subtract right operand from the left or unary minus x-y


-2

* Multiply two operands x*y

/ Divide left operand by the right one (always results into float) x/y

11
CHAPTER 4
TUPLES & LIST
4.1Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses.

4.1.1 Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain

value available at that index. For example − tup1 = ('physics',

'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0] print

"tup2[1:5]: ", tup2[1:5]

When the above code is executed, it produces the following result − tup1[0]:

physics tup2[1:5]: [2, 3, 4, 5]

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new tuple, not a string. In fact, tuples respond to all of the general
sequence operations we used on strings in the prior chapter −

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

12
for x in (1, 2, 3): print x, 123 Iteration

4.2 List

The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets. Important thing about a list is that items in a list
need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets.

For example − list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1,

2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

4.2.1Accessing Values in Lists:

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value

available at that index. For example − list1 = ['physics', 'chemistry', 1997,

2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]
Output: list1[0]: physics

list2[1:5]: [2, 3, 4, 5]

Update: list = ['physics', 'chemistry', 1997, 2000]; print

"Value available at index 2 : " print list[2] list[2] = 2001; print

"New value available at index 2 : " print list[2]

Output: Value available at index 2 :


1997 New value available at index 2 :
2001

Delete: list1 = ['physics', 'chemistry', 1997, 2000]; print list1 del

list1[2]; print "After deleting value at index 2 : " print list1

['physics', 'chemistry', 1997, 2000]

Output: After deleting value at index 2 :


['physics', 'chemistry', 2000]

4.2.2 Basic List Operation

13
Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

4.2.3Built-in List Functions & Methods:

SN Function with Description

1 cmp(list1, list2) Compares elements of both lists.

2 len(list) Gives the total length of the list.

3 max(list) Returns item from the list with max value.

4 min(list) Returns item from the list with min value.

14
5 list(seq) Converts a tuple into list.

Python includes following list methods

SN Methods with Description

1 list.append(obj) Appends object obj to list

2 list.count(obj) Returns count of how many times obj occurs in list

3 list.extend(seq) Appends the contents of seq to list

4 list.index(obj) Returns the lowest index in list that obj appears

5 list.insert(index, obj) Inserts object obj into list at offset index

6 list.pop(obj=list[-1]) Removes and returns last object or obj from list

7 list.remove(obj) Removes object obj from list

8 list.reverse() Reverses objects of list in place

15
CHAPTER 5
LOOPS & CONDITIONAL STATEMENTS

5.1 Loop definition


Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. The following diagram
illustrates a loop statement −

> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

16
>= Greater than or equal to - True if left operand is greater than or equal to the x >= y
right

<= Less than or equal to - True if left operand is less than or equal to the right +x <=
y

Python programming language provides following types of loops to handle looping requirements.

5.2 Function

Function blocks begin with the keyword def followed by the function name and parentheses ( ( ))
Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function.

The code block within every function starts with a colon (:) and is indented.

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.

Syntex:
Def functionname(parameters):

“function_docstring”

Function_suite
Return[expression]

Example:

Def printme(str):
“this print a passed string into this function” print str
return
1. # Function definition is here def printme( str
):
"This prints a passed string into this function" print str
return;

# Now you can call printme function printme("I'm first call to user
defined function!") printme("Again second call to the same
function")

17
CHAPTER 6
FUNCTION AND STRING

6.1 What is Function :-


A function is a block of code which only runs when it is called.You can pass
data, known as parameters, into a function.A function can return data as a
result.

Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")

my_function()

Arguments

Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname +" Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?

The terms parameter and argument can be used for the same thing:
information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function
definition.
An argument is the value that is sent to the function when it is called.

Number of Arguments
18
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname +" "+ lname)

my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname +" "+ lname)

my_function("Emil")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is "+ kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python


documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3,child2,child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python


documentations.

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
This way the function will receive a dictionary of arguments, and can access
the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:

19
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Arbitrary Kword Arguments are often shortened to **kwargs in Python


documentations.

Default Parameter Value


The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.
E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.
Example
def myfunction():
pass

20
Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or
ONLY keyword arguments.
To specify that a function can have only positional arguments, add , / after
the arguments:
Example
def my_function(x, /):
print(x)

my_function(3)
Without the , / you are actually allowed to use keyword arguments even if
the function expects positional arguments:
Example
def my_function(x):
print(x)
my_function(x = 3)
But when adding the , / you will get an error if you try to send a keyword
argument:
Example
def my_function(x, /):
print(x)

my_function(x = 3)

Keyword-Only Arguments
To specify that a function can have only keyword arguments,
add *, before the arguments:
Example
def my_function(*, x):
print(x)
my_function(x = 3)
Without the *, you are allowed to use positionale arguments even if the
function expects keyword arguments:
Example
def my_function(x):
print(x)

my_function(3)
But with the *, you will get an error if you try to send a positional argument:
Example
def my_function(*, x):
print(x)

my_function(3)

Combine Positional-Only and Keyword-Only


You can combine the two argument types in the same function.
Any argument before the / , are positional-only, and any
argument after the *, are keyword-only.
Example
def my_function(a, b, /, *, c, d):
print(a + b + c + d)

21
my_function(5, 6, c = 7, d = 8)

Recursion
Python also accepts function recursion, which means a defined function can
call itself.
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.
The developer should be very careful with recursion as it can be quite easy
to slip into writing a function which never terminates, or one that uses
excess amounts of memory or processor power. However, when written
correctly recursion can be a very efficient and mathematically-elegant
approach to programming.
In this example, tri_recursion() is a function that we have defined to call
itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("Recursion Example Results:")


tri_recursion(6)

6.2 String

Strings in python are surrounded by either single quotation marks, or double


quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')

Python - Slicing Strings


You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a
part of the string.
Example
Get the characters from position 2 to position 5 (not included)

22
CHAPTER 7
FILE HANDLING

7.1 File Handling


The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file
does not exist
"a" - Append - Opens a file for appending, creates the file if it does
not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file
exists
In addition you can specify if the file should be handled as binary or
text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do
not need to specify them.
Note: Make sure the file exists, or else you will get an error.

7.2 Python Read file -


Open a File on the Server
Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for
reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file
path, like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

23
Read Only Parts of the File
By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))

7.3 Python Write/Create file

write to an Existing File


To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
ExampleGet your own Python Server
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.

Create a New File


To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")

7.4 Python Delete File

Delete a File

24
To delete a file, you must import the OS module, and run
its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before
you try to delete it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")

25
CHAPTER 8
PYTHON MySQL

8.1 Python MySQL

Python can be used in database applications.


One of the most popular databases is MySQL.

8.2 MySQL Database


To be able to experiment with the code examples in this tutorial,
you should have MySQL installed on your computer.
You can download a MySQL database
at https://www.mysql.com/downloads/.

8.3 Install MySQL Driver

Python needs a MySQL driver to access the MySQL database.


In this tutorial we will use the driver "MySQL Connector".
We recommend that you use PIP to install "MySQL Connector".
PIP is most likely already installed in your Python environment.
Navigate your command line to the location of PIP, and type the
following:
Download and install "MySQL Connector":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>python -m pip install mysql-connector-python
Now you have downloaded and installed a MySQL driver.

Test MySQL Connector


To test if the installation was successful, or if you already have
"MySQL Connector" installed, create a Python page with the
following content:
demo_mysql_test.py:
import mysql.connector
If the above code was executed with no errors, "MySQL Connector"
is installed and ready to be used.

Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database:
demo_mysql_connection.py:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
26
print(mydb)
8.4 Creating a Database
To create a database in MySQL, use the "CREATE DATABASE"
statement:
Example
create a database named "mydatabase":
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

Check if Database Exists


You can check if a database exist by listing all databases in your
system by using the "SHOW DATABASES" statement:
Example
Return a list of your system's databases:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)
Example
Try connecting to the database "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"

8.5 Creating a Table


To create a table in MySQL, use the "CREATE TABLE" statement.
27
Make sure you define the name of the database when you create
the connection
Example
Create a table named "customers":
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name


VARCHAR(255), address VARCHAR(255))")

Check if Table Exists


You can check if a table exist by listing all tables in your database
with the "SHOW TABLES" statement:
Example
Return a list of your system's databases:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)

8.6 MySQL Insert Into Table


To fill a table in MySQL, use the "INSERT INTO" statement.
Example
Insert a record in the "customers" table:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase")
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s,
%s)"
28
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

29
CHAPTER 9
PYTHON MATPLOTLIB
9.1 WHAT IS MATPLOTLIB?
MATPLOTLIB IS A LOW LEVEL GRAPH PLOTTING LIBRARY IN PYTHON THAT SERVES AS A
VISUALIZATION UTILITY.
MATPLOTLIB WAS CREATED BY JOHN D. HUNTER.
MATPLOTLIB IS OPEN SOURCE AND WE CAN USE IT FREELY.
MATPLOTLIB IS MOSTLY WRITTEN IN PYTHON, A FEW SEGMENTS ARE WRITTEN IN C,
OBJECTIVE-C AND JAVASCRIPT FOR PLATFORM COMPATIBILITY.

WHERE IS THE MATPLOTLIB CODEBASE?


THE SOURCE CODE FOR MATPLOTLIB IS LOCATED AT THIS GITHUB
REPOSITORY HTTPS://GITHUB.COM/MATPLOTLIB/MATPLOTLIB

9.2 Installation of Matplotlib


If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy.
Install it using this command:
C:\Users\Your Name>pip install matplotlib
If this command fails, then use a python distribution that already has Matplotlib installed, like Anaconda,
Spyder etc.

Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module statement:
import matplotlib
Now Matplotlib is imported and ready to use:

9.3 Matplotlib Pyplot


Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Example
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()
Result:

30
9.4 Matplotlib Plotting
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the plot
function.
Example
Draw a line in a diagram from position (1, 3) to position (8, 10):
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()
Result:

31
9.5 Matplotlib Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
Example
Mark each point with a circle:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o')
plt.show()

Result:
32
9.6 Matplotlib Line
You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:
Example
Use a dotted line:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()
Result:

33
Example
Use a dashed line:

plt.plot(ypoints, linestyle = 'dashed')

Result:
34
Shorter Syntax
The line style can be written in a shorter syntax:
linestyle can be written as ls.
dotted can be written as :.
dashed can be written as --.
Example
Shorter syntax:
plt.plot(ypoints, ls = ':')

Result:

35
Line Styles
You can choose any of these styles:
Style Or

'solid' (default) '-'

'dotted' ':'

'dashed' '--'

'dashdot' '-.'

'None' '' or ' '

Line Color
You can use the keyword argument color or the shorter c to set the color of the line:
Example
Set the line color to red:
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])


36
plt.plot(ypoints, color = 'r')
plt.show()
Result:

You can also use


Example
Plot with a beautiful green line:
...
plt.plot(ypoints, c = '#4CAF50')
...
Result:

37
Or any of the
Example
Plot with the color named "hotpink":
...
plt.plot(ypoints, c = 'hotpink')
...
Result:

38
Line Width
You can use the keyword argument linewidth or the shorter lw to change the width of the line.
The value is a floating number, in points:
Example
Plot with a 20.5pt wide line:
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linewidth = '20.5')


plt.show()
Result:

39
Multiple Lines
You can plot as many lines as you like by simply adding more plt.plot() functions:
Example
Draw two lines by specifying a plt.plot() function for each line:
import matplotlib.pyplot as plt
import numpy as np

y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])

plt.plot(y1)
plt.plot(y2)

plt.show()
Result:

40
You can also plot many lines by adding the points for the x- and y-axis for each line in the
same plt.plot() function.
(In the examples above we only specified the points on the y-axis, meaning that the points on the x-axis
got the the default values (0, 1, 2, 3).)
The x- and y- values come in pairs:
Example
Draw two lines by specifiyng the x- and y-point values for both lines:
import matplotlib.pyplot as plt
import numpy as np

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])

plt.plot(x1, y1, x2, y2)


plt.show()
Result:

41
42
Conclusion
I believe the trial has shown conclusively that it is both possible and desirable to use Python as the
principal teaching language:

o It is Free (as in both cost and source code).


o It is trivial to install on a Windows PC allowing students to take their interest further. For
many the hurdle of installing a Pascal or C compiler on a Windows machine is either
too expensive or too complicated;

o It is a flexible tool that allows both the teaching of traditional procedural programming
and modern OOP; It can be used to teach a large number of transferable skills;
o It is a real-world programming language that can be and is used in academia and the
commercial world;
o It appears to be quicker to learn and, in combination with its many libraries, this offers
the possibility of more rapid student development allowing the course to be made more
challenging and varied;
and most importantly, its clean syntax offers increased understanding and enjoyment for students

43
Reference

1. Guttag, John V. (12 August 2016). Introduction to Computation and Programming Using Python: With
Application to Understanding Data. MIT Press. ISBN 978-0-262-52962-4.
2. ^ "Python 3.9.2 and 3.8.8 are now available". 19 February 2021. Retrieved 19 February2021.
3. ^ "Python 3.10.0a6 is now available for testing". 1 March 2021. Retrieved 2 March 2021.
4. ^ "Why is Python a dynamic language and also a strongly typed language - Python Wiki". wiki.python.org.
Retrieved 27 January 2021.
5. ^ "PEP 483 -- The Theory of Type Hints". Python.org.
6. ^ File extension .pyo was removed in Python 3.5. See PEP 0488
7. ^ Holth, Moore (30 March 2014). "PEP 0441 -- Improving Python ZIP Application Support". Retrieved 12
November 2015.
8. ^ "Starlark Language". Retrieved 25 May 2019.
9. ^ Jump up to:a b
"Why was Python created in the first place?". General Python FAQ. Python Software
Foundation. Retrieved 22 March 2007.
10. Esterbrook, Charles. "Acknowledgements". cobra-language.com. Cobra Language. Retrieved 7 April 2010.
11. ^ Lattner, Chris (3 June 2014). "Chris Lattner's Homepage". Chris Lattner. Retrieved 3 June 2014. I started
work on the Swift Programming Language in July of 2010^ Kupries, Andreas; Fellows, Donal K. (14
September 2000). "TIP #3: TIP Format". tcl.tk. Tcl Developer Xchange. Retrieved 24 November 2008.
12. ^ Gustafsson, Per; Niskanen, Raimo (29 January 2007). "EEP 1: EEP Purpose and Guidelines". erlang.org.
Retrieved 19 April 2011.
13. ^ "Swift Evolution Process". Swift Programming Language Evolution repository on GitHub. 18 February
2020. Retrieved 27 April 2020.
14.A Practical introduction to Python 3 by Saurabh Dubey Sir .
15.Python Crash Course by UDEMY.
16. Wikipedia (python,udemy).

44

You might also like