【问题标题】:invalid literal for int() with base 10: '' error以 10 为基数的 int() 的无效文字:“”错误
【发布时间】:2015-02-14 05:55:11
【问题描述】:

我大约 5 周前才开始编写代码,我正在为我的游戏开发课程编写代码,但我非常卡在一个问题上。当我运行我的代码时,我得到“ValueError: invalid literal for int() with base 10: ''”错误,我不确定我做错了什么。我将在下面发布我的代码。任何帮助表示赞赏。谢谢!

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。检查您的input 电话。

标签: python function loops python-3.x base


【解决方案1】:
  1. 您输入字符串值并尝试将字符串转换为 int。

例如

>>> 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

【讨论】:

    【解决方案2】:

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

    ...
    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!")
    

    【讨论】:

    • option = option = int(input("Please enter your selection"))option = int(input("Please enter your selection")) 有什么不同吗?
    【解决方案3】:

    当您输入的不是数字时,这可能会发生,因此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

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2013-03-11
      • 1970-01-01
      • 2017-12-06
      • 2013-07-27
      相关资源
      最近更新 更多