python条件循环语句_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("\nFinished 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("\nFinished 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

参考资料:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值