如何在循环中允许字符串值?蟒蛇

时间:2017-09-19 23:59:47

标签: python

while age > 2018:
    print ("If that were true, you would not exist")
    age = eval(input("In what year were you actually born?"))
while age <= 1999:
    print ("if that were true you would have graduated")
    age = eval(input("In what year were you actually born?"))
while age == str():
    print ("Sorry I didn't understand that, make sure you only use integers in your year of birth")
    age = eval(input("in what year were you born?"))


num = int(input("what is your favourite number?"))
name = str(input("What is your name?"))
the_sum(age, num, name)

句()

我怎样才能接受str作为对任何一个问题的回答并重述问题而不是报告错误?

3 个答案:

答案 0 :(得分:1)

# keep going until a valid year is entered
while True:

    # keep prompting until a number is entered
    while True:
        year = input("In what year were you born? ")
        if year.isdigit():
            break
        else:
            print("That is not a number.  Please try again.")

    # we broke out of the input loop, so it's a number.  convert to integer
    year = int(year)

    if year > 2018:
        print ("If that were true, you would not exist")

    elif year <= 1999:
        print ("if that were true you would have graduated")

    else:
        # success!  break out of the outer loop
        break

答案 1 :(得分:0)

这里有几个问题。一个是age永远不会被初始化 - 你需要在一开始就要求它。另一个是在Python 2中,input将运行任何输入并评估为评估的任何内容。你真正想要做的是接受作为输入的字符串,你可以使用Python 2中的raw_input或Python 3中的inputeval(input())将尝试评估无论input返回什么,如果你输入一个数字,这是一个整数,但是eval想要接受一个字符串。最后,你永远不会定义the_sum,但我会假设你已将它定义在其他地方并且没有给我们。

这给了我们

age = int(raw_input("In what year were you born?"))
while age > 2018:
    print ("If that were true, you would not exist")
    age = int(raw_input("In what year were you actually born?"))
while age <= 1999:
    print ("if that were true you would have graduated")
    age = int(raw_input("In what year were you actually born?"))
while age == str():
    print ("Sorry I didn't understand that, make sure you only use integers in your year of birth")
    age = int(raw_input("in what year were you born?"))

num = int(raw_input("what is your favourite number?"))
name = raw_input("What is your name?")
the_sum(age, num, name)

如果您使用的是Python 3,请在上面的代码块中将所有raw_input替换为input

答案 2 :(得分:0)

您的while循环似乎无效,并且由于未定义age而导致错误。相反,将整个事物包装在一个循环中,以便您继续接受输入,直到用户实际输入正确的内容。

year = None # If you don't preinitialize the variable name, then it will only exist in the local scope of the loop
while True:
    year = input("Please enter your year >>> ")
    if not year.isdigit():
        print("The entered value is not a valid integer.")
        continue # keep taking input
    year = int(year())
    if year >= 2018:
        print("That is in the future. Try again.")
    elif year <= 1999:
        print("You would have graduated by now (unless you keep failing school). Try again.")
    else: break # the value was correct :D

您可以执行try... except而不是if year and any(digit not in "0123456789" for digit in year)语句,如果输入为空或不是数字,则执行if语句。