Python U1
Python U1
Python
1
Unit-1
• INTRODUCTION TO PYTHON
• Structure of Python Program-Underlying mechanism of Module Execution-
Branching and Looping-Problem Solving Using Branches and Loops-Functions
- Lists and Mutability- Problem Solving Using Lists and Functions
• Lab Exercises
1. Demonstrate usage of branching and looping statements
2. Demonstrate Recursive functions
3. Demonstrate Lists
2
What is Python?
3
What can Python do?
• Python can be used on a server to create web
applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can also
read and modify files.
• Python can be used to handle big data and perform
complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.
4
Why Python?
6
Structure of Python Program
• a program consists of a set of statements. Each statement can contain one or more
mathematical expressions, and each expression consists of literals, identifiers and
operators.
• Python runs a program by executing its statements, each of which fulfills a specific
functionality.
• The right hand side of = must be an expression, and the left hand side must be an
identifier
• The statement is executed by evaluating the
expression first, and then binding the
resulting object with associating
the left-hand-side identifier.
Understanding the execution of each
type of statement is crucial to the understanding
and design of Python programs.
7
8
9
10
Underlying mechanism of Module Execution
• What is a Module?
A file containing a set of functions you want to include in your application.
• Create a Module
To create a module just save the code you want in a file with the file extension .py
def wel(name):
print("Hello," + name+"welcome to python class")
• Use a Module
Now we can use the module we just created, by using the import statement:
import ex1
11
Module Objects
• an imported module can be accessed by an identifier that bares the same
name of the module
• functions defined in a module can be accessed by using the module name
and the dot (.) operator (i.e. math.e)
• the memory structure after the following three lines of code are executed
>>> x = 1
>>> y =’abc’
>>> import math
12
13
• Python automatically searches for the locations above when a library
module is imported, where the folder names depend on the Python
version. Note that the math module is an exception: it cannot be
found under the library folder locations above.
• This is because math is a very commonly used module, and is built in
the main Python program itself.
• Other commonly used modules, including cmath, are also built-in.
14
The Mechanism of Module Importation
• The import statement creates an identifier that has the same name as
the module.
• For example, by using ‘import random’, ‘random.py’ is imported into
the memory, and associated with the name ‘random’ in the global
binding table.
• To avoid name clashes and for the convenience of reference, a
module can also be given a different name when imported into the
binding table.
• This can be achieved by using a variant of the import statement, with
the syntax ‘import x as y’, where x is the name of the module in the
file system and y is the desired name in the binding table.
15
• The Math Module
• Python has also a built-in module called math, which extends the list of mathematical
functions.
import math
import math
x = math.sqrt(64)
print(x)
x = math.ceil(1.4)
y = math.floor(1.4)
print(x)
print(y)
x = math.pi
print(x)
print(math.isclose(1.233, 1.231))
print(math.isfinite(2000)) 16
Example
❖ In the example above, the math module is loaded into the binding table and associated with the identifier m.
❖ As a result, by using “m.”, the corresponding binding table of the math module can be accessed.
❖ However, the identifier “math” does not exist in the global binding table this time
17
Example
In the example above, x is initially bound to a number, but then rebound to a module.
18
Example
19
• modules such as random.py are Python programs themselves. In fact,
any Python program can be loaded as a module.
• To verify this, the program saving.py can be used as an example.
• Suppose that another source file, textimport.py, is created under the
Desktop folder.
20
Duplicated Imports
• If the same module is imported twice, the content of the module will
not be executed by the second import statement.
21
Importing Specific Identifiers
22
23
24
Python Install
• https://www.python.org/downloads/release/python-3106/
25
Run Python in Immediate mode
26
Run Python in the Integrated Development Environment
(IDE)
• PyCharm
• PyDev
• Spyder
• Thonny
• IDLE
• Wing
• Atom IDE
27
• Python syntax can be executed by writing directly in the Command
Line: >>> print("Hello, World!")
Hello, World!
• Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
if 5 > 2:
print(“Five is greater than two!”)ry it Yourse
• use the same number of spaces in the same block of code, otherwise Python will
give an error 28
Comments
29
Python Variables
31
• Single or Double Quotes?
• String variables can be declared either by using single or double
quotes:
• x = "John"
# is the same as
x = 'John’
• Variable names are case-sensitive.
• a = 4
A = "Sally"
#A will not overwrite a
• Variable Names
• A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables: A
variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three
different variables) 32
Multi Words Variable Names
33
Assign Multiple Values
35
• when combine a string and a number with the +
operator , an error is occurred
•x = 5
y = "John"
print(x + y)
• The best way to output multiple variables in the print()
function is to separate them with commas, which even
support different data types
•x = 5
y = "John"
print(x, y)
36
Global Variables
37
Built-in Data Types
38
Keywords
39
Strings
• quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars." 42
Boolean Values
In programming you often need to know if an expression is True or False.
Evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)
43
Python Operators
44
Arithmetic Operators
45
Assignment operators
== Equal x == y
!= Not equal x != y
47
Logical operators
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
48
Python Identity Operators
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall
shift off
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
shift the rightmost bits fall off
50
51
52
53
54
55
56
Execution-Branching and Looping
57
Python Conditions and If statements
58
• These conditions can be used in several ways, most
commonly in "if statements" and loops.
• An "if statement" is written by using the if keyword.
• Example
• If statement:
if <condition>:
print()
a = 33
b = 200
if b > a:
print("b is greater than a")
59
• Elif
• The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".
if <condition1>:
print()
elif <condition2>:
print()
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
60
Else
• The else keyword catches anything which isn't caught by the
preceding conditions.
if <condition1>:
print()
elif <condition2>:
print()
else:
print()
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
62
Short Hand If ... Else
• If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line:
Example
• One line if else statement:
•a = 2
b = 330
print("A") if a > b else print("B")
• This technique is known as Ternary Operators,
or Conditional Expressions.
63
• lso have multiple else statements on the same line:
• Example
• One line if else statement, with 3 conditions:
• a = 330
b = 330
print("A") if a > b else print("=") if a ==
b else print("B")
64
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
65
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
66
Nested If
• have if statements inside if statements, this is called nested if statements.
Example
• x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
67
The pass Statement
• if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
• Example
a = 33
b = 200
if b > a:
pass
68
Python Loops
• while loops
• for loops
69
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Initialization
while <condition>:
print()
<increment or decrement >
Example
• Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while condition is true:
Example
• Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
71
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
72
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
• Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
73
Python For Loops
75
The break Statement
With the break statement we can stop the loop before it has looped through all
the items:
Example
• Exit the loop when x is "banana":
77
The range() Function
• To loop through a set of code a specified number of
times, we can use the range() function,
• The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the
values 0 to 5.
78
• The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values
from 2 to 6 (but not including 6):
• Example
• Using the start parameter:
• for x in range(2, 6):
print(x)
79
• The range() function defaults to increment the sequence
by 1, however it is possible to specify the increment value
by adding a third parameter: range(2, 30, 3):
• Example
• Increment the sequence with 3 (default is 1):
• for x in range(2, 30, 3):
print(x)
• Try it Yourself »
80
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has
ended:
for x in range(6):
print(x)
else:
print("Finally finished!") 81
• The else block will NOT be executed if the loop is stopped by a break statement.
• Example
• Break the loop when x is 3, and see what happens with the else block:
• for x in range(6):
• if x == 3: break
• print(x)
• else:
• print("Finally finished!")
82
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each
iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
83
The pass Statement
• for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
84
Python Collections (Arrays)
• There are four collection data types in the Python programming
language:
• List is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable.
No duplicate members.
• *Set items are unchangeable, but you can remove and/or add
items whenever you like.
• **As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered. 85
List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
• Lists are ordered, it means that the items have a defined order,
and that order will not change.
• If you add new items to a list, the new items will be placed at
the end of the list.
Changeable
• The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created. 86
Python Lists
88
Allow Duplicates
• Since lists are indexed, lists can have items with the same value:
Example
• Lists allow duplicate values:
89
List Length
• To determine how many items a list has, use the len() function:
Example
#Print the number of items in the list:
• It is also possible to use the list() constructor when creating a new list.
Example
• Using the list() constructor to make a List:
92
Access List Items
• List items are indexed and you can access them by
referring to the index number:
Example
• Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
• The first item has index 0.
93
Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last item etc.
Example
• Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
• specify a range of indexes by specifying where to start and where to end the range.
• When specifying a range, the return value will be a new list with the specified items.
Example
• Return the third, fourth, and fifth item:
The search will start at index 2 (included) and end at index 5 (not included) 94
• By leaving out the start value, the range will start at the first item:
Example
• This example returns the items from the beginning to, but NOT
including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
• By leaving out the end value, the range will go on to the end of the list:
Example
• This example returns the items from "cherry" to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
95
Range of Negative Indexes
• Specify negative indexes if you want to start the search from the
end of the list:
Example
• This example returns the items from "orange" (-4) to, but NOT
including "mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
96
Check if Item Exists
Example
if "apple" in thislist:
Example
• If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
• Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist) 99
• If you insert less items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:
Example
• Change the second and third value by replacing it with one
value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
100
Python - Add List Items
Append Items
• To add an item to the end of the list, use the append() method:
Example
• Using the append() method to append an item:
Insert Items
✔ To insert a list item at a specified index, use the insert() method.
✔ The insert() method inserts an item at the specified index:
Example
✔ Insert an item as the second position:
102
Add Any Iterable
• The extend() method does not have to append lists, you can add any
iterable object (tuples, sets, dictionaries etc.).
Example
• Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
103
Python - Remove List Items
Remove Specified Item
• The remove() method removes the specified item.
Example
• Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
105
Python - Loop Lists
106
Loop Through the Index Numbers
• Also use loop through the list items by referring to their index number.
• Use the range() and len() functions to create a suitable iterable.
Example
• Print all items by referring to their index number:
107
Using a While Loop
• loop through the list items by using a while loop.
• Use the len() function to determine the length of the list, then start at 0 and
loop your way through the list items by referring to their indexes.
• Remember to increase the index by 1 after each iteration.
Example
• Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
108
List Comprehension
✔ List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Example:
✔ Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
✔ Without list comprehension you will have to write a for statement with a conditional test
inside:
✔ Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
109
Looping Using List Comprehension
• List Comprehension offers the shortest syntax for looping through lists:
• Example
• A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
With list comprehension you can do all that with only one line of code:
• Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
110
The Syntax
• newlist = [expression for item in iterable if condition == True]
• The return value is a new list, leaving the old list unchanged.
Condition
• The condition is like a filter that only accepts the items that valuate to
True.
Example
• Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
111
• The condition if x != "apple" will return True for all elements other than "apple",
making the new list contain all fruits except "apple".
• The condition is optional and can be omitted:
Example
• With no if statement:
newlist = [x for x in fruits]
✔ Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Example
✔ You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
Example
112
newlist = [x for x in range(10) if x < 5]
Expression
• The expression is the current item in the iteration, but it
is also the outcome, which you can manipulate before it
ends up like a list item in the new list:
Example
• Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]
print(newlist)
Example
• Set all values in the new list to 'hello':
newlist = ['hello' for x in fruits]
print(newlist)
113
• The expression can also contain conditions, not like a filter, but
as a way to manipulate the outcome:
Example
• Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]
114
Python - Sort Lists
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default
num = [100, 50, 65, 82, 23]
num.sort()
print(num)
str = ["orange", "mango", "kiwi", "pineapple", "banana"]
str.sort()
print(str)
• To sort descending, use the keyword argument reverse = True
115
Reverse Order
• The reverse() method reverses the current sorting order of the
elements.
• Example
• Reverse the order of the list items:
L = ["banana", "Orange", "Kiwi", "cherry"]
L.reverse()
print(L)
116
Copy a List
• There are ways to make a copy, one way is to use the built-in List
method copy()
L1 = ["mon", "tue", "wed"]
n1 = L1.copy()
print(n1)
117
Repetition of lists
>>>x=[1,2]
>>>print(x*3)
[1, 2, 1, 2, 1, 2]
118
Python Functions
my_function("Emil")
my_function("Tobias")
121
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.
122
Number of Arguments
• 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:
my_function("Emil", "Refsnes")
✔ If you try to call the function with 1 or 3 arguments, you will get an error:
123
Arbitrary Arguments, *args
• If do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
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])
adder(10,12,13)
sum: 35
Ex:
def adder(x,y,z):
print("sum:",x+y+z)
adder(5,10,15,20,25)
125
Example *args
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
126
Keyword Arguments
127
Arbitrary Keyword Arguments, **kwargs
✔ If 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:
def my_function(**kid):
print("His last name is " + kid["lname"])
129
def myFun(args,**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
130
• *args and **kwargs are special keyword which allows function to take
variable length argument.
• *args passes variable number of non-keyworded arguments and on
which operation of the tuple can be performed.
• **kwargs passes variable number of keyword arguments dictionary to
function on which operation of a dictionary can be performed.
• *args and **kwargs make the function flexible.
131
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")
132
Passing a List as an Argument
✔ 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)
my_function(fruits)
133
Return Values
• Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
134
def num(x):
if x>0:
return "positive"
elif x<0:
return "negative"
else:
return "zero"
print(num(-4))
135
def odd(n):
for i in n:
if i%2==1:
return i
print(odd((1,2,3)))
136
def odd(n):
s=[]
for i in n:
if i%2==1:
s.append(i)
return s
print(odd((1,2,3)))
137
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
138
Recursion
❖Python also accepts function recursion, which means a defined function can call itself.
❖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.
139
140
141
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
• Recursive functions are hard to debug.
144
Python programs in Recursive
• Factorial
• Fibonacci series
145
recursion to find out the sum of numbers from 1 to n like 1 + 2 + 3 + 4 +, etc.
def sumnums(n):
if n == 1:
return 1
return n + sumnums(n - 1)
print(sumnums(3))
print(sumnums(6))
print(sumnums(9))
146
Function Definition Using lambda
expressions
• f (x, y) = x+2y. The function takes two number arguments, and returns
their weighted sum. The name of the function is f .
• Python provides a simple type of expression, the lambda expression,
for the definition of such a function
147
148
149
150
• An argument that is explicitly assigned in a function call is called a
keyword argument.
151
The Dynamic Execution Process of Function Calls
def f1():
print("function1")
f2()
def f2():
print("function2")
f3()
def f3():
print("function3")
f1()
152
Identifier Scopes
• Identifier scope refers to the accessibility of identifiers in different
parts of Python code; it is an important concept related to functions.
• For a simple example of the concept of scopes, consider the
accessibility of identifiers from a function body.
• Statements defined in a function can contain references to identifiers
defined outside the function
• Global scope and local scope. Top-level statements in IDLE or a Python
program being executed form the global scope, while statements
inside a function body being executed form a local scope.
153
x = "global"
def scope():
x="local"
print("x inside:", x)
scope()
print("x outside:", x)
154