Download for Loop Statement

Document related concepts
no text concepts found
Transcript
2
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)
•  Here, statement(s) may be a single statement or a block of
statements with uniform indent. The condition may be any
expression, and true is any non-zero value. The loop
iterates while the condition is true.
•  When the condition becomes false, program control passes
to the line immediately following the loop.
3
while Loop Statement
count = 0!
while (count < 5):!
print ('The count is:', count)!
count = count + 1!
print ("Good bye!")!
The count
The count
The count
The count
The count
Good bye!
is:
is:
is:
is:
is:
0!
1!
2!
3!
4!
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.
for iterating_var in sequence:!
statements(s)
•  if a sequence contains an expression list, it is evaluated
first. Then, the first item in the sequence is assigned to the
iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var,
and the statement(s) block is executed until the entire
sequence is exhausted.
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!")!
Current fruit : banana!
Current fruit : apple!
Current fruit : mango!
Good bye!
8
Nested loops
•  Python programming language allows to use one loop inside
another loop.
for iterating_var in sequence:!
for iterating_var in sequence:!
statements(s)!
statements(s)!
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.
•  When execution leaves a scope, all automatic objects that
were created in that scope are destroyed.
•  Python supports the following control statements:
!  break statement
!  continue statement
!  pass statement
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)!
var = 10
# Second Example!
while var > 0:!
print ('Current variable value :', var)!
var = var -1!
if var == 5:!
break!
print ("Good bye!")
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).
•  If the else statement is used with a while loop, the else
statement is executed when the condition becomes false.
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')!
any number: 33!
number found in list!
any number: 22!
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')!
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.
for letter in 'Python':
# First Example!
if letter == 'h':!
continue!
print ('Current Letter :', letter)!
var = 10
# Second Example!
while var > 0:!
var = var -1!
if var == 5:!
continue!
print ('Current variable value :', var)!
print ("Good bye!")
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.
for letter in 'Python':!
if letter == 'h':!
pass!
print ('This is pass block')!
print ('Current Letter :', letter)!
print ("Good bye!")
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
• 
• 
• 
• 
Listați toate persoanele sub 35 ani
Listati toate persoanele care incep cu litera D
Listati toate persoanele cuprinse intre 45 si 55 ani
Listati sub forma de tabel, toate persoanele in ordine
alfabetică (folsiti metoda sort: lista.sort() )
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
==============================
•  Listati tarile dintr-un anumit continent
•  Listati tarile cu populatie mai mare decat 15000000 locuitori
•  Creati un tabel cu:
Continentul
Europa
Asia
…
Nr. Total de 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)
•  It is possible to represent integer in hexa-decimal or octal form:
>>> number = 0xA0F #Hexa-decimal!
>>> number!
2575!
>>> number=0o37 #Octal!
>>> number!
31!
22
Mathematical Functions
Function
abs(x)
ceil(x)
exp(x)
fabs(x)
floor(x)
log(x)
log10(x)
max(x1, x2,...)
min(x1, x2,...)
modf(x)
pow(x, y)
round(x [,n])
sqrt(x)
Returns ( description )
The absolute value of x:
The smallest integer not less than x
The exponential of x: ex
The absolute value of x.
The largest integer not greater than x
The natural logarithm of x, for x> 0
The base-10 logarithm of x for x> 0 .
The largest of its arguments
The smallest of its arguments
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.
The value of x**y.
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.
The square root of x for x > 0
23
Trigonometric Functions
Function
acos(x)
asin(x)
atan(x)
atan2(y, x)
cos(x)
hypot(x, y)
sin(x)
tan(x)
degrees(x)
radians(x)
Description
Return the arc cosine of x, in radians.
Return the arc sine of x, in radians.
Return the arc tangent of x, in radians.
Return atan(y / x), in radians.
Return the cosine of x radians.
Return the Euclidean norm, sqrt(x*x + y*y).
Return the sine of x radians.
Return the tangent of x radians.
Converts angle x from radians to degrees.
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
[:]
Range Slice - Gives the characters from
the given range
Membership - Returns true if a character
exists in the given string
Membership - Returns true if a character
does not exist in the given string
in
not in
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!
Format Symbol
%c
%s
%i
%d
%u
%o
%x
%X
%e
%E
%f
%g
%G
Conversion
character
string conversion via str() prior to formatting
signed decimal integer
signed decimal integer
unsigned decimal integer
octal integer
hexadecimal integer (lowercase letters)
hexadecimal integer (UPPERcase letters)
exponential notation (with lowercase 'e')
exponential notation (with UPPERcase 'E')
floating point real number
the shorter of %f and %e
the shorter of %f and %E
27
Built-in String Methods
•  capitalize()
Capitalizes first letter of string
>>> str = "this is string example!"
>>> print ("str.capitalize() : ", str.capitalize())
str.capitalize() : This is string example!
•  center(width, fillchar)
Returns a string padded with
fillchar with the original string centered to a total of width
columns.
>>> print ("str.center(40, ‘*') : ", str.center(40, '*'))
str.center(40, ‘*') : ********this is string example!*********
28
Built-in String Methods
•  len(string)
Returns the length of the string
•  count(str, beg= 0,end=len(string))
Counts how
many times str occurs in string or in a substring of string if
starting index beg and ending index end are given.
>>> str = "this is string example!”
>>> sub = 'i'
>>> print ("str.count('i') : ", str.count(sub))
str.count('i') : 3
>>> sub = 'exam'
>>> print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))
str.count('exam', 10, 40) : 1
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.
>>> print (str.find('exam'))
15
>>> print (str.find('exam',10))
15
>>> print (str.find('exam',40))
-1
>>> print (str.index('exam',10))
15
>>> print (str.index('exam',40))
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
print (str.index('exam',40))
ValueError: substring 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
list2
print
print
= ['physics', 'chemistry', 1997, 2000]!
= [1, 2, 3, 4, 5, 6, 7 ]!
("list1[0]: ", list1[0])!
("list2[1:5]: ", list2[1:5])!
•  Updating Lists:
!  list2[2] = 2001!
!  list1[1] = 'math'!
•  Delete List Elements:
!  del list1[2]
33
Basic List Operations
Python Expression
len([1, 2, 3])
[1, 2, 3] + [4, 5, 6]
Results
3
[1, 2, 3, 4, 5, 6]
['Hi!'] * 4
3 in [1, 2, 3]
for x in [1,2,3] :
print (x,end=' ')
['Hi!', 'Hi!', 'Hi!', 'Hi!’] Repetition
True
Membership
123
Description
Length
Concatenation
Iteration
34
Indexing, Slicing
L=['C++', 'Java', 'Python']
Python Expression
L[2]
L[-2]
L[1:]
L[:-1]
L[-1:]
L[-3:-1]
L[-3:]
L[1][2]
L[2][2]
Results
'Python’
'Java’
['Java', 'Python']
['C++', 'Java']
['Python']
['C++', 'Java']
['C++', 'Java', 'Python']
'v’
't'
35
Built-in List Functions
Function
<, <=, >, >=, ==
len(list)
list(seq)
Description
Compares elements of both lists.
Gives the total length of the list.
Converts a tuple into list
>>> [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)
•  list.count(obj)
•  list.extend(seq)
Appends object obj to list
Returns count of how many times
obj occurs in list
Appends the contents of seq to list
list1 = ['C++', 'Java', 'Python']
list1.append('C#')
['C++', 'Java', 'Python', 'C#']
>>> aList.count(123)
>>> aList.count('zara’)
2
1
>>> list1 = ['physics', 'chemistry', 'maths']
>>> list2=list(range(5))
>>> list1.extend(list2)
>>> list1
['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]
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’)
>>> list1.index('C#’)
1
ValueError: 'C#' is not in list
>>> list1.insert(1, 'Biology')
>>> list1
['physics', 'Biology', 'chemistry', 'maths’]
>>> list1.pop()
>>> list1.pop(1)
'maths'
'Biology'
38
Methods with Description
•  list.remove(obj)
•  list.reverse()
•  list.sort([func])
>>>
>>>
>>>
>>>
Removes object obj from list
Reverses objects of list in place
Sorts objects of list, use compare func if given
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.remove('Biology')
list1.remove('maths')
list1
['physics', 'chemistry']
>>> 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
len((1, 2, 3))
(1, 2, 3) + (4, 5, 6)
('Hi!',) * 4
3 in (1, 2, 3)
for x in (1,2,3) :
print (x, end=' ')
Results
3
(1, 2, 3, 4, 5, 6)
('Hi!', 'Hi!', 'Hi!', 'Hi!')
True
123
Description
Length
Concatenation
Repetition
Membership
Iteration
41
Indexing, Slicing
T=('C++', 'Java', 'Python')!
Python Expression
T[2]
T[-2]
T[1:]
T[:]
Results
'Python’
'Java’
('Java', 'Python')
(’C++’, 'Java', 'Python')
42
Built-in Tuple Functions
•  < , <=, >, >=, ==, !=
•  len(tuple)
•  max(tuple)
•  min(tuple)
•  tuple(seq)
Gives the total length of the tuple
Returns item from the tuple with
max value.
Returns item from the tuple with
min value.
Converts a list into tuple.
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!
dict = {'Name': 'Zara', 'Age': 7, 'Class’:'First’}!
print ("dict['Alice']: ", dict['Alice'])!
KeyError: 'Alice'
45
Updating Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'}!
dict['Age'] = 8
# update existing entry!
# Add new entry!
dict['School'] = "DPS School" !
print ("dict['Age']: ", dict['Age'])!
print ("dict['School']: ", dict['School'])!
dict['Age']: 8!
dict['School']:
DPS School
46
Delete Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'}!
del dict['Name'] #remove entry with key 'Name’!
dict.clear()
del dict
# remove all entries in dict!
# delete entire dictionary!
print ("dict['Age']: ", dict['Age'])!
print ("dict['School']: ", dict['School'])
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.
dict = {['Name']: 'Zara', 'Age': 7}!
print ("dict['Name']: ", dict['Name'])!
dict = {['Name']: 'Zara', 'Age': 7}!
TypeError: list objects are unhashable
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.
str(dict)
Produces a printable string representation
of a dictionary
type(variable)
Returns the type of the passed variable.
If passed variable is dictionary, then it
would return a dictionary type.
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()
dict.copy()
dict.fromkeys()
Removes all elements of dictionary dict
Returns a shallow copy of dictionary dict
Create a new dictionary with keys from
seq and values set to value.
dict.get(key, default=None)
dict.has_key(key)
For key key, returns
value or default if key
not in dictionary
Returns true if key in dictionary
dict, false otherwise
51
•  Construiti o agenda telefonica folosind:
1.  O lista
2.  Un dictionar
• 
• 
• 
• 
Adaugati/stergeti intrari din agenda
Listati agenda sub forma de tabel (nume nr.telefon)
Verificati daca un anumit nume exista in agenda
Gasiti numarul de telefon pentru o anumita persoana sub
forma de dialog:
! 
! 
! 
Dati numele persoanei:….
Se introduce numele
Se obtine numarul de tel sau mesaj ca pers. Nu este in
agenda
52
Methods with Description
•  dict.items()
•  dict.keys()
Returns a list of dict's (key, value)
tuple pairs
Returns list of dictionary dict's keys
•  dict.setdefault(key, default=None)
Similar to
get(), but will set dict[key]=default
if key is not already in dict
•  dict.update(dict2)
Adds dictionary dict2's key-values
pairs to dict
•  dict.values()
Returns list of dictionary dict's
values
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
dict1 = {'Name': 'Manni', 'Age': 7, 'Class':
'First'}!
dict2 = dict1.copy()!
print ("New Dictionary : ",dict2)
New dictionary : {'Name': 'Manni', 'Age': 7,
'Class': 'First'}!
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!
seq = ('name', 'age', 'sex')!
dict = dict.fromkeys(seq)!
print ("New Dictionary : %s" %
dict = dict.fromkeys(seq, 10)!
print ("New Dictionary : %s" %
str(dict))!
str(dict))
New Dictionary : {'age': None, 'name': None, 'sex': None}!
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
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.
dict = {'Name': 'Zara', 'Age': 27}!
print ("Value : %s" % dict.get('Age'))!
print ("Value : %s" %
dict.get('Sex', "NO"))
Value : 27!
Value : NO
56
has_key
dict.has_key(key)
•  key -- This is the Key to be searched in the dictionary.
dict = {'Name': 'Zara', 'Age': 7}!
print ("Value : %s" % dict.has_key('Age'))!
print ("Value : %s" %
dict.has_key('Sex'))
Value : True!
Value : False
57
items, keys
dict = {'Name': 'Zara', 'Age': 7}!
print ("Value : %s" %
dict.items())
Value : [('Age', 7), ('Name', 'Zara')]!
dict = {'Name': 'Zara', 'Age': 7}!
print ("Value : %s" %
dict.keys())
Value : dict_keys(['Name', 'Age'])
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.
dict = {'Name': 'Zara', 'Age': 7}!
print ("Value : %s" % dict.setdefault('Age',
None))!
print ("Value : %s" % dict.setdefault('Sex',
None))!
print (dict)
Value : 7!
Value : None!
{'Name': 'Zara', 'Sex': None, 'Age': 7}
59
update, values
dict.update(dict2)
•  dict2 -- This is the dictionary to be added into dict.
dict = {'Name': 'Zara', 'Age': 7}!
dict2 = {'Sex': 'female’ }!
dict.update(dict2)!
print ("updated dict : ", dict)!
updated dict :
{'Sex': 'female', 'Age': 7, 'Name': 'Zara'}!
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}!
print ("Values : ", list(dict.values()))
Values :
['female', 7, 'Zara']
60
Python Functions
•  A function is a block of organized, reusable code that is used to perform a
single, related action.
def functionname( parameters ):!
"function_docstring”!
function_suite!
return [expression]!
•  Here are simple rules to define a function in Python.
!  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.
!  The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
!  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.
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
>> print (fib2(100))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> print(fib2(400))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
>>> print(fib2(30))
[0, 1, 1, 2, 3, 5, 8, 13, 21]
63
Lambda Expressions
•  Small anonymous functions can be created with the lambda
keyword.
•  lambda a, b: a+b
!  This function returns the sum of its two arguments
•  Lambda functions can be used wherever function objects
are required.
•  Lambda expression can be used to return a function from a
function.
•  Lambda expression can be used to pass a small function as
an argument
64
Ex 1
def adun(n):
"""Functia adun(n) returneaza o functie f(x) care aduna n la x"""
return lambda x: x + n
>>>
>>>
>>>
17
>>>
114
>>>
23
f = adun(9)
g = adun(14)
f(8)
g(100)
f(0)+g(0)
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