Casting
Casting means taking a value and producing a new version of it with a different data type. Python gives you four casting functions, and you use one by putting the value inside its brackets: str() produces a string, int() produces an integer, float() produces a real number and bool() produces a Boolean.
Each cast hands back a brand new value of the type you asked for. That new value can be printed, stored in a different variable or used straight away inside an expression.
Casting does not change a variable by itself. The variable keeps its original type and value; only the single place where the cast appears works with the new type:
distance = "42"
print(int(distance) + 8)
print(distance + "8")
distance = int(distance) # the cast result is stored back
print(distance + 8)Output:
50
428
50On line 2 the cast is worked out first, so 8 is added to the integer 42 to give 50. Line 3 contains no cast, so distance is still a string and + joins the text instead. Line 4 assigns the cast result back into the same variable, so from then on distance really does hold an integer and line 5 adds two integers.
Python is a high-level language, and real programs use casting to control the data type used in one particular expression or assignment:
+.OCR GCSE Computer Science · Casting