Python For GCSE
Casting is a programming technique used to change the data type used to store information. This is something we need to do fairly often in programs.
Study the following program,
name = input("Enter your name: ") age = int(input("Enter your age: ")) height = float(input("Enter your height in metres: ")) print("Name:", name) print("Age:", age) print("Height:", height)
When we use an input statement, the value we are getting is a string. Strings are character data. That's fine if we are wanting to store a person's name. If we are getting a whole number, for an age, we need to convert the input from string into an integer. Since the height is going to need some decimal places, we need to convert it to a float.
In the following example, we want to convert a number into a string so that we can concatenate (add) it to some text. We would get an error if we tried to do this without casting.
name = "Me" num = 123 username = name + str(num) print(username)
We can also get Python to tell us the data type for a variable or value. This can be useful if your program is not giving the result that you expect.
name = "Me" num = 123 username = name + str(num) height = 1.81 print(type(name)) print(type(num)) print(type(username)) print(type(height))