Python语法基础刻意练习:Task02(条件与循环)

1.条件语句
一个简单的示例:

if 2==2:
	print('right') #right

每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。如果测试的值为True,Python就将执行if语句后面的代码;如果为False,就忽略这些代码。

最简单的if语句,只有一个测试和一个操作。

if 2==2:
	print('right') #right
age=19
if age >=18:
	print('You are old enough to vote!')   #You are old enough to vote!

if-else语句

age=17
if age >=18:
	print('You are old enough to vote!')   
else:
	print('Sorry,you are too young to vote.')   #Sorry,you are too young to vote.

if-elif-else结构

age=12
if age <4:
	print('Your admission cost is $0.')   
elif age<18:
	print('Your admission cost is $5.')    #Your admission cost is $5.
else:
	print('Your admission cost is $10.')

if语句还有许多用法,比如处理列表、字典等,由于顺序在后面,就先不做介绍了。

2.循环语句
while循环

current_number=1
while current_number<=5:
	print(current_number)
	current_number+=1
# 1
# 2
# 3
# 4
# 5

while循环不断运行,直到指定的条件不满足为止。

让用户选择何时退出循环

prompt='\nTell me something,and I will repeat it.'
prompt+='\nEnter "quit" to end the program.'
message=''
while message!= 'quit':
	message=input(prompt)
	print(message)
	
#Tell me something,and I will repeat it.
#Enter "quit" to end the program.hello
#hello

#Tell me something,and I will repeat it.
#Enter "quit" to end the program.quit
#quit


------------------
(program exited with code: 0)

请按任意键继续. . .

使用标志退出循环

prompt='\nTell me something,and I will repeat it.'
prompt+='\nEnter "quit" to end the program.'
active=True
while active:
	message=input(prompt)
	if message=='quit':
		active=False
	else:
		print(message)

使用break退出循环

prompt='\nTell me something,and I will repeat it.'
prompt+='\nEnter "quit" to end the program.'
while True:
	city=input(prompt)
	if city=='quit':
		break
	else:
		print('i love '+city.title())

在循环中使用continue

current_number=0
while current_number<10:
	current_number+=1
	if current_number%2==0:
		continue
	print(current_number)
#1
#3
#5
#7
#9

continue语句让Python忽略余下的代码,并返回到循环的开头。

关于while循环也还有许多关于列表、字典、元组等的用法,以后再详细列举吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值