1.8. Type Conversions#
It is often useful to change the type of your variables. This is called casting. Here are some useful functions:
int(): convert to integerfloat(): convert to floatstr(): convert to string
Question 1
What do you think the output of the following code will be?
x = '2'
y = '7'
print(int(x) + int(y))
Solution
9
x and y are initially strings, but both of these are converted to integers before they are added together. This means we are adding the integers 2 and 7 which gives 9.
Question 2
What do you think the output of the following code will be?
x = 3
y = 5
z = str(x)
print(z * y)
Solution
Solution is locked
Question 3
What do you think the output of the following code will be?
x = '1'
y = '2'
print(float( x + y))
Solution
Solution is locked
Code challenge: Nesting
The following code takes input from a user, converts it to an integer and then adds 1.
n = input('Enter a number: ')
n = int(n)
print(n + 1)
Can you rewrite this code in just two lines?
Note
While it might look nicer to reduce the size of your code by combining multiple lines into one, spreading your code over more lines might make it easier for other people to read. In general, try to make your code easy to read. This will come with experience but it’s something to keep in mind.
Solution
Solution is locked