Python 并非所有参数都在字符串格式化过程中转换。没有 % 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45499191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:04:54  来源:igfitidea点击:

not all arguments converted during string formatting.. NO % variables

pythonpython-3.xtypeerror

提问by Lance Tecson

x = input()
y = 1 
print (x)
while 1 == y:
if x == 1:
    y == y + 1
elif x % 2 == 0: #even
    x = x // 2
    print (x)
else:
    x = 3 * x + 1
    print (x)

If you know what the Collatz conjecture is, I'm trying to make a calculator for that. I want to have x as my input so I don't have to change x's number and save every time I want to try out a new number.

如果您知道 Collat​​z 猜想是什么,我正在尝试为此制作一个计算器。我想将 x 作为我的输入,这样每次我想尝试一个新数字时,我都不必更改 x 的数字并保存。

I get below error

我得到以下错误

TypeError: not all arguments converted during string formatting' at line 7.

类型错误:并非所有参数都在第 7 行的字符串格式化期间转换。

Please help a noobie out.

请帮助一个菜鸟。

回答by juanpa.arrivillaga

The problem is that you take user input:

问题是您接受用户输入:

x = input()

Now xis a str. So, on this line:

现在x是一个str. 所以,在这一行:

    elif x % 2 == 0: #even

The %operatoracts as a string interpolation operator.

%运算符充当字符串插值运算符

>>> mystring = "Here goes a string: %s and here an int: %d" % ('FOO', 88)
>>> print(mystring)
Here goes a string: FOO and here an int: 88
>>>

However, the inputyou gave does not have a format specifier, thus:

但是,input您提供的没有格式说明符,因此:

>>> "a string with no format specifier..." % 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>

You need to convert your user input into an intfor the %operator to perform the modulo operation.

您需要将您的用户输入转换为int%操作员执行模运算。

x = int(input())

Now, it will do what you want:

现在,它会做你想做的事:

>>> x = int(input("Gimme an int! "))
Gimme an int! 88
>>> x % 10
8
>>>