Lecture 2
Lecture 2
Lecture 2
1 / 11
if Statement
#!/usr/bin/python3.6
if x < 0:
a = -1 * x
elif x
== 2:
a = 2 * x
elif x == 3:
a = x
else:
a = x / 2
print(a)
2 / 11
for Statement
for i in range(10):
print(i ** 2) # outputs squares 0 to 81
for i in range(len(words)):
print(len(words[i])) # outputs 1 to 4
for i in 'abcd':
print(i) # outputs a
to d
3 / 11
Functions
(1)
def mul(a, b):
""" This is the function doc string """
return a * 2, b + 2, a * b
def add(list_arg):
s = list_arg[0]
for i in range(1, len(list_arg)):
s += list_arg[i]
return s
list1 = [1, 2, 3, 4]
print (add(list1)) # outputs 10
Myadd = add
print(Myadd(list2)) # outputs 'abc'
4 / 11
Functions
(2)
def fun2(x):
return x * 3
def fun1(q,
x):
return q(x)
print(fun1(fun2, 7)) # outputs 21
5 / 11
Functions (3): Parameter Passing
f1(1, 2) # outputs 1 2
f1(b = 1, a = 2) # outputs 2 1
f1(1, b = 2) # outputs 1 2
6 / 11
More on Lists
a = [66.25, 333, 333, 1, 1234.5]
print(a.count(333), a.count(66.25), a.count('x')) # outputs 2 1 0
a.insert(2, -1)
a.append(333)
print(a) # outputs [66.25, 333, -1, 333, 1, 1234.5, 333]
print(a.index(333)) # outputs 1
a.remove(333)
print(a) # outputs [66.25, -1, 333, 1, 1234.5, 333]
a.reverse()
print(a) # outputs [333, 1234.5, 1, 333, -1, 66.25]
a.sort()
print(a) # outputs [-1, 1, 66.25, 333, 333, 1234.5]
a1 = []
if x != y:
a1.append((x,
y))
a2 = [(x, y) for x in
[1,2,3] for y in [3,1,4] if
x != y]
8 / 11
More on Data Structures
Not to be covered
Tuples
Sets
Dictionaries
In other programming languages, called maps
Indexed by keys (strings or numbers)
• Where as, lists are indexed by a range of numbers
9 / 11
Dictionaries
(1)
student = {'name' : 'Mohammad', 'StudentID' : 111111}
student['gender'] = 'male'
print(student)
# outputs {'StudentID': 111111, 'gender': 'male', 'name': 'Mohammad'}
print(list(student.items()))
# outputs [('StudentID', 111111), ('gender', 'male'), \
# ('name', 'Mohammad')]
student['name'] = 'Ahmad'
print(student)
# outputs {'StudentID': 111111, 'gender': 'male', 'name': 'Ahmad'}
10 /
Dictionaries (2)
k, v = list(student.items())[0]
print(k, v) # outputs StudentID 111111
for k, v in student.items():
print(k, v)
# outputs
# StudentID 111111
# gender male
# name Ahmad
11 /