[英]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.