Python Manual
Python Manual
➢ Hardware
o Processor
o Memory
o I/O units
➢ How does it work?
Components of a computer:
• Machine language
• Assembler language
iload intRate
bipush 100
if_icmpgt intError
Programs:
The programs characterize what a computer actually does.
A program (independently of the language in which it is written) is constituted by two fundamental parts:
• a description of how to manipulate the representation in such a way as to realize the desired
functionality: operations
We want to realize a program for a call-center that handles requests for telephone numbers.
Specifically, a certain client requests the telephone number associated to a certain person name in a
certain city, and the operator answers to the request by selecting the telephone registry of the city
and searching there the telephone number corresponding to the person name.
Objects:
– Client
– Operator
– Telephone registry – telephone numbers, person names, cities - these are just character
sequences (strings)
Operations:
• 1. request for the telephone number of a given person name in a given city, done by a client
• 2. selection of the telephone registry of the requested city, done by the operator
• 3. Search of the telephone number corresponding to the requested person name on the telephone
registry.
The program has to represent all objects that come into play and realize all operations.
Realization of operations:
Algorithms usually, we realize an operation when we need to solve a specific problem.
Example: given a person name, find the corresponding telephone number in a telephone registry. To
delegate to a computer the solution of a problem, it is necessary to find an algorithm that solves the
problem.
Algorithm:
Procedure is through which we obtain the solution of a problem. In other words, a sequence of
statements that, when executed one after the other, allow one to calculate the solution of the
problem starting from the information provided as input.
Example of an algorithm:
Scan the person names, one after the other as they appear in the registry, until you have found the
requested one; return the associated telephone number.
Using Python:
Python is commonly used for developing websites and software, task automation, data analysis, and data
visualization. Since it's relatively easy to learn, Python has been adopted by many non-programmers such as
accountants and scientists, for a variety of everyday tasks, like organizing finances.
Designing a program
Program design consists of the steps a programmer should do before they start coding the program
in a specific language.
• Design the program
• Processing
• Outputs
This IPO approach involves what the user must enter on the keyboard and what processing or
manipulations will be done.
Input, processing, and output
❑ Input:
Comment
Comment: notes of explanation within a program
o Ignored by python interpreter
Variables
• Variable: name that represents a value stored in the computer memory
• Example: age=18
Arithmetic Operator(s):
Python uses the following symbols (operators) in calculations:
+ Addition
- Subtraction
* Multiplication
/ Division
The order of operations (also called precedence rules) defines how an expression is to be evaluated.
Multiplication is granted higher precedence than addition. Thus, the expression 2 + 3 * 4 is
interpreted to have the value 2 + (3 * 4) = 14
So the rule is that unless we use brackets the multiplication and division precedes addition and
subtraction.
Read carefully the next 2 examples that demonstrate the syntax of Python arithmetic expressions:
a = 4
b = 2
x = (a + b) “ (a — b)
print(“Value of x: “, x)
Example 5:
Example 6:
a=4
b = a/2
c = (a + b) “ (a — b)
d=a+b“a—b
x = c —d
print(“Value of x: “, x)
Modulus operator
The modulus operator (%) returns the division remainder. For instance, when we divide 10/3 the
remainder is 1. When we divide 10/5 the remainder is 0. As you can see the modulus operator is used
to find if a number is divisible by another number.
Example 7:
a = 17
b = 5
c = a % b
There are two numeric types in Python (there are also complex numbers which we will not
discuss):
int
float
int - they are called just integers or ints, are positive or negative whole numbers with no decimal
point.
float - they are called floats, they represent real numbers and are written with a decimal point
dividing the integer and decimal parts.
Example:
X 11 # integer
Y 3.14 # float
we can convert from one type to another with the int(), and float() functions.
Examples:
x 1 # assign int number
y 2.8 # assign float number
Python converts numbers to strings through using the str() function. We’ll pass either a
number or a variable into the str() function, and, then that numeric value will be converted
into a string value.
Let’s first look at converting integers. To convert the integer 12 to a string value, you just pass 12
into the str() function:
We also can use str() function to convert float numbers or float variables into a string:
a = "alpha"
b = "bet:"
c=a + b
Here is another instance of concatenation. Note the use of a single character string " " used
to create a space between the firstName and familyName
firstname = "John"
familyname="Harris"
# (see the extra space)
fullname = firstname + " " + familyname
Print function:
Function print()
The print() function prints the specified message to the screen. The message can be a string, or
any other variable, the variable will be converted into a string before written to the screen.
Simple use of print() function.
Strings are enclosed in double quotes:
Example 1:
a = 1000
b = 2000
c = 3000
pri nt (a)
print (b)
print (c)
Example 3:
The program will output: 10 0
0
20 00
30 0 0
In contrast, this example ends each line with a comma character (except the last print() statement):
a = 1000
b = 2000
c = 3000
print (a , end=" ,")
print (b , end=" , ")
print (c)
Example 4:
Logical operators:
Python logical & comparison operators
Let’s recall the comparison and logical operators that were described in Python Primer:
a =0
b =a + l
if a > 0 or b > 0:
a= a + l
b=b+ l
1 f a > 0 and b > 0 :
a= a + l
b=b+ l
x=a+b
p rint: ("value of x:”,x)
Output:
Value of x: 5
If — else Statement, if-elif-else Statements
The if-else statement executes a block of code if a specified condition is true. If the condition is
false, another block of code is executed. Let’s explore the following code:
Example 1:
a =2
b =2
if a > b:
a = a * 2
b = b *2
else:
a = a + 1
b = b + 1
x = a +b
print(“Value of x: “, x)
if conditionl:
code to be executed if this condition is true;
elif condition2:
code to be executed if the first condition is false and this condition is true;
else:
code to be executed if all conditions arefalse; Here is a simple
number =
-1 msg =
"
if number > 0:
msg = "Number is
positive" exif number‹
0:
msg = "Number is
negative" else:
msg = "Number is 0"
print(msg)
Boolean can have only two values, True or False (the first letter must be capitalized). Let’s
explore how to use Boolean variables to control program flow using conditional statements. In the
following example it should be obvious that the block after the ‘if’ statement will be executed as
the condition is true.
Example 1
Output:
Value of x: 1
Let’s slightly modify the previous code:
Example 2
a =0
b = a >= 0 # the result of this comparison is True
if b:
a=a+1
x=a
print("value of x: " , x)
Output:
Value of x: 1
Let’s continue with further modifications: notice in the next example the test of two Boolean
values in the ‘if’ statement.
Example 3
Output:
Value of x: 1
While condition:
# execute code as long as condition is true
The while statement is the most basic loop construct in Python.
Example 1
n=0
while n < 2 :
n=n+1
x= n
print("value of x: ", x)
The next example prints all odd numbers between <1, 10>. Note that the ‘if’ statement that determines whether
a number is odd or even (if the remainder of division by 2 is not zero then by definition the number is odd).
n = 1
while n <= 10:
if n%2 != 0:
print(n, is an odd number")
n=n+1
Example 3
Output:
1 is an odd number
3 is an odd number
5 is an odd number
7 is an odd number
9 is an odd number
Break Keyword used in the while loop:
The break keyword is used to brea k out the loop. In the next example the while loop ends when
the condition (i > 5) is true
Infinite Loops:
Working with while, loops present a challenge: a coding error can cause an infinite
loop. Infinite loop, as the name suggests, is a loop that will keep running forever. If
you accidentally make an infinite loop, it could crash your Python
interpreter.
Example 1
n = 0
for i in range(0, 2, 1):
n = n + 10
x= n
print("value of x: ", x)
Looking at the above example you might think that (range) is part of the (for loop) syntax. It is not. Range() is
a Python function which returns a sequence of integer numbers which in turn allows the for loop to iterate
over. Since range creates a fixed length list the for loop runs for a fixed number of iteration.
start isan integer number specifying at which position to start stopisan integer number specifying at which
position toend. step is an integer number specifying the incrimination.
It is very important to note that the sequence ends before the value (stop) is reached, in other words,
range() function generate numbers up to, but not including (stop) number
examples
Furthermore, values (start) and (step) are optional. Default for (start) is 0 and the default for (step) is 1. This
means that the following range definition:
range(0,10,1)
In the context of the for loop these two statements are identical
Example 2
Output:
1 is an odd number
3 is an odd number
5 is an oddnumber
7 is an odd number
9 is an odd number
Let’s modify the above code — just iterate using odd numbers sequence (it will produce an identical output):
Example 3
a = range (l , 10, 2)
for n in a:
print(n, " is an odd number")
Example4
We’ve already learned that the while loop can be terminated by the break keyword. The same
functionality applies for the “for loop” as the next example shows:
Introductions to functions:
A Python function is a block of code designed to perform a particular task. A function is defined
with the (def) keyword, followed by a name (’maxnum’ in our example), followed by parentheses
(). A colon is used to specify the start of the function code.
Important Rule:
Make sure that your function is declared before it is needed(called). Note that the body of
a function isn’t interpreted until the function is executed. HoweVer, the functions can be
defined in any order, as long as all are defined before any executable code uses a
function. So let’s repeat:
The rule: All functions must be defined before any code that does real work
When we talk about functions, the terms “parameters” and “arguments” are often
interchangeably used as if it were one and the same thing but there is a very subtle difference:
a)
Parameters are variables listed as a part of the function definition.
b)
Arguments are values passed to the function when it is invoked.
Note that the function defines variable r. This variable exists inside the function ‘maxnum’. For
other functions this variable is invisible. The technical term for this feature is called scope. It
means that the variable r has only a local scope. Local scope means: within the scope of the
function ‘maxnum’. If we define variables outside of any function then the scope of such a
variable is global. This means: anywhere in our program a global variable can be accessed and
modified.
It is very important to grasp the distinction between local and global variables. Therefore let’s
re-state this again:
If this statement is defined inside a function body the scope (or the visibility) of this
declaration/assignment is limited to the body of the function. However, if this
statement is placed outside of any function then the scope of defined variables is gl obal.
It is not a good coding technique to use global variables as it leads to many problems.
An experienced programmer can use under certain conditions global variables; Python
certainly allows that. But for our purposes, we will avoid using global variables!
To repeat one more time: the scope refers to the visibility of variables. This means which parts of
your program can see or use it. The coding technique implemented in this course limits a
variable’s scope to a single function.
How is this done? Let’s explore the next example, which is going to be a template for all our
examples:
def
someFunction()
: some code
here .
# end of someFunction()
main()
What you see is a call to function main (at the very end of the program sequence) which passes
the code execution to the body of the function main. In other words, all action happens inside the
body of the function main. Other functions are called directly or indirectly from the main
function. This style ensures that all variables
have a local scope - which is our objective. This seemingly unnecessary complication of enclosing
all Python code in one or several functions guarantees the reliability of our code.
Remember we’ve established a rule for ordering the functions stated like this: the functions
can be defined in any order, as long as all are defined before any executable code
uses a function.
The presented template puts the executable code in one line of code - main() which must be
placed as the very last statement! Let’s demonstrate this using the following example:
# Python program that does NOT use global variables def main
() :
a = 10
b = 20
x = maxnum(a, b)
p ri nt(”Val ue of x: ” , x)
# end of main()
def maxnum(a, b):
r=a
if r < b:
r = b
return r
# end of maxnum()
# call to the 'main' function MUST BE THE LAST statement
main()
Example 1
List:
What is a list? A list is a special variable, which can hold more than one value at a time. Let’s say we have a list of
numbers. Storing them in single variables would look like this:
numberl 200
number2 300
number3 400
But if we wanted to use a loop to find a specific number, that would be difficult — especially for large set of
numbers. The solution is to use a list. The list can hold many values under a single name, and you can access the
values by referring to an index number:
myList [200, 300, 400]
Python (as most modern languages) uses so-called zero-based indexing. This is extremely important! Let’s
remember and repeat:
[0] the index of the first element
[1] the index of the second element
if the list length is defined as len then [Ien-1] is the index of the last element
informally lists and arrays are treated as identical concepts. However, Python does make a distinction between lists
and arrays (although they are very similar).
However, we will not discuss the concept of Python arrays in this manual.
Creating a list
Syntax:
listName [iteml, item2, .]
Example :
numbers = [200, 300, 400] # this list has 3 elements
Access the Elements of a list
You access a list element by referring to the index number. This statement accesses the value of the first
element in ‘numbers’:
someVariable = numbers[0] # the first element
Example defines and initiates a list. Consequently, list elements are assigned random values:
List Functions
Add a new item to a list — append():
Function append adds an element to the end of the list
fruits = [] # let begin with an empty list fruits.append("Apple") # sets fruits[0] to "Apple"
fruits.append("Mango") # sets fruits[1] to "Mango"
It should be self-evident that after ‘append’ is executed the list length is incremented by 1.
Delete last element from list — pop()
Function pop removes the last element of a list; the list length drops by 1
fruits ["Orange", "Lemon", "Avocado"]
fruits.pop() # Removes the last element ("Avocado") from list
Delete an element from a list by index using del operator
The del operator removes an element at the specified index location from the list. Example:
Example:
Remove all elements from a list — clear() function The clear() function removes all the elements from a
list.
Syntax
listName.clear()
Example:
Suppose you need to construct a loop that will iterate over all list elements. We know how to do it using the
function range():
Output:
10 0
20 0
300
However, Python allows to loop through all the elements of a list. The previous example could be rewritten
(and simplified) as the following (producing identical output):
example 3
a)
we’ve already seen the simplest possible way:
a [1, 2, 3, 4, 5]
print(a)
b)
print a list using a loop
a [1, 2, 3, 4, 5]
for y in a:
print(y)
c)
print a list using a loop and make the output a single line (no line breaks):
a [1, 2, 3, 4, 5]
for y in a:
print(y, end=" ")
a = 0.15 + 0.15
b = 0.1 + 0.2
i f a == b:
print(”Values a and b are equal ”) e1se:
print(”Val ues a and b are NOT equal ”)
Example 1
Output:
Values a and b are NOT equal
Merge Lists:
Merge algorithm takes two sorted lists as input and produce a single list as output, containing
all the elements of both input lists in sorted order.
Input Lists:
listl = [1, 3, 4, 5]
list2 = [2, 4, 6, 8]
Multi-line statements:
You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the
backslash ( \ ) to indicate that a statement is continued on the next line. For example this
statement:
a 5 6 7
could be re-written as the following: (note the backslash characters at the end of lines):
a 5 \
6 \
7
Input-Output in Python
Python provides some built-in functions to perform both input and output operations.
In order to print the output, python provides us with a built-in function called print().
Example:
Print(“Hello Python”)
Output:
Hello Python
Files in Python
A file is a named location on the disk which is used to store the data permanently.
Here are some of the operations which you can perform on files:
• open a file
• read file
Variables in Python:
Unlike other programming languages, Python has no command for declaring a variable. A
variable is created the moment you first assign a value to it:
a = 100
This means: variable (a) has been created and assigned value 100.
Python tuple :
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-
in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage. A tuple is a collection which is
ordered and unchangeable. Tuples are written with round brackets
• Unchangeable
• Ordered
• Allow duplicates
Tuple Length
To determine how many items a tuple has, use the len() function:
Dictionaries:
Dictionaries are used to store data values in key: value pairs. A dictionary is a
collection which is ordered*, changeable and do not allow duplicates. Dictionaries
are written with curly brackets, and have keys and values:
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.Dictionary
items are presented in key: value pairs, and can be referred to by using the key
name.
• Ordered
• Changeable
Ford
Python sets
Sets are used to store multiple items in a single variable. Set is one of 4 built-in
data types in Python used to store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage. A set is a collection which
is unordered, unchangeable*, and unindexed. Sets are written with curly brackets.
Output
{Cherry,banana,apple}
Python turtle graphics
turtle is a pre-installed Python library that enables users to create pictures and
shapes by providing them with a virtual canvas. The onscreen pen that you use for
drawing is called the turtle and this is what gives the library its name. In short, the
Python turtle library helps new programmers get a feel for what programming with
Python is like in a fun and interactive way.
With the Python turtle library, you can draw and create various types of shapes and
images. Here’s a sample of the kinds of drawings you can make with turtle:
• Forward
• Backward
• Left
• Right
The turtle moves .forward() or .backward() in the direction that it’s facing. You can
change this direction by turning it .left() or .right() by a certain degree. You can
try each of these commands like so:
Output