Professional Documents
Culture Documents
Loops
In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the
second, and so on. There may be a situation when you need
to execute a block of code several number of times.
A loop statement allows us to execute a statement or group
of statements multiple times.
Python programming language provides following types of
loops:
! while loop
! for loop
! nested loops
2
while Loop Statement
A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.
while expression:!
statement(s)
3
while Loop Statement
count = 0!
while (count < 5):!
print ('The count is:', count)!
count = count + 1!
print ("Good bye!")!
4
for Loop Statement
The for statement in Python has the ability to iterate over
the items of any sequence, such as a list or a string.
5
for Loop Statement
for letter in 'Python':!
# traversal of a string sequence!
print ('Current Letter :', letter)!
print()!
fruits = ['banana', 'apple', 'mango']!
for fruit in fruits:!
# traversal of List sequence!
print ('Current fruit :', fruit)!
print ("Good bye!")
6
for Loop Statement
The built-in function range() is the right function to iterate over a sequence of
numbers. It generates an iterator of arithmetic progressions.
>>> range(5)!
range(0, 5)!
>>> list(range(5))!
[0, 1, 2, 3, 4]!
>>> for var in list(range(5)):print(var)!
0!
1!
2!
3!
4!
>>> for var in (range(5)):print(var)!
0!
1!
2!
3!
4!
7
fruits = ['banana', 'apple', 'mango']!
for index in range(len(fruits)):!
print ('Current fruit :', fruits[index])!
print ("Good bye!")!
8
Nested loops
Python programming language allows to use one loop inside
another loop.
while expression:!
while expression:!
statement(s)!
statement(s)
9
for i in range(1,11):!
for j in range(1,11):!
k=i*j!
print (k, end=' ')!
print()!
1 2 3 4 5 6 7 8 9 10 !
2 4 6 8 10 12 14 16 18 20!
3 6 9 12 15 18 21 24 27 30 !
4 8 12 16 20 24 28 32 36 40 !
5 10 15 20 25 30 35 40 45 50 !
6 12 18 24 30 36 42 48 54 60 !
7 14 21 28 35 42 49 56 63 70 !
8 16 24 32 40 48 56 64 72 80 !
9 18 27 36 45 54 63 72 81 90 !
10 20 30 40 50 60 70 80 90 100
10
Loop Control Statements
Loop control statements change execution from its normal
sequence.
11
break statement
The break statement is used for premature termination of current
loop. After abandoning the loop, execution at the next statement
is resumed:
for letter in 'Python': # First Example!
if letter == 'h':!
break!
print ('Current Letter :', letter)!
12
Using else Statement with Loops
Python supports to have an else statement associated with
a loop statement
If the else statement is used with a for loop, the else block
is executed only if for loops terminates normally (and not
by encountering break statement).
13
Examples
no=int(input('any number: '))!
numbers=[11,33,55,39,55,75,37,21,23,41,13]!
for num in numbers:!
if num==no:!
print ('number found in list')!
break!
else:!
print ('number not found in list')!
14
Examples
numbers=[11,33,55,39,55,75,37,21,23,41,13]!
for num in numbers:!
if num%2==0:!
print ('the list contains an even number')!
break!
else:!
print ('the list does not contain even number')!
15
continue statement
The continue statement in Python returns the control to the beginning of current
loop.
When encountered, the loop starts next iteration without executing remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
16
pass Statement
The pass statement is a null operation; nothing happens
when it executes.
It is used when a statement is required syntactically but you
do not want any command or code to execute.
17
Tema
Construiti o lista format din perechi (nume, varsta) De
exemplu [(Ion, 45), (Dana, 32), ]
Listati sub forma unui tabel:
Nume Varsta
Ion 45
18
>>> lista = [('ion',22), ('vasile',33), ('dan', 67), ('dana',35)]
>>> lista.sort(key = snd)
>>> lista
[('ion', 22), ('vasile', 33), ('dana', 35), ('dan', 67)]
19
Construiti o lista de liste cu elemente de forma [tara, continent,
suprafata, populatie]:
tari = [[Romania, Europa, 250000, 19500000],]
Creati un tabel
Tara Continent Nr. Locuitori
==============================
20
Numbers
Python supports different numerical types:
! int (signed integers): They are often called just integers or
ints, are positive or negative whole numbers with no decimal
point. Integers in Python 3 are of unlimited size. Python 2 has
two integer types - int and long.
! float (floating point real values) : Also called floats, they
represent real numbers and are written with a decimal point
dividing the integer and fractional parts. Floats may also be in
scientific notation, with E or e indicating the power of 10
(2.5e2 = 2.5 x 102 = 250).
! complex (complex numbers) : are of the form a + bJ, where
a and b are floats and J (or j) represents the square root of -1
(which is an imaginary number). The real part of the number
is a, and the imaginary part is b.
21
Numbers
>>> int(7.3)
7
>>> float(99)
9.0
>>> complex(8)
(8+0j)
>>> complex(2,3)
(2+3j)
22
Mathematical Functions
Function Returns ( description )
abs(x) The absolute value of x:
ceil(x) The smallest integer not less than x
exp(x) The exponential of x: ex
fabs(x) The absolute value of x.
floor(x) The largest integer not greater than x
log(x) The natural logarithm of x, for x> 0
log10(x) The base-10 logarithm of x for x> 0 .
max(x1, x2,...) The largest of its arguments
min(x1, x2,...) The smallest of its arguments
modf(x) The fractional and integer parts of x in a
two-item tuple. Both parts have the same sign
as x. The integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point.
Python rounds away from zero as a tie-breaker: round(0.5)
is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0
23
Trigonometric Functions
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
24
>>> max(99,-3,89,453,8)
453
>>> exp(3)
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
exp(3)
NameError: name 'exp' is not defined
>>> math.exp(6)
403.4287934927351
>>> math.pow(7,3)
343.0
>>> math.sqrt(81)
9.0
>>> math.pi
3.141592653589793
>>> math.sin(math.pi/2)
1.0
>>> math.degrees(math.pi/2)
90.0
>>> math.acos(1)
0.0
>>> math.asin(1)
1.5707963267948966
25
Strings
Operator Description
+ Concatenation
* Repetition
[] Slice - Gives the character from the given index
26
String Formatting Operator
>>> print("My name is %s and I am %d years old!" %('George', 35))
My name is George and I am 35 years old!
27
Built-in String Methods
capitalize() Capitalizes first letter of string
28
Built-in String Methods
len(string) Returns the length of the string
29
Built-in String Methods
find(str, beg=0 end=len(string)) Determine if str occurs in
string or in a substring of string if starting index beg and ending index
end are given returns index if found and -1 otherwise.
index(str, beg=0, end=len(string)) Same as find(), but raises
an exception if str not found.
30
Built-in String Methods
isalnum() Returns true if string has at least 1 character
and all characters are alphanumeric and false otherwise.
isalpha() Returns true if string has at least 1 character
and all characters are alphabetic and false otherwise.
isdigit() Returns true if string contains only digits and
false otherwise.
islower() Returns true if string has at least 1 cased
character and all cased characters are in lowercase and false
otherwise.
isupper() Returns true if string has at least one cased
character and all cased characters are in uppercase and false
otherwise.
isnumeric() Returns true if a unicode string
contains only numeric characters and false otherwise.
isspace() Returns true if string contains only whitespace
characters and false otherwise.
31
Built-in String Methods
max(str) Returns the max alphabetical character
from the string str.
min(str) Returns the min alphabetical character
from the string str.
replace(old, new [, max]) Replaces all occurrences of
old in string with new or at most max
occurrences if max given.
rfind(str, beg=0,end=len(string)) Same as find(),
but
search backwards in string.
rindex( str, beg=0, end=len(string)) Same as
index(), but search backwards in string.
32
Lists
Accessing Values in Lists:
! 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])!
Updating Lists:
! list2[2] = 2001!
! list1[1] = 'math'!
Delete List Elements:
! del list1[2]
33
Basic List Operations
34
Indexing, Slicing
L=['C++', 'Java', 'Python']
35
Built-in List Functions
Function Description
>>> [8,5,4,6,3,4,5,6]<=[8,5,4,9]
True
>>> [8,5,4,6,3,4,5,6]==[8,5,4,9]
False
>>> len(list(range(4,19,2)))
8
>>> len([8,5,4,6,3,4,5,6])
8
>>> list((4,3,5,2,8,7))
[4, 3, 5, 2, 8, 7]
36
Methods with Description
list.append(obj) Appends object obj to list
list.count(obj) Returns count of how many times
obj occurs in list
list.extend(seq) Appends the contents of seq to list
>>> aList.count(123) 2
>>> aList.count('zara) 1
37
Methods with Description
list.index(obj) Returns the lowest index in list that obj appears
list.insert(index, obj) Inserts object obj into list at offset index
list.pop(obj=list[-1]) Removes and returns last object or obj
from list
>>> list1.index('chemistry) 1
>>> list1.index('C#) ValueError: 'C#' is not in list
38
Methods with Description
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort([func]) Sorts objects of list, use compare func if given
>>> list1.reverse()
>>> list1 ['maths', 'chemistry', 'Biology', 'physics']
>>> list1.sort()
>>> list1 ['Biology', 'chemistry', 'maths', 'physics']
39
Tuples
tup1 = ('physics', 'chemistry', 1997, 2000)!
tup2 = (1, 2, 3, 4, 5 )!
tup3 = "a", "b", "c", "d!
tup4 = (50,)!
tup5 = ()!
Tuples are immutable which means you cannot update or
change the values of tuple elements.
Removing individual tuple elements is not possible.
To explicitly remove an entire tuple, just use the del
statement.
40
Basic Tuples Operations
Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
41
Indexing, Slicing
T=('C++', 'Java', 'Python')!
42
Built-in Tuple Functions
< , <=, >, >=, ==, !=
43
>>> max((2,4,3,5,4,3))
5
>>> max(2,4,3,5,4,3)
5
>>> (3,4)>(1,2,3)
True
>>> (3,4)!=(1,2,3)
True
>>> tuple([2,3,2,'oo'])
(2, 3, 2, 'oo')
>>> list1= ['maths', 'che', 'phy', 'bio']
>>> tuple1=tuple(list1)
>>> tuple1
('maths', 'che', 'phy', 'bio')
44
Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class:'First'}!
print ("dict['Name']: ", dict['Name'])!
print ("dict['Age']: ", dict['Age'])!
dict['Name']: Zara!
dict['Age']: 7!
KeyError: 'Alice'
45
Updating Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'}!
dict['Age'] = 8 # update existing entry!
dict['Age']: 8!
dict['School']: DPS School
46
Delete Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'}!
47
Properties of Dictionary Keys
Dictionary values have no restrictions.
There are two important points to remember about
dictionary keys:
! no duplicate key is allowed.
! Keys must be immutable. Which means you can use strings,
numbers or tuples as dictionary keys but something like ['key']
is not allowed.
48
Built-in Dictionary Functions
len(dict) Gives the total length of the dictionary.
This would be equal to the number of
items in the dictionary.
49
Methods with Description
d = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
>>> len(d)
3
>>> str(d)
"{'Name': 'Manni', 'Age': 7, 'Class': 'First'}
>>> x=8
>>> type(x)
<class 'int'>
>>> type(d)
<class 'dict'>
50
Methods with Description
dict.clear() Removes all elements of dictionary dict
dict.copy() Returns a shallow copy of dictionary dict
dict.fromkeys() Create a new dictionary with keys from
seq and values set to value.
51
Construiti o agenda telefonica folosind:
1. O lista
2. Un dictionar
52
Methods with Description
dict.items() Returns a list of dict's (key, value)
tuple pairs
dict.keys() Returns list of dictionary dict's keys
53
clear copy
dict = {'Name': 'Zara', 'Age': 7}!
print ("Start Len : %d" % len(dict))!
dict.clear()!
print ("End Len : %d" % len(dict))
Start Len : 2
End Len : 0
54
fromkeys
dict.fromkeys(seq[, value]))
seq -- This is the list of values which would be
used for dictionary keys preparation.!
value -- This is optional, if provided then
value would be set to this value!
55
get
dict.get(key, default=None)
key -- This is the Key to be searched in the dictionary.
default -- This is the Value to be returned in case key does
not exist.
Value : 27!
Value : NO
56
has_key
dict.has_key(key)
key -- This is the Key to be searched in the dictionary.
Value : True!
Value : False
57
items, keys
dict = {'Name': 'Zara', 'Age': 7}!
print ("Value : %s" % dict.items())
58
setdefault
dict.setdefault(key, default=None)
key -- This is the key to be searched.
default -- This is the Value to be returned in case key is not
found.
59
update, values
dict.update(dict2)
dict2 -- This is the dictionary to be added into dict.
60
Python Functions
A function is a block of organized, reusable code that is used to perform a
single, related action.
61
Ex 1
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print (a, end = ' ')
a, b = b, a+b
return
>>> fib(200)
0 1 1 2 3 5 8 13 21 34 55 89 144
>>> fib(3000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1597 2584
>>> fib(15)
0 1 1 2 3 5 8 13
62
Ex 2
def fib2(n):
# return Fibonacci series up to n
"""Return a list of Fibonacci series up to n.""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
63
Lambda Expressions
64
Ex 1
def adun(n):
"""Functia adun(n) returneaza o functie f(x) care aduna n la x"""
return lambda x: x + n
>>> f = adun(9)
>>> g = adun(14)
>>> f(8)
17
>>> g(100)
114
>>> f(0)+g(0)
23
65
Ex 2
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
>>> pairs.sort()
>>> pairs
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
66
Ex 3
>>> amici = [('ion', 32), ('vasile',43), ('dinu', 33), ('dan', 42), ('ana',
22), ('dana', 19)]
>>> a1=amici.sorted()
>>> a2 = sorted(amici, key = lambda pereche:pereche[1])
>>> amici
[('ion', 32), ('vasile', 43), ('dinu', 33), ('dan', 42), ('ana', 22), ('dana',
19)]
>>> a1
[('ana', 22), ('dan', 42), ('dana', 19), ('dinu', 33), ('ion', 32), ('vasile',
43)]
>>> a2
[('dana', 19), ('ana', 22), ('ion', 32), ('dinu', 33), ('dan', 42), ('vasile',
43)]
67