[英]How can the user input both str and int with out crashing?
我正在寫一個日歷程序。 如果用戶輸入年份的負數,它將再次要求他們輸入正數,直到他們輸入。 如何編寫一段代碼,允許他們無限制地無數次輸入字母字母,直到它們最終變成正整數為止? 反之亦然? 如果他們寫了一個字母,那么-number然后是字母?
將輸入設置為int
現在將允許重復輸入字母。 但如果我把它拿出來,然后我就再也沒能間的int
def func():
first_year = (input("What year would you like to start?\n")) #input set to varibale for users desired start yea
while type(first_year) == str:
first_year = int(input("Please enter a number value. What year would you like to start?\n"))
while first_year < 0:
first_year = int(input("Please enter a nonnegative year. What year would you like to start?\n")) #while loop to make sure year is a valid positive year
print("You have chosen the year " + str(first_year) + " as your starting year")
end_year = int(input("What would you like to print up to?\n")) #input set to variable for users desired end year
while end_year < 0:
end_year = int(input("Please enter a nonnegative year. What year would you like to end with?\n"))
print("You have chosen the year " + str(end_year) + " as your ending year") #delete later
format = input("What date format do you want to print? Ex. with slashes ' 1/1/2000 ' or by printed month 'Januaray, 1, 2000' ? Please enter '-' for slashes or 'print' for printed month." )
input = raw_input("Give a number: ")
try:
input = int(input)
except ValueError:
# input is not parsable to string
do_something()
我將嘗試部分解決您的問題。 您可以嘗試使用isinstance()
這樣的東西。
def func():
first_year = (input("What year would you like to start?\n")) #input set to varibale for users desired start yea
if isinstance(first_year,(str,)): ## checks if first_year is of string type
## do whatever you want when its string.
elif isinstance(first_year,(int,)): ## checks if first_year is of int type
## do what you want when its int.
if first_year >= 0 : ### this checks for negative value
# go ahead with your program
else:
## ask the user to put positive values.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.