' int'无效的文字尝试将输入字符串转换为int时

时间:2017-11-02 18:15:08

标签: python

我已尝试将输入设为整数,但如果我输入一个字母,我会得到一个'

的无效字面值

请帮助。

def agecheck():

    quit_menu = False

    while quit_menu is False:

         age = input("\nEnter your age: ")

         if age >= "18":
             print("You are the correct age.")
         elif age < "18":
             print("Get off this website.")
         else:
             print("Enter a correct integer.")
             quit_menu = True

    agecheck()

2 个答案:

答案 0 :(得分:0)

如果使用>=<等运算符,输入和您要比较的内容都应该是整数。另外,我怀疑你实际上想要退出菜单,如果输入有效而不是无效,并继续循环直到用户输入一个整数。如果输入的内容无法转换为int,您还应该使代码异常安全。请尝试以下方法:

def agecheck():

    quit_menu = False

    while quit_menu == False:

         try:

             age = int(input("\nEnter your age: "))

             if age >= 18:

                 print("You are the correct age.")

             elif age < 18:

                 print("Get off this website.")

             quit_menu = True

         except:

             print("Enter a correct integer.")

agecheck()

答案 1 :(得分:0)

这是你可以尝试的东西 -

<button class="btn btn-primary" (click)="_click()" id="view-more-button">
  View More Map
</button>

它会运行三次,输入输入def agecheck(): ans = input("\n Enter your age: ") try: age = int(ans) if age >= 18: print("You are the correct age.") elif age < 18: print("Get off this website.") else: print("Enter a correct integer.") except ValueError: print("That wasn't a number") for i in range(3): agecheck() 420,并注意日志。