Converting Data Types

Converting Data Types#

Earlier in this chapter we used arithmetic operators to develop a Fahrenheit - Celsius temperature conversion formula. Imagine a scenario in which we want to convert a user-provided temperature.

We could use the input() function and then pass that input value to our conversion formula. Let’s try it.

temp = input("Enter a temperature in Fahrenheit: ")

# conversion formula
celsius = (temp - 32) * (5/9)

# show celsius output
print(temp + " degrees in Fahrenheit is " + celsius + " degrees in Celsius")

Except this program results in a TypeError. In Python, this is a data type error indicating we’re trying to perform an operation that’s not compatible with the data types we’re using.

Python includes built-in functions that let us convert specific data types.

Boolean
NamePython SyntaxExampleDescription
Stringstr()"Hello World!"String of character
Integerint()7Whole number
Floatfloat()1.5Decimal number, or number with floating point values
bool()TrueTwo-state system that typically represents true/false values
Nothing/Null/NoneTypeNoneTypeNoneNo value

Remember our program from an earlier section on concatenation:

# trying concatenation with an integer and string
year = 2023
school = "Notre Dame"

print(school + ", Class of " + year)

We can use the str() function to convert year from an integer to a string object. That will allow the final print() statement to run.

# assign year variable
year = 2023

# convert to string
year = str(year)

# assign school variable
school = "Notre Dame"

# output
print(school + ", Class of " + year)

We could combine the first two lines of this program to convert the data type when we create the variable.

# assign year variable and convert to string
year = str(2023)

# assign school variable
school = "Notre Dame"

# output
print(school + ", Class of " + year)

An alternate workflow for instructing Python to treat 2023 as a string of characters:

# assign year variable as string
year = "2023"

# assign school variable
school = "Notre Dame"

# output
print(school + ", Class of " + year)

Comprehension Check#

Clipboard icon Converting Data Types Comprehension Check

Application#

Q8: Write a program that prompts the user to enter two numbers, converts the input values to integers, adds them, and reports the result. Answer to this question includes program + comments that document process and explain your code.

Q9: Write a program that asks the user to think of a month and then enter the number of days in that month. Your program should then compute the number of minutes in the month, and report the result. Answer to this question includes program + comments that document process and explain your code.

Q10: Write a program that prompts the user to enter a temperature in Fahrenheit, and reports the equivalent temperature in Celsius. Answer to this question includes program + comments that document process and explain your code.