String to Integer
When you read input from a user, it comes as a string. Use int() to convert a string containing a number into an actual integer.
age_str = "25"
age_int = int(age_str)
print(age_int + 5)
Try it Yourself →
Integer to String
Use str() to convert numbers into strings. This is essential when you need to combine numbers with text.
score = 95
message = "Your score is " + str(score)
print(message)
Try it Yourself →
Float Conversions
float() converts strings or integers to floats. int() on a float truncates the decimal part.
price_str = "19.99"
price_float = float(price_str)
print(price_float)
rounded = int(price_float)
print(rounded)
from_int = float(42)
print(from_int)
Try it Yourself →