我有一個練習:
撰寫向用戶詢問整數的代碼,當給出 0 時停止回圈。最后,將所有給定的數字相加并列印出來。
到目前為止,我管理這個:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b a
print("The total sum of the numbers are {}".format(b))
但是,代碼需要檢查輸入并給出一條訊息,以防它不是整數。
在網上搜索時發現了這一點,但對于我的生活,我無法將這兩個任務結合起來。
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum num
print(total_sum)
break
我懷疑你需要一個if地方,但無法解決。
uj5u.com熱心網友回復:
根據您的嘗試,您可以合并這兩個任務,例如:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b a
print("The total sum of the numbers are {}".format(b))
uj5u.com熱心網友回復:
如果要使用 If 陳述句,則不需要 else:如果數字不為 0,它將重新開始,直到某個時候為 0。
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum num
if num == 0:
print(total_sum)
break
uj5u.com熱心網友回復:
由于input' 的回傳是一個字串,因此可以使用isnumericno 查看給定值是否為數字。
如果是這樣,可以將其轉換string為float并檢查給定float的是否正在integer使用,is_integer。
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b = a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462031.html
上一篇:如何迭代多個字典鍵串列(值)對
