以 10 为底的 int() 的无效文字:'' 错误

invalid literal for int() with base 10: '' error

我大约 5 周前才开始编写代码,我正在为我的游戏开发编写代码 class,但我一直被一个问题困住了。当我 运行 我的代码时,我收到 "ValueError: invalid literal for int() with base 10: ''" 错误并且我不确定我做错了什么。我会 post 我的代码如下。任何帮助表示赞赏。谢谢!

start = 0
def addition(num1):
    return num1 + num1

def square(num):
    print("I'm in square")
    return num * num

def display(message):
    """Display game instuctions"""
    print(message)
def instructions():
    """Display game instuctions"""
    print("Welcome to the world's greatest game")


def main():
    instructions()
    scores = [("Roger", 3456), ("Justin", 2320), ("Beth", 1422)]

    start = input("Would you like to view the high score options? y/n ")
    if start == "y":
        print("""\
        Hello! Welcome to the high scores!
        Here are the current high score leaders!:
        """)
        print(scores)
        print("""\n\
        0 - Sort high scores
        1 - Add high score
        2 - Reverse the order
        3 - Remove a score
        4 - Square a number
        5 - Add 2 numbers together
        """)
        option = int(input())
        while option < 6:
            start = int(input("Please enter your selection")) 
            print(scores)
            if option == 0:
                scores.sort()
                print("These are the scores sorted alphabetically")
                print(scores)
            if option == 1:
                print(scores)
                print("Please enter your name and score; After entering your name, hit the return key and enter your score")
                name = input()
                score = int(input())
                entry = (name,score)
                scores.append(entry)
                print(scores)
            if option == 2:
                print(scores)
                scores.reverse()
                print("\nHere are the scores reversed")
                print(scores)
            if option == 3:
                print(scores)
                print("Please enter the high score you would like to remove. After typing the name, hit the return key and enter the score")
                name1 = input()
                score1 = int(input())
                remove = (name1,score1)
                scores.remove(remove)
                print(scores)
            if option == 4:
                val = int(input("Give me a number to square"))
                sqd = square(val)
                print(sqd)
            if option == 5:
                val0 = int(input("Give me one number"))
                val1 = int(input("Give me another number"))
                addi = (val0 + val1)
                print(addi)

main()

当您输入的不是数字时可能会发生这种情况,因此 int() 会失败。

例如:

>>> int(input())
hey
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hey'

要解决此问题,您可以通过 try/except 子句和循环不断请求输入,直到它成为 int

这很可能发生在您的代码中,因为您在循环开始时要求用户输入两次。

...
option = int(input())
while option < 6:
  start = int(input("Please enter your selection")) 
...

这也意味着他们首先输入的任何内容(在空提示中,这可能是您通过 acident 输入空字符串的地方)将始终是选项(即您的 start 变量永远不会用于确定选择哪个选项)。也许只保留一个变量(例如,option)并将您的代码更改为:

option = int(input("Please enter your selection"))
while option < 6
  ...
  option = option = int(input("Please enter your selection"))

如果您想在输入非整数时显示某种错误并退出程序,您可以使用 try-except 块:

...
try:
  option = int(input("Please enter your selection")) 
  while option < 6:  
    ...
    option = int(input("Please enter your selection")) 
except ValueError:
  print("Error!")
  1. 您输入字符串值并尝试将字符串转换为整数。

例如

>>> int(raw_input())
e
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'e'
>>> 
  1. 使用if - elif

例如

if option == 0:
    # Do coding for option 0
elif option==1:
    # Do coding for option 1