< Prev  |  Home  |  Next >

Python Casting

Oh, there you are. I’m in danger of sounding like the world’s worst programmer, but I’m going to ask you to run another program that doesn’t work:

Actually, it’s not that the program doesn’t work. It’s that it doesn’t do what I wanted it to do. If I asked you to tell me what 3 lots of 4 is, I’d expect you to say 12 and not 444.

The problem with this program is related to the different data types we have met. The user enters text (a string) into the program, so Python keeps it as a string and multiplies it by 3. And remember how Python adds strings? Like this:

Which gives:


So we need to tell python to¬†turn the string into an integer. And that’s what casting is.

We can do this really simply. Just change the second line (line 4 below) of your ‘multiply by 3′ program to look like this:

This turns whatever is inside the brackets (the number the user entered) into an integer. Run your program again and you’ll see that now it really doesn’t work:

Traceback (most recent call last):
File "C:/Python32/test.py", line 3, in <module>
print("Your number tripled is : " + answer)
TypeError: Can't convert 'int' object to str implicitly


The clue to this error is in the last line of the error message. Python can only print strings to the screen, so we need to turn the integer back into a string to print it:

So we have two useful casting functions to turn something into an integer or a string.


Design and write a program to calculate the area of a circle. The user will enter the radius of the circle and the program will print the area. I’m not going to tell you how to calculate the area of a circle though. You’ve got fingers / Google.

Remember to produce a flowchart before you write your code.

< Prev  |  Home  |  Next >