IF-While-For 轻松掌握Python流程控制语句

流程控制语句包括If条件判断语句、While循环语句及For循环语句。

If 条件判断

If语句允许您检查程序的当前状态,并对该状态作出适当的响应。可以编写一个简单的If语句来检查一个条件,也可以创建一系列复杂的if语句来标识您正在寻找的确切条件。

条件测试

条件测试是一个表达式,可以计算为真或假。Python使用TrueFalse值来决定是否执行If语句中的代码。

>>> x == 42  # 等于
>>> x != 42  # 不等于
>>> x > 42   # 大于
>>> x >= 42  # 大于或等于
>>> x < 42   # 小于
>>> x <= 42  # 小于或等于

多条件测试

  • and

>>> 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
  • or

>>> 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循环就会重复一个代码块。,只要某些条件仍然为真。可以使用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 + "!")
  • 在循环中使用continue

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 + "!")

For循环

while循环一样,for可以完成循环的功能。

在Python中 for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

for循环的格式

for i in range(10):  #遍历
    print(i,end=' ')

break

L = []
for i in range(1,10000):
    if i%3 == 0:
        L.append(i)
    if len(L) == 100:
        break
print(L)

在多层的for循环当中

name = '世界杯在召唤我'

for i in range(3):
    for x in name:
        if x == '在': 
             break       
    # 打断的是最内层的for循环,但仍然继续执行外层循环
        print(x)
    print("——————我是{}次大循环结束之后的优美的分割线——————".format(i+1))
print("这句话在for循环后,与for循环无关")

continue

name = '世界杯在召唤我'

for x in name:
    if x == '在': 
        continue  # 结束本次循环
    print(x)

pass

for i in 'Python':
    if i == 'h':
        pass
    else:
        print(i)
-- 数据STUDIO -- 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值