流程控制语句包括If
条件判断语句、While
循环语句及For
循环语句。
If
语句允许您检查程序的当前状态,并对该状态作出适当的响应。可以编写一个简单的If
语句来检查一个条件,也可以创建一系列复杂的if语句来标识您正在寻找的确切条件。
条件测试是一个表达式,可以计算为真或假。Python使用True
和False
值来决定是否执行If
语句中的代码。
>>> x == 42 # 等于
>>> x != 42 # 不等于
>>> x > 42 # 大于
>>> x >= 42 # 大于或等于
>>> x < 42 # 小于
>>> x <= 42 # 小于或等于
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21 False
>>> age_1 = 23
>>> age_0 >= 21 and age_1 >= 21 True
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False
>>> 'trek' in bikes # 是否存在
>>> 'surly' not in bikes # 是否不存在
>>> game_active = True
>>> can_edit = False
存在几种if
语句。选择使用哪一个取决于需要测试的条件的数量。可以有你需要的任何数量的elif
块,而else
块总是可选的。
if
语句age = 19
if age >= 18:
print("You're old enough to vote!")
if-else
语句age = 17
if age >= 18:
print("You're old enough to vote!")
else:
print("You can't vote yet.")
if-elif-else
语句if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else:
ticket_price = 15
While
循环就会重复一个代码块。,只要某些条件仍然为真。可以使用while
循环让程序运行,只要用户希望它们运行。
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
msg = ''
while msg != 'quit':
msg = input("What's your message? ")
print(msg)
prompt = "\nTell me something, and I'll "
prompt += "repeat it back to you."
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
你可以在任何Python循环中使用break语句和continue语句。例如,你可以使用break来退出正在处理列表或字典的For循环。在循环遍历列表或字典时,也可以使用continue跳过某些项。
break
退出循环prompt = "\nWhat cities have you visited?"
prompt += "\nEnter 'quit' when you're done. "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I've been to " + city + "!")
banned_users = ['eve', 'fred', 'gary', 'helen']
prompt = "\nAdd a player to your team."
prompt += "\nEnter 'quit' when you're done. "
players = []
while True:
player = input(prompt)
if player == 'quit':
break
elif player in banned_users:
print(player + " is banned!")
continue
else:
players.append(player)
print("\nYour team:")
for player in players:
print(player)
remove()
方法从列表中删除特定的值,但它只删除您提供的值的第一个实例。可以使用while
循环删除特定值的所有实例
pets = ['dog', 'cat', 'dog', 'fish', 'cat',
'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
每个while
循环需要一种方法来停止运行,这样它就不会永远继续运行。如果没有办法使条件变为False
,循环将永远不会停止运行。
# 下面这个无限循环
while True:
name = input("\nWho are you? ")
print("Nice to meet you, " + name + "!")
像while
循环一样,for
可以完成循环的功能。
在Python中 for
循环可以遍历任何序列的项目,如一个列表或者一个字符串等。
for i in range(10): #遍历
print(i,end=' ')
L = []
for i in range(1,10000):
if i%3 == 0:
L.append(i)
if len(L) == 100:
break
print(L)
name = '世界杯在召唤我'
for i in range(3):
for x in name:
if x == '在':
break
# 打断的是最内层的for循环,但仍然继续执行外层循环
print(x)
print("——————我是{}次大循环结束之后的优美的分割线——————".format(i+1))
print("这句话在for循环后,与for循环无关")
name = '世界杯在召唤我'
for x in name:
if x == '在':
continue # 结束本次循环
print(x)
for i in 'Python':
if i == 'h':
pass
else:
print(i)