Theory: If statement(理论:如果语句)

在某些情况下,您的程序仅在特定条件为真时才需要执行某些代码。可以在 Python 中设置该条件,在本主题中,我们将学习如何操作!

简单的 if 语句

因此,在 Python 中,只应在某种条件下执行的一段代码应该放在if 语句的主体中。该模式与英语中的模式相同:首先是关键字if,然后是条件,然后是要执行的表达式列表。条件始终是一个布尔表达式,即它的值等于True or  False。下面是一个带有条件表达式的代码的示例:

biscuits = 17
if biscuits >= 5:
    print("It's time for tea!")

请注意,条件以冒号结尾,新行以缩进开头。通常,使用 4 个空格来指定每个缩进级别。所有行都在同一缩进级别的一段代码称为代码块。在 Python 中,只有缩进用于分隔不同的代码块,因此,只有缩进显示了if满足语句时应该执行哪些代码行,以及应该独立if语句执行哪些代码行。查看以下示例:

if biscuits >= 5:
    print("It's time for tea!")
    print("What tea do you prefer?")
print("What about some chocolate?")

在此示例中,仅当有 5 个或更多饼干时才会打印行和 "。无论饼干的数量如何,都会打印该"It's time for tea!"行。"What tea do you prefer?"What about some chocolate?"

if 只有条件成立(布尔值为 True)时,才会执行语句,否则将被跳过。

布尔值基本上可以明确一段代码是否需要执行。由于比较结果是bool,因此将它们用作条件始终是一个好主意。

不过,有一个陷阱。您不应将相等的比较运算符==与赋值运算符混淆=。只有前者提供了适当的条件。尽量避免代码中出现这种常见错误。

嵌套 if 语句

if有时一个条件对于一个简单的语句来说太复杂了。在这种情况下,您可以使用所谓的嵌套if语句。嵌套的语句越if多,代码就越复杂,这通常不是一件好事。但是,这并不意味着您需要if不惜一切代价避免嵌套语句。让我们看一下下面的代码:

rainbow = "red, orange, yellow, green, blue, indigo, violet"
warm_colors = "red, yellow, orange"
my_color = "orange"

if my_color in rainbow:
    print("Wow, your color is in the rainbow!")
    if my_color in warm_colors:
        print("Oh, by the way, it's a warm color.")

上面的示例说明了一个嵌套if语句。如果变量my_color是包含彩虹颜色名称的字符串,我们输入第一条if 语句的主体。首先,我们打印消息,然后检查我们的颜色是否属于暖色。成员资格运算符in仅显示my_color是相应字符串的子字符串,rainbow还是warm_colors。就像算术比较一样,它返回一个布尔值。

以下是我们将在我们的案例中看到的内容:

Wow, your color is in the rainbow!
Oh, by the way, it's a warm color.

对于嵌套if语句,适当的缩进至关重要,因此不要忘记缩进以if关键字开头的每个语句。

概括

总而言之,在本主题中,我们学习了如何在 Python 中使用 if 语句编写和嵌套条件。

示例

花商 Lillian 发现,当鲜花数量为奇数时,更容易安排鲜花。所以,如果一束鲜花的数量恰好是偶数,她通常会多加一朵花。

n_flowers = int(input())
if n_flowers % 2 == 0:
    n_flowers += 1

渡船人卡戎将灵魂穿过冥河带到死者的世界,但这样做只是为了收费。毕竟是生意。

检查死者是否有硬币,如果有,打印 Welcome to Charon's boat!

最后通过打印消息,警告每个人 There is no turning back.

# read the value from the input
coin = bool(int(input()))  # don't modify this line, please
if coin:
    print("Welcome to Charon's boat!")

print('There is no turning back.')

任何食谱都以配料表开头。下面是一本食谱的摘录,其中包含一些菜肴的配料。编写一个程序,告诉你可以根据你所拥有的成分制作什么食谱。

输入格式:

某种成分的名称。

输出格式:

一条消息说“食物时间! ”其中“食物”代表含有这种成分的菜肴。例如,“披萨时间! ” 如果该成分出现在多个食谱中,请按照它们在食谱中出现的顺序将它们全部写下来。


样本输入 1:

basil

样本输出 1:

pasta time!

样本输入 2:

flour

样本输出 2:

apple pie time!
chocolate cake time!

pasta = "tomato, basil, garlic, salt, pasta, olive oil"
apple_pie = "apple, sugar, salt, cinnamon, flour, egg, butter"
ratatouille = "aubergine, carrot, onion, tomato, garlic, olive oil, pepper, salt"
chocolate_cake = "chocolate, sugar, salt, flour, coffee, butter"
omelette = "egg, milk, bacon, tomato, salt, pepper"
food = input('')
if food in pasta:
	print('pasta time!')
if food in apple_pie:
	print('apple pie time!')
if food in ratatouille:
	print('ratatouille time!')
if food in chocolate_cake:
	print('chocolate cake time!')
if food in omelette:
	print('omelette time!')

elif语句

下面的代码应该根据城市人口将城市分为 4 类(百万 - 大 - 中 - 小)。

if population > 1000000:
    print("This is a million city")
elif population > 350000:
    print("This is a large city")
elif population > 100000:
    print("This is a medium city")
else:
    print("This is a small city")

项目时间

目标

  1. 询问玩家一个可能的词。
  2. You survived!如果用户猜到单词,则打印。
  3. You lost!如果用户猜错了就打印。
顺便说一句, python应该是玩家需要猜到的词才能赢得游戏。
Example 1

H A N G M A N
Guess the word: > python
You survived!

Example 2

H A N G M A N
Guess the word: > java
You lost!

# Write your code here
print('H A N G M A N')
print('The game will be available soon.')
a = input('Guess the word: > ')
if a=='python':
    print('You survived!')
else:
    print('You lost!')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值