Python 条件语句

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在幻想森林这个神秘的领域中,一个充满迷人生物和魔法的世界,大多数人对此一无所知,对于有抱负的巫师来说,这里存在着一个绝佳的机会。你是著名巫师阿尔达(智者阿尔达)的最新学徒,他以掌控元素和咒语而闻名于世。

作为你训练的一部分,阿尔达设置了一系列挑战,这些挑战将考验你的逻辑能力和对神秘脚本——Python 条件语句的理解。你的目标是通过编写基于各种条件做出决策的咒语(程序)来应对这些挑战,就像任何熟练的巫师必须做的那样。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") subgraph Lab Skills python/conditional_statements -.-> lab-271532{{"Python 条件语句"}} end

解读基础之书

在这一步中,你将开始学习如何使用 Python 中的ifelifelse结构来做出决策。想象一下,你在《基础之书》中发现了一段描述如何通过观察森林中遇到的神秘生物的特征来确定其类型的内容。

这是你在/home/labex/project/creature_type.py中的第一个咒语:

## creature_type.py
creature = "Dragon"

if creature == "Dragon":
    print("The creature is a fiery Dragon!")
elif creature == "Unicorn":
    print("The creature is a majestic Unicorn!")
else:
    print("The creature is of unknown origin.")

在这段代码中,我们检查creature变量是否为龙或独角兽,并相应地打印一条消息。如果两者都不是,我们就打印该生物来源不明。

要运行这个 Python 脚本,请在/home/labex/project目录中使用以下命令:

python creature_type.py

预期结果应该是:

The creature is a fiery Dragon!

逻辑运算符的魔药

在幻想森林的深处,你接到了一项任务,要制作一种需要精确配料的魔药。阿尔达已经教过你在 Python 脚本中使用逻辑运算符andornot

在这一步中,你将创建一个咒语,帮助你根据当天的天气和湿度条件来决定需要哪些配料。

在名为/home/labex/project/potion_ingredients.py的文件中编写以下咒语:

## Determine the needed potion ingredients
weather = "sunny"
humidity = "high"

if weather == "rainy" and humidity == "high":
    print("Add a sunflower petal to counter the rain.")
elif weather == "sunny" or humidity == "moderate":
    print("Add a drop of honey for sweetness.")
else:
    print("No special ingredients are needed today.")

使用以下命令执行你的咒语:

python /home/labex/project/potion_ingredients.py

你应该会看到以下消息:

Add a drop of honey for sweetness.

总结

在这个实验中,你踏上了一段穿越幻想森林的奇幻旅程,扮演一名巫师学徒来掌握 Python 条件语句。我们设计这个实验时采用了引人入胜的叙事方式,以使学习诸如ifelifelse和逻辑运算符(andornot)等编程概念更具吸引力且易于理解。

通过沉浸在魔法世界中,你练习了控制 Python 咒语的流程,并在对任何 Python 巫师都至关重要的决策结构方面变得更加熟练。你编写和理解条件语句的能力将在你继续探索编程这个迷人而神秘的领域时对你大有帮助。