[英]Write a program using while loop, which prints the sum of every fifth number from 0 to 500 (including both 0 and 500)
This is what I have done: Can anybody tell me where I went wrong?这就是我所做的:任何人都可以告诉我哪里出错了吗?
num = 0
x = 1
while x <= 500:
num += x
x += 5
print(num)
Your indentation is also wrong.你的缩进也是错误的。 It needs to be like this它需要像这样
num = 0
x = 0
while x <= 500:
num += x
x += 5
print(num)
But, if you want to print only the final sum, you can use the print statement outside loop但是,如果您只想打印最终和,则可以在循环外使用打印语句
num = 0
x = 0
while x <= 500:
num += x
x += 5
print(num)
Logic: We have to use while loop to check every number.逻辑:我们必须使用 while 循环来检查每个数字。 We have to check whether the number is divisible by 5 or not, for that, we have to put if condition and keep on adding +1 to go from 0 to 500. If the condition is satisfied, add to to a variable whose initial value is 0. You code:我们必须检查数字是否可以被5整除,为此,我们必须放置if条件并继续加1以从0到500。如果条件满足,则添加到其初始值的变量是 0。你的代码:
x=0
r=0
while x<=500:
if x%5==0:
r+=x
x+=1
print(r)
Or you can do it this way, start the initial value from 0, updating value of x should be 5, add it to variable whose initial value is 0. You alternative code:或者你可以这样做,从0开始初始值,更新x的值应该是5,将它添加到初始值为0的变量中。你的替代代码:
x=0
r=0
while x<=500:
r+=x
x+=5
print(r)
The second code will help you rectify your personal code.第二个代码将帮助您纠正您的个人代码。 Have a look看一看
Yet another way:还有一种方式:
x = 0
acc = 0
while (x := x + 5) <= 500:
acc += x
Here we use an assignment operator inside while()
to get the value while incrementing it at the same time.这里我们在while()
使用赋值运算符来获取值,同时增加它。
it's simple using range(start, stop, step)
with range(0, 500, 5)
parameter as使用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)]))
with while loop you can use :=
operator which is introduced in Python3.8
.使用while 循环,您可以使用Python3.8
引入的:=
运算符。 it allows variable assignments within expressions.它允许在表达式中进行变量赋值。
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.