简体   繁体   English

用户如何在不崩溃的情况下输入str和int?

[英]How can the user input both str and int with out crashing?

I am writing a calendar program. 我正在写一个日历程序。 If the user enters a negative number for the year it ask them again to enter a positive until they do so. 如果用户输入年份的负数,它将再次要求他们输入正数,直到他们输入。 How can I write the piece of code to allow them to enter alpabetical letters by mistake unlimited number of times until they finally under a positive int? 如何编写一段代码,允许他们无限制地无数次输入字母字母,直到它们最终变成正整数为止? And vis versa? 反之亦然? If they write a letter then -number then letter? 如果他们写了一个字母,那么-number然后是字母?

Having the input set to an int will now allow letters to be enter repeated. 将输入设置为int现在将允许重复输入字母。 But If I take it out then I will never able to inter an 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()        

I will try to solve your issue partially. 我将尝试部分解决您的问题。 You can try using isinstance() something like this. 您可以尝试使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM