Python自学笔记
来源:互联网 发布:java判断白天还是晚上 编辑:程序博客网 时间:2024/06/14 07:40
条件判断在Python程序中,用if
语句实现,
根据Python的缩进规则,如果if
语句判断是True
,就把缩进的print
语句执行了。
给if
添加一个else
语句和elif
做更细致的判断、
注意不要少写了冒号:
age = 3if age >= 18: #不要忘写冒号 print('adult')elif age >= 6: #不要忘写冒号 print('teenager')else: #不要忘写冒号 print('kid')
elif
是else if
的缩写,完全可以有多个elif
,所以if
语句的完整形式就是:
if <条件判断1>: <执行1>elif <条件判断2>: <执行2>elif <条件判断3>: <执行3>else: <执行4>
if
语句执行有个特点,它是从上往下判断,如果在某个判断上是True
,把该判断对应的语句执行后,就忽略掉剩下的elif
和else
,所以以下程序虽然是年龄20岁,但是仍显示teenager
age = 20if age >= 6: #此处已经判断为真,不再继续判断 print('teenager')elif age >= 18: print('adult')else: print('kid')
if
判断条件还可以简写,比如写:
if x: print('True')
只要x
是非零数值、非空字符串、非空list
等,就判断为True
,否则为False
。
看一个有问题的条件判断,因为input()
返回的数据类型是str
,str
不能直接和整数比较,必须先把str
转换成整数。Python提供了int()
函数来完成这件事情:
s = input('birth: ')birth = int(s) #将str转换为整数if birth < 2000: print('00前')else: print('00后')]
阅读全文
0 0
- python自学笔记1
- python自学笔记 2
- python自学笔记 3
- python自学笔记 4
- python自学笔记
- Python自学笔记
- python自学笔记 20151126
- python 自学笔记
- python 自学笔记20151215
- python 自学笔记20151222
- python 自学笔记
- python 自学笔记 20151224
- Python自学笔记20160620
- PYTHON自学笔记1
- python自学笔记
- python自学笔记
- Python自学笔记
- Python自学笔记1
- 记一次排错经历-vivo手机标识问题
- Swift4.0 新特性----Swift标准库
- 深度学习—Xavier初始化方法
- LIB和DLL的区别与使用
- Python2.7+Opencv 人脸检测
- Python自学笔记
- 多线程编程学习三(线程间通信)
- 一个故事告诉你比特币的原理及运作机制
- 数据库杂谈
- os_mbox.c
- 点击选项卡后页面标题切换的实现
- STM32 DMA1和DMA2各通道一览表
- python中基本简洁函数笔记
- sonar问题修改