Game Development Reference
In-Depth Information
Converting Strings to Integers with the
int()
Function
15. guess = int(guess)
In line 15, we call a new function called
int()
. The
int()
function takes one
argument. The
input()
function returned a string of text that player typed. But in our
program, we will want an integer, not a string. If the player enters
5
as their guess, the
input()
function will return the string value
'5'
and not the integer value
5
. Remember
that Python considers the string
'5'
and the integer 5 to be different values. So the
int()
function will take the string value we give it and return the integer value form of it.
Let's experiment with the
int()
function in the interactive shell. Try typing the
following:
>>> int('42')
42
>>> int(42)
42
>>> int('hello')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int('forty-two')
ValueError: invalid literal for int() with base
10: 'hello'
>>> int('forty-two')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
int('forty-two')
ValueError: invalid literal for int() with base
10: 'forty-two'
>>> int(' 42 ')
42
>>> 3 + int('2')
5
We can see that the
int('42')
call will return the integer value
42
, and that
int
(42)
will do the same (though it is kind of pointless to convert an integer to an integer).
However, even though you can pass a string to the
int()
function, you cannot just pass
any string. For example, passing
'hello'
to
int()
(like we do in the
int('hello')
call) will result in an error. The string we pass to
int()
must be made up of numbers.
The integer we pass to
int()
must also be numerical, rather than text, which is why