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循环也还有许多关于列表、字典、元组等的用法,以后再详细列举吧。