每条 if 语句的核心都是一个值为True或False的表达式,这种表达式也称为条件测试
if 和 else 语句以及各自的缩进部分都是一个代码块
(1)if 语句
条件测试结果为True,,执行 if 语句后面所有缩进的代码块,否则忽略他们
age = 19 if age >= 18: print("you are enough to vote!") 输出:you are enough to vote!
(2)if - else 语句
条件测试通过后执行 if 语句后面缩进的代码块,不通过时执行 else 语句后面缩进的代码块
age = 14 if age >= 18: print("you are enough to vote!") else: print("Sorry,you are too young to vote!") 输出:Sorry,you are too young to vote!
(3)if - elif - else 语句
elif 的应用场景:同时判断多个条件,所有的条件是平级的,可以根据需要使用任意数量的 elif 代码块,同时 if - elif - else 语句结构中else代码块也可以省略。
if - elif - else 语句结构仅适合于只有一个条件满足的情况
age = 14 if age < 4: print("your admisson cost isrequested_topping = ['mushrooms','extra cheese'] if 'mushrooms' in requested_topping: print("Adding mushrooms.") if 'pepperoni' in requested_topping: print("Adding pepperoni.") if 'extra cheese' in requested_topping: print("Adding extra cheese.") 输出:Adding mushrooms. Adding extra cheese.!") elif age < 18: print("your admisson cost is !") else: print("your admission cost is !") 输出:your admission cost is !
elif 代码行其实是另一个if测试,仅在前面的测试未通过时才会执行这行代码,elif代码行测试通过后,会跳过余下的else语句代码块。
(4) if 嵌套
if 语句可以用来测试多个条件
prompt = "nPlease enter the name of a city you have visited:" prompt += "n(Enter 'quit' when you are finished.)" while True: city = input(prompt) if city == 'quit': break else: print(f"I'd love to go to {city.title()}!") 输出: Please enter the name of a city you have visited: (Enter 'quit' when you are finished.)Beijing I'd love to go to Beijing! Please enter the name of a city you have visited: (Enter 'quit' when you are finished.)quit
if 嵌套语句是在之前条件满足的情况下,再增加额外的判断
age = 14 if age <= 18: if age > 3: print("you are enough to vote!") 输出:you are enough to vote!二、循环语句
循环:从0开始,让特定代码重复执行
1、for 循环
针对集合中的每个元素都执行一个代码块,是一种遍历列表的有效方式。
for 循环 *** 作列表
2、while循环
最常用的场景就是让指定的代码按照制定的次数重复执行
while 条件(判断 计数器 是否达到 目标次数):
条件满足时,做的事情1
条件满足时,做的事情2
…
处理条件(计数器 + 1)
break和continue:是专门在循环中使用的关键字
break 某一条件满足时,退出循环,不再执行后续重复的代码
current_number = 0 while current_number < 10: current_number += 1 if current_number %2 == 0: continue //偶数时跳出该循环,即不输出 print(current_number) 输出: 1 3 5 7 9
continue 某一条件满足时,不执行后续重复的代码
要返回循环开头,并根据条件测试结果决定是否继续执行循环,就可以使用continue语句
# 首先,创建一个待验证用户列表 # 和一个用于存储已验证用户的空列表 un/confirm/ied_users = ['alice','brian','candace'] /confirm/ied_users = [] # 验证每个用户,直到没有未验证用户为止 # 将每个经过验证的用户都移到已验证用户列表中 while un/confirm/ied_users: current_user = un/confirm/ied_users.pop() # 方法pop()以每次一个的方式从列表un/confirm/ied_users末尾删除未验证的用户,最先删除的是Candace,其名字首先被赋给变量current_user print(f"Verifying user:{current_user.title()}") /confirm/ied_users.append(current_user) # 显示所有已验证的用户 print("nThe following users have been /confirm/ied:") for /confirm/ied_user in /confirm/ied_users: print(/confirm/ied_user.title()) 输出: Verifying user:Candace Verifying user:Brian Verifying user:Alice The following users have been /confirm/ied: Candace Brian Alice
break和continue只针对当前所在循环有效,每个循环都必须要有停止运行的条件,在写循环语句时务必对每个循环进行测试,避免写出死循环(程序无休止的运行下去),如果陷入无限循环,可以按Ctrl+C,也可以通过关闭程序输出的终端窗口。
循环嵌套:
while嵌套就是:while里面还有while
3、while 循环处理列表和字典
while 循环可以在遍历列表的同时对其进行修改
(1)列表之间移动元素
使用函数remove()来删除列表中的特定值 pets = ['dog','cat','dog','goldfish','rabbit','cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets) 输出: ['dog', 'cat', 'dog', 'goldfish', 'rabbit', 'cat'] ['dog', 'dog', 'goldfish', 'rabbit']
(2)删除为特定值的所有列表元素
responses = {} #定义一个空字典 # 设置一个标志,指出调查是否继续 polling_active = True while polling_active: # 提示输入被调查者的名字和回答 name = input("nWhat is your name?") response = input("Which mountain would you like to climb someday?") # 将回答存储在字典中 responses[name] = response # 看看是否还有人要参与调查 repeat = input("Would you like to let another person respond?(Yes/No)") if repeat == 'No': polling_active = False # 调查结束,显示结果 print("n--- Poll Results ---") for name,response in responses.item(): print(f"{name} would like to climb {response}.") 输出: What is your name?KK Which mountain would you like to climb someday?NN Would you like to let another person respond?(Yes/No)Yes What is your name?MM Which mountain would you like to climb someday?LO Would you like to let another person respond?(Yes/No)No --- Poll Results --- KK would like to climb NN. MM would like to climb LO.
(3)使用用户来填充字典
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)