本帖最后由 WoShiXXX 于 2021-12-2 21:46 编辑
这2周一直在准备期中考试,以及沉浸在考完的喜(bei)悦(tong)之中。楼主为八年级学生,想要冲冲编程竞赛,但无奈自己智商不够,没法撸各种算法题,只好先从比较简单的Python开始,开一些帖子记录一下。由于我有前端基础,所以我并不是0基础,而是0.2基础。我随时可能拖更,如果我长时间拖更,欢迎催更!我选用的是Python编程:从入门到实践(第2版).pdf这本书当作教材。
今天主要看了if语句后面的部分
布尔表达式
只有两个值,True和False,用于赋值给变量。布尔表达式是条件测试的别名。
if语句的形式
1.简单的if语句
这种if语句只有1个测试和1个操作。如果测试通过则执行对应的操作。
[Python] 纯文本查看 复制代码 age = 19
if age >= 18:
print("You are old enough to vote!")
上面这串代码,先定义了age为19,然后判断age的值是否大于等于18(显然这是一定的),如果是,则打印“You are old enough to vote.”
2.if-else语句
if-else语句类似于简单的if语句,但else能让条件测试不通过时执行相应的操作[Python] 纯文本查看 复制代码 age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
这段代码首先定义了age为17,判断age是否大于等于18(否),如果是,则执行第一个冒号后的代码块,如果否,则执行第二个冒号后面的代码块。
3.if-elif-else结构
这种结构通常用于测试数>3的判断。比如一班公交车要经过12站,坐1-4站则1元,5-8站则2元,9-12站则3元。下面是这个例子的实现:
[Python] 纯文本查看 复制代码 stops = 3
if stops < 4 and stops>=1:
print("1 yuan.")
elif stops > 4 and stops <=8:
print("2 yuan.")
elif stops >8 and stops <=12:
print("3yuan")
else:
print("Bad data") [/mw_shl_code]
if语句处理列表
1.确定列表不是空的
if语句的测试条件可以是一个列表,列表空则为False,不空则为True
[Python] 纯文本查看 复制代码 requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
我的练习答案:
5-3、5-4、5-5[Python] 纯文本查看 复制代码 alien_color = "red"if alien_color == "green":
print("You've got 5 points")
elif alien_color == "yellow":
print("You've got 10 points")
else:
print("You've got 15 points")
5-6
[Python] 纯文本查看 复制代码 age = 20
if age < 2:
print("A baby")
elif 2 <= age < 4:
print("A child")
elif 4 <= age < 13:
print("A kid")
elif 13 <= age < 20:
print("A teenager")
elif 20 <= age < 65:
print("An adult")
elif age >= 65:
print("An old man")
5-8、5-9
[Python] 纯文本查看 复制代码 users = ["admin", "zzjzxq33", "doge", "Hmily", "WoShiXXX"]
logined_user = "admin"
if users:
for user in users:
if user == "admin":
print(f"Hello {user}, would you like to see a status report?")
else:
print(f"Hello {user}, thank you for logging in again.")
else:
print("We need some users.")
|