python的if和else、for、while语法,Python(五)语法(if,elif,else 条件判断 for in,while 循环)...

判断

计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。

如下例子

# -*- 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值