2.6 Type conversion functions
Type conversion functions enable flexibility and ensure that our programs can handle different types of data effectively.
The input()
function always returns a string. If you need a different type (like an integer or a float), you must convert it using int()
or float()
.
2.6a Input with integer conversion
By using the type conversion function int()
, we can convert the input string(str) to integer(int).
Example 2.6.1 - This program asks the user to enter their age. Since input()
returns a string, we use int(age)
to convert the input to an integer. Then, it prints the age.
Note that we are allowed to insert age as integer since we are using the commas in the print()
function. This method automatically converts non-string arguments to strings.
Example 2.6.2 - This example will cause a runtime error, because we can only concatenate string (str) and not int to str.
Example 2.6.3 - The following example works fine because we are treating age as text by default, and we are not converting it to a whole number. But if we wanted to do math with the age, we would have to turn it into a whole number like in example 2.6.1
2.6b Input with float conversion
By using the type converson function float()
, we can convert the input string to a float
Example 2.6.4 - This program prompts the user to enter their height in meters. The input string is converted to a float using float(height) and then printed.
height = input("Enter your height in meters: ")
height = float(height)
print("Your height is", height, "meters.")
2.6c Convert a value to a string with str() function
The str()
function in Python is used to convert a value into its string representation. Hence when you pass a value to str()
, it returns a string version of that value.
Example 2.6.5 - Convert a number to a string and use string concatenation (string + variable).
If we had to print the variablenumber
instead of number_str
, we would have got a TypeError telling us that we can only concatenate str (not "int") to str. Try it out.
Exercise 2.6.1 - Write a Python program that prompts the user to input their year of birth. Convert this input into an integer and store it in the same variable. Finally, print the message 'I was born in year xxxx', where 'xxxx' represents the year of birth entered.
You can refer to Output topic if you need help with the print()
function.
Exercise 2.6.1 - Model Answer - Make sure to work out the exercise before checking the model answer.