INT104-Tutorial 2

想了想还是先写Tutorial的吧,这门课Lecture已经讲到起飞了,根本听不懂啊。而TTL这边则负责打基础,总共花三节课给Python讲完是吧。

运算符

算术运算符

这是基础中的基础了,python的算术运算符和java相类似,最基础的就是:

1
2
3
4
5
6
7
print(4 + 3) # 7
print(4 - 3) # 1
print(4 * 3) # 12
print(7 / 2) # 3.5
print(7 // 2) # 3
print(int(7 / 2)) # 3
print(7 % 2) # 1

首先,”+”, “-“, “*”这三个没什么可讲了,所以我们来讲讲这个除法。众所周知,python的变量是不需要定义类型的,程序会自动识别输入的数据并分配合适的类型(真的很方便!)。所以当我们输入”/“时,python会自动将结果识别为float类型。如果想要输出不带小数点的,我们可以使用”//“这个整除符号。当然,我们也可以将其强转为int类型。最后一个”%”是取余(当然和java中的一样),简单的说就是把7除以2后余下的数取出来,所以叫做取余。
在python中,指数运算也被算作了算术运算符,其符号为”**”。在java中,我们需要使用Math.pow()来进行指数运算,但是在python中,我们只需要7 ** 2 = 49即可,是不是很方便!
所有算数运算符的运算顺序与数学中相一致,并且也可以使用()来提高运算的优先级。

1
2
3
print(16 ** 2 / 4) # 64.0
print(4 + 3 ** 2) # 13
print((4 + 3) ** 2) # 49

比较运算符

比较运算符与java中相一致,就不过多赘述了。

1
2
3
4
5
6
7
8
x = 1
y = 2
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False

要注意,=为赋值运算符,而==为比较运算符,两者不一致!

1
2
x = 5
x == 5 # True

逻辑运算符

同样,也与java中相一致。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
a = False
b = True
print(not a) # True
print(not b) # False
print(a or b) # True
print(a and b) # False

x = 14
(x > 10) and (x < 20) # True

y = 42
not ((x % 2 == 0) and (y % 3 == 0)) # False

xDivisible = (x % 2) == 0 # 检查x是否是2的倍数
yDivisible = (y % 3) == 0 # 检查y是否是3的倍数
not (xDivisible and yDivisible) # False

If Else关键字

功能与java相同,只是语法不同。

1
2
3
4
5
6
7
8
x = True
if x:
print("Executing if")
else:
print("Executing else")
print("Prints regardless of the if-else block")
# Out: Executing if
# Out: Prints regardless of the if-else block

使用比较运算符==也是可以的:

1
2
3
4
5
6
7
8
name = "阿斌"
if name == "阿斌":
print("给斌神🧎了")
else:
print("👋")
print("你好呀")
# Out: 给斌神🧎了
# Out: 你好呀

在python中,我们使用elif而不是else if

1
2
3
4
5
6
7
8
9
10
11
12
age = 20

if age < 18:
type = "🍚"
elif age == 18:
type = "🐟"
elif age < 28:
type = "🐧"
else:
type = "🐴"

print("你是" + type) # 你是🐧

Loop

For loop

python的for循环是一种迭代控制流语句,可以用于遍历序列(如字符串、列表、元组、字典、集合)中的每个元素,或者执行指定次数的循环。其使用方式类似于java中的增强for循环:

1
2
3
4
5
6
7
8
9
10
Serendipity = ["🍚", "🐟", "🐧", "🐴", "🆘", "☀️", "🥣"]
for bro in Serendipity:
print("Bro", bro, "has index", Serendipity.index(bro))
# Out: Bro 🍚 has index 0
# Out: Bro 🐟 has index 1
# Out: Bro 🐧 has index 2
# Out: Bro 🐴 has index 3
# Out: Bro 🆘 has index 4
# Out: Bro ☀️ has index 5
# Out: Bro 🥣 has index 6

如果我们想达到类似java中普通for循环的效果,可以使用for i in range(1, 10)的形式。其中,range中的前者是起始,后者是终止。也可以使用单数字形式,表示从 1 至所填数字(不包含),如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
for num in range(85):
if num == 1:
print(num)
print("你出生了")
elif num == 18:
print(num)
print("你成年了")
elif num == 30:
print(num)
print("三十而立")
elif num == 40:
print(num)
print("四十不惑")
elif num == 50:
print(num)
print("五十知天命")
elif num == 60:
print(num)
print("六十耳顺")
elif num == 70:
print(num)
print("从心所欲,不逾矩")
elif num >= 80:
print(num)
print("古来稀")
# Out: 1
# Out: 你出生了
# Out: 18
# Out: 你成年了
# Out: 30
# Out: 三十而立
# Out: 40
# Out: 四十不惑
# Out: 50
# Out: 五十知天命
# Out: 60
# Out: 六十耳顺
# Out: 70
# Out: 从心所欲,不逾矩
# Out: 80
# Out: 古来稀
# Out: 81
# Out: 古来稀
# Out: 82
# Out: 古来稀
# Out: 83
# Out: 古来稀
# Out: 84
# Out: 古来稀

While loop

while循环与java中相一致:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
n = 0
while True:
print("Executing while loop")
if n == 5:
break
n = n + 1
print("Finished while loop")
# Out: Executing while loop
# Out: Executing while loop
# Out: Executing while loop
# Out: Executing while loop
# Out: Executing while loop
# Out: Executing while loop
# Out: Finished while loop

定义函数

python真不愧是最简单的语言,只需要使用def即可创建函数。不用管是否有返回值,或是返回值的类型是什么。

1
2
3
4
5
6
7
8
def greet_user(username):
print("Hello,", username + "!")
greet_user("🍚")
greet_user("🐧")
greet_user("🐟")
# Out: Hello, 🍚!
# Out: Hello, 🐧!
# Out: Hello, 🐟!

除此之外,我们还可以给传入数据定义默认参数。当未传入参数时,python会自动使用默认参数来替代:

1
2
3
4
5
6
7
8
9
10
11
12
def describe_pet(name, animal = "dog"): # animal的默认参数:dog
print("I have a", animal + ".")
print("Its name is", name + ".")
describe_pet("阿斌", "penguin")
describe_pet("🍚")
describe_pet(animal = "horse", name = "🐴") # 顺序也可以是无所谓的
# Out: I have a penguin.
# Out: Its name is 阿斌.
# Out: I have a dog.
# Out: Its name is 🍚.
# Out: I have a horse.
# Out: Its name is 🐴.

并且,我们还可以讲默认参数设置为None。配合if语句,可以实现当未传入该参数时不输出的效果:

1
2
3
4
5
6
7
8
9
10
11
12
def describe_pet(name, animal = None): # 默认参数为None
if animal:
print("I have a", animal + ".")
print("Its name is", name + ".")
describe_pet("阿斌", "penguin")
describe_pet("🍚")
describe_pet(animal = "horse", name = "🐴") # 顺序无所谓
# Out: I have a penguin.
# Out: Its name is 阿斌.
# Out: Its name is 🍚.
# Out: I have a horse.
# Out: Its name is 🐴.

在定义的函数中使用If-Else关键字:

1
2
3
4
5
6
7
8
9
10
11
12
def roundNum(num):
remainder = num % 1
if remainder < 0.5:
return num - remainder
else:
return num + (1 - remainder)
print(roundNum(3.4))
print(roundNum(7.7))
print(roundNum(9.2))
# Out: 3.0
# Out: 8.0
# Out: 9.0

传入的数据可以时列表,当返回多个数据时,也是以列表形式返回:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def listFunc(my_list):
maximum = max(my_list)
minimum = min(my_list)
first = my_list[0]
last = my_list[-1]
return maximum,minimum,first,last

l=[24, 12, 68, 40, 120, 96]
params = listFunc(l)
print(params)
print("Max value is", params[0])
print("Min value is", params[1])
print("First value is", params[2])
print("Last value is", params[3])

# Out: (120, 12, 24, 96)
# Out: Max value is 120
# Out: Min value is 12
# Out: First value is 24
# Out: Last value is 96

多种输出方式

python支持很多种将字符串与数字连接的输出方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
pi = 3.14159
d = 12756
c = pi * d

print("Earth's diameter at equator: " + str(d) + " km. Equator's circumference: " + str(c) + " km.")
print("Earth's diameter at equator:", d, "km. Equator's circumference:", c, "km.")
print("Earth's diameter at equator: {:.1f} km. Equator's circumference: {:.1f} km.".format(d,c))
print(f"Earth's diameter at equator: {d} km. Equator's circumference: {c} km.")

# Out: Earth's diameter at equator: 12756 km. Equator's circumference: 40074.12204 km.
# Out: Earth's diameter at equator: 12756 km. Equator's circumference: 40074.12204 km.
# Out: Earth's diameter at equator: 12756.0 km. Equator's circumference: 40074.1 km.
# Out: Earth's diameter at equator: 12756 km. Equator's circumference: 40074.12204 km.

使用”+”号时,需要把数字强转为字符串形式。
使用”, “时,可以直接连接字符串与数字,并且会自动补充空格。
后面两个都是format() 方法格式化输出,我们最常使用的是第四种这样的格式。对于第三种的{:.1f}

  • ::表示要对值进行格式化。
  • .:表示小数点。
  • 1:表示保留小数点后一位数字。
  • f:表示使用浮点数格式。

所以完整来看,{:.1f}表示保留小数点后一位数字的浮点数格式。