16. Common Types & Operator
▪Numeric type
• int, float, bool, complex
• abs(), round()
▪String type
▪Container type
• list, tuple, dict, set
16
1
2
3
4
5
6
7
8
9
10
11
# python2
w = 49
h = 163
bmi = 49 / (163/100)**2
print(bmi) # 49
# python3
w = 49.0
h = 163.0
bmi = 49 / (163/100)**2
print(bmi) # 18.4425...
17. Try it!
▪#練習:Set the following variables to the corresponding values:
1. my_int to the value 7
2. my_float to the value 1.23
3. my_bool to the value True
17
19. Try it!
▪#練習:Add two Numbers
19
1
2
3
4
5
6
7
8
9
10
11
a = input()
b = input()
…
print('The sum of ‘, a, ‘and’ ,b ,’is’, a + b)
20. Try it!
▪#練習:Add two Numbers
20
1
2
3
4
5
6
7
8
9
10
11
a = input()
b = input()
…
print('The sum of ‘, a + b, ‘and’ ,a ,’is’, b)
print('The sum of %s and %s is %s ' % (a, b, sum))
print('The sum of {0} and {1} is {2} '.format(a, b, sum))
sum = int(a) + int(b)
print(f'The sum of {a} and {b} is {sum}')
21. Try it!
▪#練習:Find the Square Root
21
1
2
3
4
5
6
7
8
9
1
0
1
1
num = 9
num_sqrt = 3
print('The square root of %0.3f is %0.3f' % (num ,num_sqrt))
22. Common Types & Operator
▪Numeric type
• int, float, bool, complex
▪String type
• len()
• lower(), upper()
• split(), find(), replace()
• slice
• Formatting String
▪Container type
• list, tuple, dict, set
22
1
2
3
4
5
6
7
8
a = '12345'
b = 'hello world'
c = 'n'
d = r'n'
e = 'n'
print(b + str(a) + c + d + e)
print(b + str(a) + str(c) + str(d) +
str(e))
24. Try it!
▪#練習:Write a Python program to find the first appearance of
the substring 'not' and 'poor' from a given string, if 'bad' follows
the 'poor', replace the whole 'not'...'poor' substring with 'good'.
Return the resulting string.
• Sample Input: The lyrics is not that poor!
• Sample Output: The lyrics is good!
24
38. Try it!
▪#練習:Write a Python program to replace the last element in a
list with another list.
• Sample Input: num1 = [1, 3, 5, 7, 9, 10], num2 = [2, 4, 6, 8]
• Sample Output: [1, 3, 5, 7, 9, 2, 4, 6, 8]
38
43. Try it!
▪#練習:Write a Python program to concatenate following
dictionaries to create a new one.
43
1
2
3
4
5
6
7
8
9
10
# Input:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50, 6:60}
# Output: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
44. Try it!
▪#練習:Write a Python program to check if a given key already
exists in a dictionary.
44
1
2
3
4
5
6
7
8
9
10
# Input:
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
key = input()
# Output: Yes, the key is in this dict. or
# No, the key is not in this dict.
46. Try it!
▪#練習:Illustrate Different Set Operations
46
1
2
3
4
5
6
7
8
9
10
# define three sets
E, N = {0, 2, 4, 6, 8}, {1, 2, 3, 4, 5}
print("Intersection of E and N is", E & N) # 2, 4
print("Union of E and N is",E | N) # 0 1 2 3 4 5 6 8
print("Difference of E and N is",E - N) # 1 3 5
print("Symmetric difference of E and N is",E ^ N) # 0 1 3 5
6 8
47. Try it!
▪#練習:Remove the repeated elements from the list, and sort it
Decreasingly.
47
1
2
3
4
5
6
7
8
9
10
l = [1, 1, 3, 9, 7, 8, 8, 8]
# Output: [9, 8, 7, 3, 1]
48. 48
▪Mutable objects
• list, dict, set
▪Immutable objects
• int, float, complex, string, tuple
Reference: https://www.linkedin.com/pulse/mutable-vs-immutable-objects-python-megha-mohan
Im vs Mutable ?
50. tuple vs list?
▪slower but more powerful than tuples.
▪Lists can be modified, and they have lots of handy operations
we can perform on them.
▪Tuples are immutable and have fewer features.
▪To convert between tuples and lists use the list() and tuple()
functions:
• li = list(tu)
• tu = tuple(li)
50
65. Flow Control
▪if - elif - else
▪while
▪for in
▪break, continue
▪range(), zip(), enumerate()
65
1
2
while condition:
....
66. Flow Control
▪if - elif - else
▪while
▪for in
▪break, continue
▪range(), zip(), enumerate()
66
1
2
3
4
5
for i in [...]:
...
a = [i for i in [...]] # list
b = (i for i in [...]) # generator
84. Function
84
1
2
3
4
5
6
7
8
9
max1 = a if a > b else b...
max2 = x if x > y else y...
a = 123
b = 234
// declare funcetion
def max(a, b):
return a if a > b else b
// call function
max(10, 20)
maximum = max
maximum(10, 20)
# 20
85. Basic Method for Call Function
85
1
2
3
4
5
6
7
def f(x=100, y=200):
return x, y
f(1, 2)
f(y=2, x=1)
f(*(1, 2))
f(**{y=2, x=1})
124. Error Exception
124
1
2
3
4
5
6
7
8
9
10
11
12
13
14
10 * (1/0)
# Traceback (most recent call last):
# File "<stdin>", line 1, in
<module>ZeroDivisionError: division by zero
4 + spam*3
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>NameError:
name 'spam' is not defined
'2' + 2
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>TypeError:
Can't convert 'int' object to str implicitly
125. try-except
125
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try:
x = input("the first number:")
y = input("the second number:")
r = float(x)/float(y)
print(r)
except Exception as e:
print(e)
the first number: 2
the second number: 0
# float division by zero
the first number: 2
the second number: a
# could not convert string to float: a
the first number: 4
the second number: 2
# 2.0