【问题标题】:Empty Input line raises an error in Python 3.3空输入行在 Python 3.3 中引发错误
【发布时间】:2019-04-27 11:14:22
【问题描述】:

我是 Python 新手,正在尝试一些我在网上找到的练习。我正在忙的那个需要首先输入文本,然后是整数输入。 我卡在引发错误的整数输入上。
当我第一次遇到错误时,我已经开始稍微修改代码以测试自己。
最终将其更改为与示例/练习完全相同,但两者都在同一行上导致相同的错误。
引发的错误是:

Traceback (most recent call last):
  File ************************ line 7, in <module>
    numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: '' 

我检查了一下,发现当输入为空时它会被触发,但根据我所阅读的内容,其余代码应该可以处理这个问题。

numOfGuests = int(input())
if numOfGuests:

如果没有输入任何内容,我希望代码会再次要求输入,但会出现错误。
非常感谢。

【问题讨论】:

    标签: python-3.3


    【解决方案1】:

    更新:
    我设法找到了一种解决方法,即使它不能回答我的问题,我也会接受它。
    对于任何感兴趣的人,这就是我所做的:
    我改变了:

    numOfGuests=int(input())  
    

    到:

    numOfGuests=input()  
    

    只有在输入某些内容后,我才对其进行转换:

    numOfGuests=int(numOfGuests)  
    

    所以最后一个块是:

    numOfGuests=''
    while not numOfGuests:
        print('How many guests will you have?')
        numOfGuests = input()
    numOfGuests=int(numOfGuests)  
    

    任何改进它的想法或一些见解,将不胜感激。

    【讨论】:

      【解决方案2】:

      我知道这个问题已经 10 个月了,但我只想分享您遇到错误 ValueError 的原因。

      Traceback (most recent call last):
        File ************************ line 7, in <module>
          numOfGuests = int(input())
      ValueError: invalid literal for int() with base 10: '' 
      

      是因为input()函数读取任意值并将其转换为字符串类型。即使您尝试输入空或空白。

      示例代码:

      any_input = input("Input something: ")
      print(f"Your input is: [{any_input}]")
      

      输出:

      Input something: 
      Your input is: []
      

      然后空白或空字符串将在int() 函数中传递。 int() 函数将尝试将字符串转换为以 10 为底的整数。众所周知,没有空白或空数字。这就是为什么它给你一个ValueError

      为避免这种情况,我们需要在您的代码中使用 try-except/EAFP

      try:
          # Try to convert input to integer
          numOfGuests = int(input("How many guests will you have? "))
      except:
          # Handle Value Error
      

      并放入一个 While 循环中重复,直到输入有效。

      示例代码:

      while True:
          try:
              # Try to convert input to integer
              numOfGuests = int(input("How many guests will you have? "))
              # If input is valid go to next line
              break # End loop
          except:
              # Handle Value Error
              print("Invalid input!")
      print(f"The number of guest/s is: {numOfGuests}")
      

      输出:

      How many guest will you have? 3
      The number of guest/s is: 3
      

      【讨论】:

        猜你喜欢
        • 2014-06-06
        • 2013-03-27
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 2013-04-22
        • 2018-04-04
        • 1970-01-01
        相关资源
        最近更新 更多