Python if条件语句
Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
if ...else 结构
if(表达式):
语句1
else:
语句2
实例:
#!/usr/bin/python
age = 19
if age >= 18:
print("you are old enough.")
else:
print("You are too young.")
if...elif..else结构
if(表达式1):
语句1
elif(表达式2:):
语句2
...
elif(表达式n):
语句n
else:
语句m
实例:
#!/usr/bin/python
age = 12
if age < 4:
print("your admission cost is $0")
elif age < 18:
print("your admission cost is $5")
else:
print("your admission cost is $10")
Python while语句
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:
while 判断条件:
执行语句...
执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件为false时,循环结束。
实例
#!/usr/bin/python
prompt = "\nTell me something, and i will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message = "" ##定义一个空字符,让python首次执行为了代码时有可供检查的东西
while message != 'quit': ##当message的值为quit时,才会停止循环
message = input(prompt)
print(message)
执行测试
Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program.ss
ss
Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program.quit
quit
使用break退出循环
如果需要立即退出while循环不再运行循环余下的代码,也不管条件测试的结果如何,可使用break语句,break语句用于控制程序流程,控制哪些代码执行,哪些代码不执行
实例
#!/usr/bin/python
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city = input(prompt)
if city == 'quit': ##当输入的为quit时,中断循环
break
else:
print("You have visited " + city.title() + "!" )
执行:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)new york
You have visited New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)beijing
You have visited Beijing!
在循环中使用continue ,continue 用于跳过该次循环
#!/usr/bin/python
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0: ##当前数字如果被2整除,跳出此次循环
continue
print(current_number)
来源:oschina
链接:https://my.oschina.net/u/4366211/blog/4020418