iScrE4m has shown how to fix your program, but I'll explain why you got that
TypeError: not all arguments converted during string formatting
error message.
When the Python interpreter sees %
after a string it interprets the %
as the string interpolation operator, which is used to convert data and insert it into a string.
For example
a = 2
b = 3
print "%d + %d = %d" % (a, b, a + b)
output
2 + 3 = 5
In your code, value
is a string so the interpreter tries to do string interpolation on value % 2
but then it sees that value
isn't a valid format string to format the data 2
, so it gives you that TypeError
.
In modern code use of %
-style string formatting is discouraged and the str.format
method is preferred. The equivalent to the above example is:
print "{0} + {1} = {2}".format(a, b, a + b)
In Python 2.7 and later you can omit the field numbers:
print "{} + {} = {}".format(a, b, a + b)
I have a few more comments on your code.
When calling a function in Python it's conventional to not put a space after the function name.
There's no need to use print
to print a prompt before calling raw_input
: you can (and should) supply the prompt as an argument to raw_input
.
When performing integer division you should use the integer division operator //
. A single slash works ok in Python 2, but in Python 3 it won't behave as expected here because it will perform a floating-point division. Eg, 10 / 2
will result in 5.0
.
When you need to perform a single operation on a variable and save the result of that operation back to the same variable you can use an augmented assignment operator. Eg,
instead of i = i + 1
you can write i += 1
;
instead of value = value // 2
you can write value //= 2
.
Also, instead of
value = value * 3
value = value + 1
you could do
value *= 3
value += 1
However, when performing multiple operations on a variable it's a little more compact and efficient to do them on one line. So it would be more usual to do:
value = value * 3 + 1
Putting it all together, here's a re-worked version of your code.
value = int(raw_input("Enter value: "))
i = 0
while True:
if value == 1:
break
elif value % 2 == 0:
value //= 2
else:
value = value * 3 + 1
i += 1
print "After {} attempts the conjecture has been demonstrated.".format(i)