Python循环语句
for 循环:可以遍历任何可迭代对象,如一个列表或者字符串。
用于有明确循环对象或次数。
语法格式:
for 变量名 in 可迭代对象:
# 循环主体 遍历可迭代对象中的所有元素实例:
# 循环打印列表中每个元素
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in sites:
print(site)
# 循环打印字典中所有体温异常人员的工号和体温
temperature_dict = {"101": 36.5, "102": 36.2, "103": 36.3, "104": 38.6, "105": 36.6}
for temperature_tuple in temperature_dict.items(): # 遍历字典中所有键值对组成的元祖列表
staff_id = temperature_tuple
temperature = temperature_tuple
if temperature >= 38:
print(staff_id, temperature)
# 以下写法与上面的代码功能相同,只是简化了变量的赋值操作
for staff_id, temperature in temperature_dict.items(): # 将元祖中元素的值按顺序赋值给 for 循环中的变量
if temperature >= 38:
print(staff_id, temperature)
# 循环打印字符串中每个字符
word = 'runoob'
for letter in word:
print(letter)
# 整数范围值可以配合 range() 函数使用
# 循环打印 0 到 5 的所有数字:
for number in range(0, 6):
print(number)
# 计算 1 + 2 + 3 ... + 100 的和并打印
total = 0
for i in range(1, 101):
total = total + i
print(total)关于 range() 函数用法参考:https://www.runoob.com/python3/python3-func-range.html
while 循环:
直到 判断条件 为假时结束循环,否则一直执行循环。
用于循环次数未知的情况。
语法格式:
while 判断条件:
# 循环主体,条件成立时执行实例:
# 计算 1 到 100 的总和
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n,sum))# 输出结果:1 到 100 之和为: 5050
#用户输入任意数字求平均值,当输入q时终止程序
total = 0
count = 0
user_input = input("请输入数字(完成所有数字输入后,请输入q终止程序):")
while user_input != "q":
num = float(user_input)
total += num
count += 1
user_input = input("请输入数字(完成所有数字输入后,请输入q终止程序):")
if count == 0:
result = 0
else:
result = total / count
print("您输入的数字平均值为" + str(result))相关学习资料:
3小时快速入门Python
Python3教程
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]