判断
计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。
如下例子
# -*- coding: utf-8 -*-
age =input('请输入年龄:')
if age==18:
print('年龄',age)
elif age>18:
print('超龄')
else :
print('年龄未达到')
E:\python\helloword>python elseif.py
请输入年龄:18
Traceback (most recent call last):
File "elseif.py", line 5, in
elif age>18:
TypeError: '>' not supported between instances of 'str' and 'int'
报错,这是因为input()返回的数据类型是str,str不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情:
# -*- coding: utf-8 -*-
age =input('请输入年龄:')
age =int(age)
if age==18:
print('年龄',age)
elif age>18:
print('超龄')
else :
print('年龄未达到')
E:\python\helloword>python elseif.py
请输入年龄:18
年龄 18
E:\python\helloword>python elseif.py
请输入年龄:19
超龄
E:\python\helloword>python elseif.py
请输入年龄:17
年龄未达到
循环
for...in循环 注意冒号不能省略
list=[1,2,3,4,5]
for x in list:
print(x)
E:\python\helloword>python for.py
1
2
3
4
5
Python提供一个range()函数,可以生成一个整数序列,再通过list()函数可以转换为list
list=list(range(101))
sum=0
for x in list:
sum=sum+x
print(sum)
E:\python\helloword>python for.py
5050
while循环
n=5
while n>0:
print(n)
n=n-1
E:\python\helloword>python while.py
5
4
3
2
1
break语句可以在循环过程中直接退出循环
list=range(5)
for num in list:
if num==2:
break
print(num)
0
1
continue语句可以提前结束本轮循环,并直接开始下一轮循环
list=range(5)
for num in list:
if num==2:
continue
print(num)
0
1
3
4