【问题标题】:Integer Errors in PythonPython 中的整数错误
【发布时间】:2012-03-27 11:57:51
【问题描述】:

所以我做了一个非常简单的程序,从 99 开始倒计时(唱 99 瓶啤酒),但我总是遇到 2 个错误中的 1 个

#!/usr/bin/env python
print("This program sings the song 99 bottles of beer on the wall")
lim = input("What number do you want it to count down from?")
def sing():
    global lim
    while int(lim) >= 0:
        if int(lim) != 1 or int(lim) != 0:
            print(lim, "bottles of beer on the wall", lim, "bottles of beer")
            print("Take one down pass it around...")
            print(lim, "bottles of beer on the wall")
            input("\nPRESS ENTER\n")
            lim -= 1
sing()
TypeError: unsupported operand type(s) for -=: 'str' and 'int'

然后,当我将lim -= 1 更改为int(lim) -= 1 时,它会显示SyntaxError: illegal expression for augmented assignment

【问题讨论】:

  • 考虑:for bottles in range(lim, 0, -1): ....
  • 您使用的是 Python 2 还是 3?因为在 Python 3 中使用了 input()print() 函数,但是您的第一行脚本显示为:#!/usr/bin/env python 而不是 #!/usr/bin/env python3。你能指定你想运行哪一个吗?

标签: python math numbers integer


【解决方案1】:

您需要将 lim 从字符串转换为整数。试试这个:

lim = int(input("What number do you want it to count down from?"))

【讨论】:

  • 如果您这样做,您还可以删除在sing() 中出现的所有其他转换。
【解决方案2】:

如果您使用的是 Python 2.x(未指定),请改用 raw_input

lim = int(raw_input("What number do you want it to count down from?"))

从那里,您可以删除对int(lim) 的所有检查,因为lim 已经是一个整数。

【讨论】:

  • OP代码的第一行写着:#!/usr/bin/env python,但是print之后就像函数一样使用(谁知道呢,可能是来自__future__)。
【解决方案3】:

你会得到TypeError,因为lim 是一个字符串。而且字符串不支持-= 运算符:

>>> s = '10'
>>> s -= 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -=: 'str' and 'int'

您需要做的是将lim 转换为整数,如下所示:

lim = input('Insert number: ')
lim = int(lim)

之后不用担心print,它也可以打印整数,而不仅仅是字符串:)


我还要说您的第一行存在一个主要问题。从您的代码来看,这是:

#!/usr/bin/env python

应该是

#!/usr/bin/env python3

因为您使用 Python 3 语法/时尚编写代码。

你也可以去掉global 声明:

#!/usr/bin/env python3
def sing():
    print("This program sings the song 99 bottles of beer on the wall")
    lim = input("What number do you want it to count down from?")
    lim = int(lim)
    while lim > 1:
        print(lim, "bottles of beer on the wall", lim, "bottles of beer")
        print("Take one down pass it around...")
        print(lim, "bottles of beer on the wall")
        input("\nPRESS ENTER\n")
        lim -= 1
sing()

【讨论】:

  • input() 在 Python 2.x 中是完全有效的语法,它只是不像 raw_input 那样做。 input() 评估 2.x 中的代码;在 3.x 中,它只是读取它。
  • @Makoto:是的,但不是 OP 使用它的方式。之后就不需要转换为整数了。
猜你喜欢
  • 2015-01-05
  • 2017-08-20
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 2021-06-15
相关资源
最近更新 更多