This document provides an overview of Python fundamentals including basic concepts like data types, operators, flow control, functions and classes. It begins with an introduction to Python versions and environments. The outline covers topics like Hello World, common types and operators for numeric, string and container data types. It also discusses flow control structures like if/else, while loops and for loops. Finally, it briefly mentions functions, classes, exceptions and file I/O.
15. Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression
§ String type
§ Container type
• list, tuple, dict, set
15
1
2
3
4
5
6
7
8
9
w = 49
h = 163
bmi = 49 / (163/100)**2
print(bmi) # 49
w = 49.0
h = 163.0
bmi = 49 / (163/100)**2
print(bmi) # 18.4425...
16. 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
16
18. Try it!
§ #練習:Add two Numbers
18
1
2
3
4
5
6
7
8
9
1
0
1
1
a = input()
b = input()
…
print('The sum of {0} and {1} is {2} '.format(a, b, sum))
19. Try it!
§ #練習:Find the Square Root
19
1
2
3
4
5
6
7
8
9
1
0
1
1
num = 8
…
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
20. Common Types & Operator
§ Numeric type
• int, float, bool, complex
§ String type
• len, lower, upper, split
§ Container type
• list, tuple, dict, set
20
1
2
3
4
5
6
7
8
a = '12345'
b = 'hello world'
c = 'n'
d = r'n'
print(b + str(a) + c + d)
print(b + str(a) + str(c) + str(d))
print(b + str(a) + repr(c) + repr(d))
21. Try it!
§ #練習:Set the following variables to their respective phrases:
1. Set caesar to Graham
2. Set sentence to There's a snake in my boot!
3. Set paragraph to Dear Mr. Chen,
I’m Jacky, nice to meet you.
21
22. Common Types & Operator
§ Numeric type
• int, float, bool, complex
§ String type
§ Container type
• list [] => mutable sequence
• tuple (,) => immutable sequence
• dict {:} => mutable unordered collection of key-value mapped element
• set {} => mutable unordered collections of unique elements
22
23. list
23
1
2
3
4
5
6
L = [1, 2, 3, 4]
G = [3, 4, 5, 6]
L + G # [1, 2, 3, 4, 3, 4, 5, 6]
L – G
L * 2 # [1, 2, 3, 4, 1, 2, 3, 4]
L / 2
33. Try it!
§ #練習:Illustrate Different Set Operations
33
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("Union of E and N is",E | N) #
print("Intersection of E and N is",E & N)
print("Difference of E and N is",E - N)
print("Symmetric difference of E and N is",E ^ N)
34. 34
§ 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 ?
36. 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)
36
51. Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
51
1
2
while condition:
....
52. Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
52
1
2
3
4
5
for i in [...]:
...
a = [i for i in [...]] # list
b = (i for i in [...]) # generator
58. Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
58
59. Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
59
1
2
3
4
5
6
7
8
for i in range(1, 3):
print(i)
for i, j in zip([a, b, c], [1, 2, 3]):
print(i, j)
for i,j in enumerate([a, b, c]):
print(i, j)
69. Function
69
1
2
3
4
5
6
7
8
9
max1 = a if a > b else b...
max2 = x if x > y else y...
def max(a, b):
return a if a > b else b
maximum = max
maximum(10, 20)
# 20
70. Basic Method for Call Function
70
1
2
3
4
5
6
7
def f(x, y):
return x, y
f(1, 2)
f(y=2, x=1)
f(*(1, 2))
f(**{y=2, x=1})
91. Error Exception
91
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
92. try-except
92
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)
else:
pass
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