Python 用户如何在不崩溃的情况下同时输入str和int?
我正在写一个日历程序。如果用户输入年份的负数,它会再次要求用户输入正数,直到用户输入负数为止。我如何编写代码,允许他们错误地输入任意数量的字母,直到最后输入正整数?反之亦然?如果他们写一封信,那么-数字,然后是字母 将输入设置为int将允许重复输入字母。但是如果我把它拿出来,我就永远不能插入一个intPython 用户如何在不崩溃的情况下同时输入str和int?,python,Python,我正在写一个日历程序。如果用户输入年份的负数,它会再次要求用户输入正数,直到用户输入负数为止。我如何编写代码,允许他们错误地输入任意数量的字母,直到最后输入正整数?反之亦然?如果他们写一封信,那么-数字,然后是字母 将输入设置为int将允许重复输入字母。但是如果我把它拿出来,我就永远不能插入一个int 我将设法部分解决你的问题。您可以尝试使用类似这样的isinstance def func(): first_year = (input("What year would you like
我将设法部分解决你的问题。您可以尝试使用类似这样的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.
input = raw_input("Give a number: ")
try:
input = int(input)
except ValueError:
# input is not parsable to string
do_something()
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.