并非在字符串格式化期间转换所有参数.NO%变量

Lan*_*son 2 python typeerror python-3.x

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)
Run Code Online (Sandbox Code Playgroud)

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

我得到以下错误

TypeError:不是在第7行的字符串格式化期间转换的所有参数.

请帮助noobie.

jua*_*aga 7

问题是你接受用户输入:

x = input()
Run Code Online (Sandbox Code Playgroud)

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

    elif x % 2 == 0: #even
Run Code Online (Sandbox Code Playgroud)

%运营商作为一个字符串插值算.

>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)

但是,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
>>>
Run Code Online (Sandbox Code Playgroud)

您需要将用户输入转换int%运算符以执行模运算.

x = int(input())
Run Code Online (Sandbox Code Playgroud)

现在,它会做你想要的:

>>> x = int(input("Gimme an int! "))
Gimme an int! 88
>>> x % 10
8
>>>
Run Code Online (Sandbox Code Playgroud)