[英]How do I write a for loop in Python to repeatedly ask the user to enter a number until they enter in a whole number (0, 1, 2, etc)?
[英]How to loop a function def in python until I write the number 0
我正在嘗試執行 def 函數並讓它添加輸入的任何數字的數字並在我鍵入數字“0”時停止,例如:
輸入數字:25 位數:7
輸入數字:38 位數:11
輸入數字:0 循環完成
我已經為輸入的數字的數字總和創建了代碼,但是當程序完成添加時,循環結束,但我正在尋找的是再次詢問另一個數字,直到最后輸入數字“0”循環結束:(
這是我的代碼:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
為了獲得連續輸入,您可以使用while True
並添加您的中斷條件,在這種情況下, if num == 0
。
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
更好的方法是讓sum_dig
接收您想要將數字求和的數字作為參數,然后使用 while 循環來處理獲取用戶輸入、將其轉換為數字並調用sum_digit
函數.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
這使您的代碼能夠遵守 單一職責原則,其中每個代碼單元都有一個單一的職責。 在這里,該函數負責獲取輸入數字並返回其數字總和(如其名稱所示),而循環負責連續讀取用戶輸入,對其進行轉換,檢查它是否不是退出值( 0),然后在輸入上調用處理函數並打印其輸出。
使用list()
將輸入數字(作為字符串)分解為數字列表,並使用列表理解對它們求和。 使用while True
進行無限循環,並使用return
退出。 使用f 字符串或格式化字符串文字打印數字總和:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
Rustam Garayev 的回答肯定解決了問題,但作為替代方案(因為我認為您也試圖以遞歸方式創建它),請考慮這個非常相似的(遞歸)版本:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.