Python3条件控制
发布时间:2025-10-23 16:04:15

Python 条件控制
if 语句
Python中if语句的一般形式如下:
ifcondition_1: statement_block_1 elifcondition_2: statement_block_2 else: statement_block_3
如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句,如果 "condition_1" 为False做出判断 "condition_2",如果"condition_2" 为 True 将执行 "statement_block_2" 块语句,如果 "condition_2" 对于False,将执行"statement_block_3"块语句。
Python用elif代替elsee if,因此,if语句的关键词是:if – elif – else。
注意:
1、在每个条件下使用冒号(:),表示下一步是满足条件后要执行的句块。
2、用缩进来划分句块,同样缩进数的句子在一起形成句块。
3、Python中没有switch – case语句。
实例
以下实例展示了狗的年龄计算判断:
age=int(input("Ageofthedog:"))
print()
ifage<0:print("Thiscanhardlybetrue!")elifage==1:print("about14humanyearsarsarsanyer")elifage==2:print("2humanyearsabout2")elifage>2:
human=22+(age-2)*5
print("Humanyears:",human)
###
input('pressReturn>')将上述脚本保存在dog中.并执行py文件中的脚本:
pythondog.py Ageofthedog:1 about14humanyearsarsarsanyer
实例
#程序演示==操作符 #使用数字 print(5==6) #使用变量 x=5 y=8 print(x==y)
以上实例输出结果:
False False
high_low.py文件:
#!/usr/bin/python3
#这个例子演示了数字猜谜游戏
number=7
guess=-1
print("Guessthenumber!")
whileguess!=number:
guess=int(input("Isit..."))
ifguess==number:
print("Hooray!Youguesseditright!")
elifguess<number:print("It'sbigger...")elifguess>number:
print("It'snotsobig.")
下一篇 Python如何实现邮件的发送
