Python条件控制与循环语句
Posted gzhjj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python条件控制与循环语句相关的知识,希望对你有一定的参考价值。
1. 条件控制
# if-elif-else结构
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
# Your admission cost is $5.
可以使用多个elif
代码块,也可以省略else
代码块。
1.1 使用if语句处理列表
# 确定列表不是空的
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("
Finished making your pizza!")
else:
print("Are you sure you want to plain pizza?")
# Are you sure you want to plain pizza?
# 使用多个列表
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("
Finished making your pizza!")
# Adding mushrooms.
# Sorry, we don't have french fries.
# Adding extra cheese.
#
# Finished making your pizza!
2. 循环语句
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n,sum))
# 1 到 100 之和为: 5050
2.1 while 循环使用 else 语句
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
# 0 小于 5
# 1 小于 5
# 2 小于 5
# 3 小于 5
# 4 小于 5
# 5 大于或等于 5
如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中。
while(True): print('Hello!')
注意:以上的无限循环你可以使用 CTRL+C 来中断循环。
2.2 for语句
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print (x)
# C
# C++
# Perl
# Python
2.3 break语句
n = 1
while n <= 10:
if n > 5: # 当n = 6时,条件满足,执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')
# 1
# 2
# 3
# 4
# 5
# END
2.4 continue语句
n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # 如果n是偶数,执行continue语句
continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
print(n)
# 1
# 3
# 5
# 7
# 9
参考资料:
- Python3 教程 | 菜鸟教程
- Python教程 - 廖雪峰的官方网站
- 《Python编程从入门到实践》——【美】Eric Matthes 著
以上是关于Python条件控制与循环语句的主要内容,如果未能解决你的问题,请参考以下文章