[Python]第七讲:if与while
2016-05-18 13:11
465 查看
条件判断
计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用
if语句实现:
age = 20 if age >= 18: print('your age is', age) print('adult')
根据Python的缩进规则,如果
if语句判断是
True,就把缩进的两行print语句执行了,否则,什么也不做。
也可以给
if添加一个
else语句,意思是,如果
if判断是
False,不要执行
if的内容,去把
else执行了:
age = 3 if age >= 18: print('your age is', age) print('adult') else: print('your age is', age) print('teenager')
注意不要少写了冒号
:。
当然上面的判断是很粗略的,完全可以用
elif做更细致的判断:
age = 3 if 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,所以,请测试并解释为什么下面的程序打印的是
teenager:
age = 20 if age >= 6: print('teenager') elif age >= 18: print('adult') else: print('kid')
if判断条件还可以简写,比如写:
if x: print('True')
只要
x是非零数值、非空字符串、非空list等,就判断为
True,否则为
False。
再议 input
最后看一个有问题的条件判断。很多同学会用input()读取用户的输入,这样可以自己输入,程序运行得更有意思:
birth = input('birth: ') if birth < 2000: print('00前') else: print('00后')
输入
1982,结果报错:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: str() > int()
这是因为
input()返回的数据类型是
str,
str不能直接和整数比较,必须先把
str转换成整数。Python提供了
int()函数来完成这件事情:
s = input('birth: ') birth = int(s) if birth < 2000: print('00前') else: print('00后')
再次运行,就可以得到正确地结果。但是,如果输入
abc呢?又会得到一个错误信息:
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'abc'
原来
int()函数发现一个字符串并不是合法的数字时就会报错,程序就退出了。
循环
要计算1+2+3,我们可以直接写表达式:>>> 1 + 2 + 3 6
要计算1+2+3+...+10,勉强也能写出来。
但是,要计算1+2+3+...+10000,直接写表达式就不可能了。
为了让计算机能计算成千上万次的重复运算,我们就需要循环语句。
Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子:
names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name)
执行这段代码,会依次打印
names的每一个元素:
Michael Bob Tracy
所以
for x in ...循环就是把每个元素代入变量
x,然后执行缩进块的语句。
再比如我们想计算1-10的整数之和,可以用一个
sum变量做累加:
sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x print(sum)
如果要计算1-100的整数之和,从1写到100有点困难,幸好Python提供一个
range()函数,可以生成一个整数序列,再通过
list()函数可以转换为list。比如
range(5)生成的序列是从0开始小于5的整数:
>>> list(range(5)) [0, 1, 2, 3, 4]
range(101)就可以生成0-100的整数序列,计算如下:
sum = 0 for x in range(101): sum = sum + x print(sum)
请自行运行上述代码,看看结果是不是当年高斯同学心算出的5050。
第二种循环是while循环,只要条件满足,就不断循环,条件不满足时退出循环。比如我们要计算100以内所有奇数之和,可以用while循环实现:
sum = 0 n = 99 while n > 0: sum = sum + n n = n - 2 print(sum)
在循环内部变量
n不断自减,直到变为
-1时,不再满足while条件,循环退出。
相关文章推荐
- Python的5个基本排序算法
- ubuntu 搭建python2.x 抓取环境
- 语音情感数据库&python实现文件名的批量更改
- python实例:Django实现登录、注册
- Python TypeError: not enough arguments for format string
- python fork()创建新的进程,daemon进程
- Python实用函数
- Python Tricks(五)—— 计算 list of lists 的长度(元素个数)
- Python函数的各种参数用法(含星号参数)
- python yield的初识,Iterator与Generator
- Python Tricks(四)—— list of lists 的flatten
- 同时装了Python3和Python2,怎么用pip?
- Python正则表达式
- [XPath/Python] XPath 与 lxml (二)XPath 语法 - iFantasticMe
- python遍历删除指定后缀文件
- Python特殊语法:filter、map、reduce、lambda
- Python学习笔记&接口测试总结
- python map reduce 将浮点字符串转为浮点数
- Python的input(),print()函数问题
- python2.7升级到python3后,用pip进行安装时报Fatal error in launcher:Unbale to create process using`""