我正在写日历程序。如果用户输入年份的负数,则再次要求他们输入正数,直到他们这样做。我如何编写这段代码以允许他们无限次地输入alpabetical字母,直到他们最终在积极的int下?反之亦然?如果他们写了一封信,那么 - 编号然后写信吗?
将输入设置为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." )
答案 0 :(得分:0)
input = raw_input("Give a number: ")
try:
input = int(input)
except ValueError:
# input is not parsable to string
do_something()
答案 1 :(得分:0)
我会尝试部分解决您的问题。您可以尝试使用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.