[英]How do i write a basic program that asks for a number and then prints out the sum from one to the number?
[英]Write a program using while loop, which prints the sum of every fifth number from 0 to 500 (including both 0 and 500)
这就是我所做的:任何人都可以告诉我哪里出错了吗?
num = 0
x = 1
while x <= 500:
num += x
x += 5
print(num)
你的缩进也是错误的。 它需要像这样
num = 0
x = 0
while x <= 500:
num += x
x += 5
print(num)
但是,如果您只想打印最终和,则可以在循环外使用打印语句
num = 0
x = 0
while x <= 500:
num += x
x += 5
print(num)
逻辑:我们必须使用 while 循环来检查每个数字。 我们必须检查数字是否可以被5整除,为此,我们必须放置if条件并继续加1以从0到500。如果条件满足,则添加到其初始值的变量是 0。你的代码:
x=0
r=0
while x<=500:
if x%5==0:
r+=x
x+=1
print(r)
或者你可以这样做,从0开始初始值,更新x的值应该是5,将它添加到初始值为0的变量中。你的替代代码:
x=0
r=0
while x<=500:
r+=x
x+=5
print(r)
第二个代码将帮助您纠正您的个人代码。 看一看
还有一种方式:
x = 0
acc = 0
while (x := x + 5) <= 500:
acc += x
这里我们在while()
使用赋值运算符来获取值,同时增加它。
使用range(start, stop, step)
和range(0, 500, 5)
参数很简单
# list of numbers
print([x for x in range(0, 501, 5)])
# sum of numbers
print(sum([x for x in range(0, 501, 5)]))
使用while 循环,您可以使用Python3.8
引入的:=
运算符。 它允许在表达式中进行变量赋值。
total = 0
i = iter(range(5, 501, 5))
while val := next(i, None):
if not val:
break
total += val
print('total : ', total)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.