一、简单的if 语句
在if语句中,缩进的作用与for循环中相同。如果测试通过了,将执行if语句后面所有缩进的代码行,否则将忽略它们。
age = 19
if age >= 18:
print("You are old enough to vote!")
1.1 if-else语句
age=17
if age >=18:
print("You are old enough to vote!")
else:
print("Sorry, you are too young to vote.")
1.2 if-elif-else 语句
Python只执行 if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。可根据需要使用任意数量的elif代码块。
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
输出:
Your admission cost is $5.
1.3 使用if语句处理列表
确定列表不是空的
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
在这里,列表为空,输出如下:
Are you sure you want a plain pizza?
二、用户输入和for循环
2.1 函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做.
2.2 使用 int()来获取数值输入
使用函数input()时,Python将用户输入解读为字符串。进行数值比较时会发生错误,为解决这个问题,可使用函数int(),它让Python将输入视为数值。
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
2.3 while 循环简介
使用while循环来数数,例如,下面的while循环从1数到5:
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
让用户选择何时退出,可使用while循环让程序在用户愿意时不断地运行
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
使用标志
我们把这个标志命名为active(可给它指定任何名称),它将用于判断程序是否应继续运行:
2.3.1 使用while循环来处理列表和字典
假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中.
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# 显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())