4️⃣

2.4 Casting

Casting

However, you can change strings into integers or floating numbers, but only if they’re numbers already. If you want x = '5' to be x = 5, you can say int(x) or float(x), but the float turns it into 5.0. But this method only works if your variable is a number. If it has any letters in it at all, then trying to turn it into an integer or float will give you an error.
x = '5' y = '6' sum = int(x) + int(y) # this is 11 because x and y were converted to integers print(sum) a = 5 message = "Hello!" a = str(a) # converts to string so that concatenation works print(message + " " + a)
View code on GitHub.
💡
Note: If you want to know the type of a variable, you can use the type() function. For example:
# print the type of a variable a = 5 print(type(a)) # prints the <class 'int'>
View code on GitHub.

Practice

Int

Set a variable x to “12” and turn it into an integer. Print the result.

Float

Write a program that takes a number from the user and stores it in a variable as a floating point number. Cast the number to an integer and store it in another variable. Then print: (floating point number) = (integer). Also print the type of the floating point variable. Remember! type(variable_name) will return the data type of a variable.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.