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 = 123y = str(x)print(y) #"123"print(type(y)) #<class 'str'>Note
type(y)returns the type of the variabley.
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
strreturns 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)) #Falseprint(bool(1)) #Trueprint(bool("")) #Falseprint(bool("Hello")) #TrueIf we invoke the bool function without providing an argument, it will return False.
print(bool()) #Falseint()
int(x) converts x into an integer, where x can be any value.
- For floating point numbers, this truncates towards zero.
- If
xis 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 return123,int("-123")will return-123,int("123 ")will return123. We can also provide a second argument, which is the base of the number system to convert to. For example:int("123", 8)will return83because123in base 8 is83. - If
xis a Boolean, then it returns1if it’sTrue, otherwise0.
We can’t convert complex numbers to integers.
print(int(123.45)) #123print(int("-123")) #-123print(int("-1_234")) #-1234print(int(" -123 ")) #-123print(int("123", 8)) #83print(int(True)) #1print(int(False)) #0print(int(2+3j)) #TypeError: can't convert complex to intfloat()
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
xis 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 return123.45,float("-123.45")will return-123.45,float("123.45 ")will return123.45. The argument may also representNaN,Infinityor-Infinity. - If
xis a Boolean, then it returns1.0if it’sTrue, otherwise0.0.
We can’t convert complex numbers to floating point numbers.
print(float(123)) #123.0print(float("-123.45")) #-123.45print(float("123.45 ")) #123.45print(float("123_456.7_891_234 ")) #123456.7891234print(float("NaN")) #nanprint(float("Infinity")) #infprint(float("-Infinity")) #-infprint(float(True)) #1.0print(float(False)) #0.0print(float(2+3j)) #TypeError: can't convert complex to floatcomplex()
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
xis a string, then this string should represent a valid complex numberOp1xOp2yjwhere bothOp1andOp2can be+, or-(for theOp1it can be nothing), and optionally surrounded by whitespace. For example:complex("2+3j")will return2+3j,complex("3j")will return3j,complex(" 123.45+67.89j")will return123.45+67.89j. As both numbers are float, each one could also representNaN,Infinityor-Infinity. Lastly the complex number could be surrounded by brackets. - If
xis a Boolean, then it returns1.0if it’sTrue, otherwise0.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 + yprint(z)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 + yprint(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)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 integerprint(t)Exercise 3: A basic calculator
Write a program which asks the user to enter two numbers and add them together.
Please enter the first number: 10Please enter the second number: 20The sum of the two numbers is 30x = int(input("Please enter the first number: "))y = int(input("Please enter the second number: "))z = x + yprint("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.
Please enter the temperature in Celsius: 20The temperature in Fahrenheit is 68temp = float(input("Please enter the temperature in Celsius: "))fahrenheit = (temp * 9/5) + 32print("The temperature in Fahrenheit is", fahrenheit)