![](/img/trans.png)
[英]How to write the program that prints out all the positive integer values from 1 up to the input number and each pair of numbers is flipped?
[英]Write a program that prompts for an integer and prints the int, if anything else is entered ask again till a integer is input
我正在編寫一個程序,提示輸入一個整數並打印該整數,但如果輸入的不是整數,該程序會不斷要求輸入一個整數。
我不知道如何讓它正確重置。 我嘗試了不同的方法,但沒有任何效果。
到目前為止,這是我的代碼:
inp = input ("Enter a Integer:")
while inp.isdigit():
print (inp)
break
else:
print ("Enter a Integer")
有沒有人有一些建議?
最好遵循 python 請求寬恕而不是許可策略:
while True:
try:
k = input("integer:") # gets a string
k = int(k) # tries integer conversion
break # if success: break while True loop
except ValueError:
print("Try again.") # int() failed
print(k) # print the output
輸出:
integer:a
Try again.
integer:b
Try again.
integer:5
5
優點:這甚至適用於負整數, isdigit()
檢查不適用。
異常處理: https : //docs.python.org/3/tutorial/errors.html#handling-exceptions
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.