Python基础之条件控制操作示例【if语句】
作者:流年醉影 时间:2021-02-09 09:30:02
本文实例讲述了Python基础之条件控制操作。分享给大家供大家参考,具体如下:
if 语句
Python中if语句的一般形式如下所示:
if condition_1:
statement_block_1
elif condition_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代替了else if,所以if语句的关键字为:if – elif – else。
注意:
1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。
以下实例演示了狗的年龄计算判断:
age = int(input("Age of the dog: "))
print()
if age < 0:
print("This can hardly be true!")
elif age == 1:
print("about 14 human years")
elif age == 2:
print("about 22 human years")
elif age > 2:
human = 22 + (age -2)*5
print("Human years: ", human)
###
input('press Return>')
将以上脚本保存在dog.py文件中,并执行该脚本:
python dog.py
Age of the dog: 1
about 14 human years
以下为if中常用的操作运算符:
操作符 | 描述 |
---|---|
< | 小于 |
<= | 小于或等于 |
> | 大于 |
>= | 大于或等于 |
== | 等于,比较对象是否相等 |
!= | 不等于 |
# 程序演示了 == 操作符
# 使用数字 print(5 == 6)
# 使用变量
x = 5
y = 8
print(x == y)
以上实例输出结果:
False
False
high_low.py文件:
#!/usr/bin/python3
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("Guess the number!")
while guess != number:
guess = int(input("Is it... "))
if guess == number:
print("Hooray! You guessed it right!")
elif guess < number:
print("It's bigger...")
elif guess > number:
print("It's not so big.")
关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
来源:https://www.cnblogs.com/xiaofan130/p/8886220.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python绘制汉诺塔
![](https://img.aspxhome.com/file/2023/1/60511_0s.gif)
PHP格式化显示时间date()函数代码
![](https://img.aspxhome.com/file/2023/0/55460_0s.png)
asp 数组 重复删除函数代码
表格可读性提升分析
![](https://img.aspxhome.com/file/UploadPic/20105/19/readability_table-34s.png)
python列表的常用操作方法小结
如何往SQL Server数据库传递日期数据?
Http头 Range、Content-Range
多个域名后缀同时查询的域名查询系统代码
python运行cmd命令行的3种方法总结
HTML和CSS中的视觉语义
![](https://img.aspxhome.com/file/UploadPic/20107/9/01-27s.jpg)
定位?浮动?自适应?
![](https://img.aspxhome.com/file/UploadPic/20086/30/2008630142536281s.jpg)
注册表单的改进分解
![](https://img.aspxhome.com/file/UploadPic/20085/31/2008531172251994s.gif)
如何在Access报表中每隔N行显示一条粗线
python+flask编写一个简单的登录接口
![](https://img.aspxhome.com/file/2023/1/68931_0s.png)
mysql 主从服务器的简单配置
asp如何在线更改密码?
Oracle 10g的DBA无法登录解决方案
mysql数据库你需要特别注意的23个事项
PHP 危险函数全解析
python中torch.nn.identity()方法详解
![](https://img.aspxhome.com/file/2023/9/67399_0s.png)