PYTHON REPOT Final Master - Removed - PDF Print Final
PYTHON REPOT Final Master - Removed - PDF Print Final
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.
• 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.
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.
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
“C:\Python27\;C:\Python27\Scripts;”
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
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,
9
CHAPTER 3
DATA TYPES & OPERATOR
(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.
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
/ 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.
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain
'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0] print
When the above code is executed, it produces the following result − tup1[0]:
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 −
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.
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value
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]
13
Python Expression Results Description
14
5 list(seq) Converts a tuple into list.
15
CHAPTER 5
LOOPS & CONDITIONAL STATEMENTS
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
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
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
my_function("Emil")
my_function("Tobias")
my_function("Linus")
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")
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")
19
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
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))
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)
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
6.2 String
22
CHAPTER 7
FILE HANDLING
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.
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))
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")
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
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()
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"
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
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)
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.
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:
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
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:
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
'dotted' ':'
'dashed' '--'
'dashdot' '-.'
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
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
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])
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 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