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
not all arguments converted during string formatting.. NO % variables
提问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.
如果您知道 Collatz 猜想是什么,我正在尝试为此制作一个计算器。我想将 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 x
is 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 input
you 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 int
for 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
>>>