我剛剛開始學習 Python 并且正在嘗試處理用戶可能輸入的錯誤。程式所做的就是使用 math 模塊,向用戶詢問一個整數并回傳該數字的階乘。
我正在嘗試捕獲負數、浮點數和文本的錯誤。
如果我輸入一個整數,代碼就會像它應該的那樣運行。
當我輸入錯誤的值時,例如 -9 或 apple,try/except 似乎沒有捕獲錯誤并且我得到了回溯資訊。用戶不應該看到這一點。
任何建議或指示?
import math
from datetime import datetime
import time
num = 0
start = 0
end = 0
# max value is 2147483647
#if __name__ == '__main__':
try:
num = input("Enter a number: ")
except OverflowError:
print("Input cannot exceed 2147483647")
except ValueError:
print("Please enter a non-negative whole number")
except NameError:
print("Must be an integer")
else:
start = datetime.now()
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))
end = datetime.now()
print(f"Time taken in (hh:mm:ss.ms) is {end - start}")
如果重要的話,我在 Windows 10 Pro(64 位)PC 上使用 Python 3.10。
諾曼
uj5u.com熱心網友回復:
您的代碼缺少可能導致例外的操作:實際上,input('...')回傳一個表示任何用戶輸入的字串。這意味著您的num變數是一個字串(您可以通過列印來檢查type(num)。
您必須嘗試將其轉換為整數:
try:
num = int(input('...'))
except ValueError:
print('invalid input')
注意:如果用戶輸入值“-3”,它將被接受:字串將被轉換為整數-3,這是正確的。
如果用戶輸入單詞 like'apple'或 floats like 3.14,則引發的例外為ValueError.
我的建議是做這樣的事情:
try:
num = int(input('...'))
if num >= 0:
# computing factorial
else:
print('error: only positive numbers will be accepted')
return
except ValueError:
print('invalid input')
uj5u.com熱心網友回復:
那是因為 input() 不會僅僅因為您只需要一個數字就引發錯誤。您必須自己檢查輸入的型別,然后自己也提出錯誤。例如
if not isinstance("string", int):
raise ValueError
編輯:還可以在這里查看有關 input() 的更多資訊:https : //www.python-kurs.eu/python3_eingabe.php 它始終回傳一個字串,因此您必須以您想要的型別主動轉換您的輸入,并且在轉換期間/之后進行型別檢查
uj5u.com熱心網友回復:
我選擇了 yondaime 提供的路徑,并且非常接近我想要的。最終結果如下。
我感謝大家的意見。上一次我在 IBM 360 上的穿孔卡片上使用 Fortran 進行編程,甚至有點像編程。
我為問這些基本問題而道歉,但我真的在努力。
代碼有效但實際上并沒有指出究竟發生了哪個故障。我將嘗試弄清楚如何將輸入陳述句中的字串轉換為浮點數,并查看是否有余數(可能是模數?),以便用戶更好地提示出了什么問題。
import math
from datetime import datetime
import time
num = 0
start = 0
end = 0
try:
num = int(input('Enter a positive whole number: '))
if (num >= 0 and num <= 2147483647):
start = datetime.now()
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))
end = datetime.now()
else:
print('Number must be between 0 and 2147483647 are allowed.')
print(f"Time taken in (hh:mm:ss.ms) is {end - start}")
except ValueError:
print('Text or decimal numbers are not allowed. Please enter a whole number between 0 and 2147483647')
我有很多時間來學習,因為我退休后很無聊......
諾曼
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364697.html
