Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

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

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.

I get below error

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

Please help a noobie out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you take user input:

x = input()

Now x is a str. So, on this line:

    elif x % 2 == 0: #even

The % operator acts 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:

>>> "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.

x = int(input())

Now, it will do what you want:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...