Type Conversion

Learn about type conversion in Python and how to convert values from one type to another.

Ali Berro

By Ali Berro

6 min read Section 5
From: Python Fundamentals: From Zero to Hero

Type Conversion

Casting is one of the most important concepts in programming. It is the process of converting a value from one type to another. For example, if you have a string "123" and you want to convert it to an integer, you can use the int() function.

As we have saw, the input() function always returns a string. So if we wanted to write a simple program which takes two integers from input, provided by the user and adds them, we would need to convert them to integers first, as the input() function would give us a string.

x = input("Enter the first number: ")
y = input("Enter the second number: ")
z = int(x) + int(y)
print(z)

Python provides multiple built-in functions to convert values from one type to another. Including:

  • str()
  • bool()
  • int()
  • float()
  • complex()

str()

str(x) converts x into a string, where x can be any value.

x = 123
y = str(x)
print(y) #"123"
print(type(y)) #<class 'str'>

Note

type(y) returns the type of the variable y.

If we invoke the str function without providing an argument, it will return an empty string.

Note

We may visit this in a later chapter, but str returns the __str__ method of the object if it exists, otherwise it returns the __repr__ method.

bool()

bool(x) returns False if x is falsy, otherwise it returns True. By default everything is considered truthy, except for:

  • Constants defined to be false: None, False,
  • Zero numeric values: 0, 0.0, 0j
  • Empty sequences and collections: '', (), [], {}, set(), range(0)
print(bool(0)) #False
print(bool(1)) #True
print(bool("")) #False
print(bool("Hello")) #True

If we invoke the bool function without providing an argument, it will return False.

print(bool()) #False

int()

int(x) converts x into an integer, where x can be any value.

  • For floating point numbers, this truncates towards zero.
  • If x is a string, then this literal can be preceded by + or - and be surrounded by whitespace (this string should represent an integer). For example: int("+123") will return 123, int("-123") will return -123, int("123 ") will return 123. We can also provide a second argument, which is the base of the number system to convert to. For example: int("123", 8) will return 83 because 123 in base 8 is 83.
  • If x is a Boolean, then it returns 1 if it’s True, otherwise 0.

We can’t convert complex numbers to integers.

print(int(123.45)) #123
print(int("-123")) #-123
print(int("-1_234")) #-1234
print(int(" -123 ")) #-123
print(int("123", 8)) #83
print(int(True)) #1
print(int(False)) #0
print(int(2+3j)) #TypeError: can't convert complex to int

float()

float(x) converts x into a floating point number, where x can be any value.

  • For integers, this converts the integer to a floating point number.
  • If x is a string, then this literal can be preceded by + or - and be surrounded by whitespace (this string should represent a floating point number). For example: float("+123.45") will return 123.45, float("-123.45") will return -123.45, float("123.45 ") will return 123.45. The argument may also represent NaN, Infinity or -Infinity.
  • If x is a Boolean, then it returns 1.0 if it’s True, otherwise 0.0.

We can’t convert complex numbers to floating point numbers.

print(float(123)) #123.0
print(float("-123.45")) #-123.45
print(float("123.45 ")) #123.45
print(float("123_456.7_891_234 ")) #123456.7891234
print(float("NaN")) #nan
print(float("Infinity")) #inf
print(float("-Infinity")) #-inf
print(float(True)) #1.0
print(float(False)) #0.0
print(float(2+3j)) #TypeError: can't convert complex to float

complex()

complex(x) converts x into a complex number, where x can be any value.

  • For integers and floating point numbers, this converts the number to a complex number with imaginary part 0.
  • If x is a string, then this string should represent a valid complex number Op1xOp2yj where both Op1 and Op2 can be +, or - (for the Op1 it can be nothing), and optionally surrounded by whitespace. For example: complex("2+3j") will return 2+3j, complex("3j") will return 3j, complex(" 123.45+67.89j") will return 123.45+67.89j. As both numbers are float, each one could also represent NaN, Infinity or -Infinity. Lastly the complex number could be surrounded by brackets.
  • If x is a Boolean, then it returns 1.0 if it’s True, otherwise 0.0.
  • The last variation allows us to provide two arguments, the first one is the real part, and the second one is the imaginary part.
print(complex(123)) #(123+0j)
print(complex(-123.45)) #(-123.45+0j)
print(complex(False)) #(0+0j)
print(complex("123.45")) #(123.45+0j)
print(complex("123.45+67.89j")) #(123.45+67.89j)
print(complex(" 123.45-67.89j ")) #(123.45-67.89j)
print(complex("(123.45+67.89j)")) #(123.45+67.89j)
print(complex(123, 456)) #(123+456j)

type()

type(x) returns the type of the variable x.

print(type(123)) #<class 'int'>
print(type(123.45)) #<class 'float'>
print(type(123.45+67.89j)) #<class 'complex'>
print(type(True)) #<class 'bool'>
print(type("123")) #<class 'str'>

Exercises

Exercise 1: Bug in the code

What is the bug here and how should we fix it?

x = input("Enter a number: ")
y = input("Enter another number: ")
z = x + y
print(z)
Answer:

The bug is that we are concatenating two strings, instead of adding two numbers. We should convert the input to numbers first.

x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
z = x + y
print(z)

Exercise 2: Bug in the code

What is the bug here and how should we fix it?

x = "1"
y = "234"
z = "56.78"
t = int(x) + int(y) + int(z)
print(t)
Answer:

The bug is that we are converting 56.78 to integer by directly calling the int constructor. This is wrong, as the string should represent a valid integer not a floating point number.

x = "1"
y = "234"
z = "56.78"
t = int(x) + int(y) + int(float(z)) # Convert it to float first, then to an integer
print(t)

Exercise 3: A basic calculator

Write a program which asks the user to enter two numbers and add them together.

Terminal window
Please enter the first number: 10
Please enter the second number: 20
The sum of the two numbers is 30
Answer:
x = int(input("Please enter the first number: "))
y = int(input("Please enter the second number: "))
z = x + y
print("The sum of the two numbers is", z)

Exercise 4: Find the output

Write a program which asks the user to enter the temperature in Celsius and converts it to Fahrenheit.

Terminal window
Please enter the temperature in Celsius: 20
The temperature in Fahrenheit is 68
Answer:
temp = float(input("Please enter the temperature in Celsius: "))
fahrenheit = (temp * 9/5) + 32
print("The temperature in Fahrenheit is", fahrenheit)

Course Progress

Section 5 of 17

Back to Course