Files
2025PY/day09/03-练习1.py
2025-05-22 16:50:44 +08:00

31 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 1.使用循环不断要求用户输入数字,计算所有输入数字的和,直到用户输入 0 时结束。
# 分析
# 题目中出现中断循环或者结束循环(break)
# 第一步:不断用户输入数字(依靠无限循环不断输入)
# while True: #这里的条件一直满足,无限循环
# input('请输入你要相加的数字:')
# 第二步:计算所有输入数字的和(迭代:上一次的结果 + 下一次的值)
# sum = 0
# i = 1
# while i <= 10:# i的值从1-10
# sum += i # sum = sum + i
# # 上面代码的第一次执行sum = 0 + 1 = 1
# # 上面代码的第二次执行sum = sum + i = 1 + 2 后面的sum就是上一次的结果1 + i的下一次的值2
# i += 1
# print(sum) # 55
# 第三步:直到用户输入 0 时结束(if判断用户输入的数字如果是0,结束循环break)
sum = 0 # 求和的初始值(第一次赋值,存储所有输入数字的和)
while True:
value = int(input('请输入你要相加的数字:')) # 每次输入的值给value
sum += value # 累加(迭代)
if value == 0: # 如果用户输入的数字是0,结束循环
break
print(f'你输入的所有数字的和是{sum}')