学习Python中的If语句

235 阅读7分钟

Python的if语句允许你调查程序的当前状态,并对该状态做出相应的反应。你可以写一个基本的 if 语句来检查一个条件,或者你可以创建一系列 if 语句来确定你所寻找的确切条件。其他一些语言为这些提供了switch或case语句。Python 保持简单,只坚持使用 if 语句。if 语句用于条件测试、检查用户输入、数字比较、多条件检查、布尔值,等等。在本教程中,我们将看看条件测试、if、if-else、if-elif-else,以及如何在循环中使用条件检查。


条件性测试

一个可以被测试为 True 或 False 的表达式是一个条件检验。Python 使用 True 和 False 值来评估代码是否应该在 if 语句中执行。

检查是否相等

一个双等号 (==) 检查两个值是否相等。这不能与赋值运算符混淆,后者是一个单一的等号,将一个值赋给一个变量。

language = 'python'
language == 'python'
True
language = 'javascript'
language == 'python'
False

在进行比较时忽略大小写

sandwich = 'Ham'
sandwich.lower() == 'ham'
True

检查不平等

vegetable = 'potato'
vegetable != 'potahto'
True

If 语句

有几种类型的 if语句需要注意。你选择使用哪种语句取决于你需要测试多少个条件。所以你可以使用ifif-elseif-elifif-elif-else链。else块是可选的。

基本的if语句

color = 'Green'
if color == 'Green':
    print('Go!')

if-else 语句

color = 'Orange'
if color == 'Green':
    print('Go!')
else:
    print('Don't Go!')

if-elif-else 语句

color = 'Green'
if color == 'Red':
    takeaction = 'Stop'
elif color == 'Yellow':
    takeaction = 'Slow Down'
elif color == 'Green':
    takeaction = 'Go'
else:
    takeaction = 'Maintain current state'
print(f'You need to {takeaction}.')

在列表中使用if语句

if语句在与列表的结合中相当有用。

检查一个值是否不包括在一个列表中

foods = ['Snickers', 'Kit Kat', 'Butterfinger']
vegetable = 'Broccoli'
if vegetable not in foods:
    print("Eat some vegetables!")
Eat some vegetables!

测试一个列表是否为空

cats = []
if cats:
    for cat in cats:
        print(f"Cat: {cat.title()}")
else:
    print("Thank God we have no cats!")
Thank God we have no cats!

用列表进行条件测试

要测试某个值是否在一个列表中,你可以使用 **in**关键字。

programs = ['Photoshop', 'Illustrator', 'InDesign', 'Animate', 'Acrobat']
using = input('What program are you using? ')

if using in programs:
    print('That program is made by Adobe')
else:
    print('That is not an Adobe product')

python in keyword


检查用户输入

你可以使用输入语句让你的用户输入数据,我们可以用if语句来检查。所有的输入最初都存储为字符串数据类型。如果你想接受数字数据,你需要将输入字符串的值转换为数字形式。

一个基本的输入例子

fruit = input("What is your favorite fruit? ")
print(f"{fruit} is a great fruit!")

python accept input

使用获得数字输入 int()

favnum = input("What is your favorite number? ")
favnum = int(favnum)
if favnum == 7:
    print(f"{favnum} is also my favorite!")
else:
    print(f"{favnum} is a good choice!")

python numerical input with int

接受数字输入,通过 float()

pi = input("What is the value of pi? ")
pi = float(pi)
print(type(pi))

python num input as float


数值比较

数字值测试与字符串值测试类似。

测试平等和不平等

num = 17
num == 17
# True

num != 17
# False

比较运算符

num = 250
num < 777
# True

num <= 777
# True

num > 777
# False

num >= 777
# False

测试多个条件

你可以同时检查多个条件。如果列出的所有条件都是 "真",那么 **and**操作符如果列出的所有条件都是真,则返回真。如果任何一个条件为 "真",运算符将返回 "真"。 **or**如果任何条件为 "真",运算符返回 "真"。

使用 **and**来检查多个条件

num_0 = 12
num_1 = 8
res = num_0 >= 11 and num_1 >= 11
print(res)
# False

num_1 = 23
res = num_0 >= 11 and num_1 >= 11
print(res)
# True

使用 **or**来检查多个条件

num_0 = 12
num_1 = 8
res = num_0 >= 11 or num_1 >= 11
print(res)
# True

num_1 = 7
res = num_0 >= 15 or num_1 >= 14
print(res)
# False

布尔值

一个布尔值是 **True**或 False.带有布尔值的变量经常被用于程序中,以跟踪某些条件。

基本布尔值

subscription_active = True
is_cancelled = False

使用 **if**循环中的语句

循环中的一个 **if**循环中的语句是评估一个范围内的数字列表并根据某些条件对它们采取行动的好方法。这第一个例子是经典的fizzbuzz问题。我们想在1到15的数字上循环,在每个迭代中,为每个能被3整除的数字打印fizz,为每个能被5整除的数字打印buzz,为每个能被3和5整除的数字打印fizzbuzz。 如果数字不能被3或5整除,则打印一个信息,表示在给定的迭代中没有匹配的条件。

for i in range(1, 16):
    if i % 3 == 0 and i % 5 == 0:
        print(f'iteration {i} fizzbuzz!')
    elif i % 3 == 0:
        print(f'iteration {i} fizz!')
    elif i % 5 == 0:
        print(f'iteration {i} buzz!')
    else:
        print(f'--none on iteration {i}--')
--none on iteration 1--
--none on iteration 2--
iteration 3 fizz!
--none on iteration 4--
iteration 5 buzz!
iteration 6 fizz!
--none on iteration 7--
--none on iteration 8--
iteration 9 fizz!
iteration 10 buzz!
--none on iteration 11--
iteration 12 fizz!
--none on iteration 13--
--none on iteration 14--
iteration 15 fizzbuzz!

上面的例子是在for循环中使用 **if**语句在一个for循环中使用。我们也可以在while循环中使用 **if**语句在while循环中使用。

i = 1
while i < 16:
    if i % 3 == 0 and i % 5 == 0:
        print(f'iteration {i} fizzbuzz!')
    elif i % 3 == 0:
        print(f'iteration {i} fizz!')
    elif i % 5 == 0:
        print(f'iteration {i} buzz!')
    else:
        print(f'--none on iteration {i}--')
    i = i + 1

猜测一个密语

prompt = "Guess the secret word "
secret = ""
while secret != 'swordfish':
    secret = input(prompt)
    if secret != 'swordfish':
        print(f'{secret} is not the secret word')
    else:
        print('swordfish is the secret word!')

python if statement inside while loop

使用一个标志

我们可以用一个标志来重写猜词游戏,就像这样。

prompt = "Guess the secret word "
active = True
while active:
    secret = input(prompt)
    if secret != 'swordfish':
        print(f'{secret} is not the secret word')
    else:
        print('swordfish is the secret word!')
        active = False

python if flag in while loop


循环的break和continue

你可以使用 **break**关键字和 **continue**关键字与任何 Python 的循环一起使用。例如,你可以使用 **break**来退出一个正在迭代列表或字典的for 循环。你可以使用 **continue**关键字来跳过在 list 或 dictionary 上循环的各种项目。

用以下方法退出一个循环 break

prompt = "What are your favorite colors? "
prompt += "Enter 'q' to quit. "
while True:
    color = input(prompt)
    if color == 'q':
        print("Thanks for sharing your colors!")
        break
    else:
        print(f"{color} is a great color!")

python break out of loop

使用 **continue**在一个循环中

already_watched = ['Top Gun', 'Star Wars', 'Lord Of The Rings']
prompt = "Choose a movie to watch. "
prompt += "Enter 'q' to quit. "
movies = []
while True:
    movie = input(prompt)
    if movie == 'q':
        break
    elif movie in already_watched:
        print(f"I already saw {movie}")
        continue
    else:
        movies.append(movie)
    print("Movies to watch:")
    for movie in movies:
        print(movie)

python continue in loop

防止无限循环

每个while循环都需要一个停止运行的方法,这样它就不会永远运行。如果没有办法让条件变成假的,循环就会无限地运行。这是不好的,因为你的程序可能会崩溃或你的计算机可能会耗尽内存。


从一个列表中删除所有出现的项目

在 Python 中,你可以使用 **remove()**方法从一个列表中删除一个项目。当与 while 循环结合使用时,它可以轻松地从列表中删除一个给定值的所有实例。

从一个程序列表中删除所有重复的内容

programs = ['Photoshop', 'Illustrator', 'InDesign', 'Animate', 'Illustrator', 'Acrobat', 'Illustrator']
print(programs)
while 'Illustrator' in programs:
    programs.remove('Illustrator')
print(programs)
['Photoshop', 'Illustrator', 'InDesign', 'Animate', 'Illustrator', 'Acrobat', 'Illustrator']
['Photoshop', 'InDesign', 'Animate', 'Acrobat']


Python If 语句摘要

Python中的if语句是流程控制的一种形式。它允许程序决定是否需要跳过一些指令,重复几次,或者从众多指令中选择一条。正是流程控制语句告诉 Python 要运行哪些指令,在什么条件下运行这些指令。在本教程中,我们看到了 if 语句、if-else 语句、if-elif-else 链,以及许多条件测试的例子。