Types and castsSlide solved ✓
Types of values
In Python, values have types.
For example, the value
"test" is of the string type.
As another example, the value
123 is of the integer type. (Integer means
Why learn about types?
Mixing up types in ways that don't make logical sense results in errors.
You need to understand types, because if you don't, your programs will not work and you won't understand why.
Example of a type mistake
Adding two integers makes sense -- it creates a new integer.
Adding two strings makes sense too -- it concatenates the strings.
But what should happen when adding a string and a number? In Python, doing this this is not allowed and will produce an error.
Try running the program below to get an error.
Types of variables
When a variable holds a value of some type, we say that the variable has the same type.
For example, consider this code:
x = 123 s = "test"
We say that the
x variable has an integer type, and the
s variable has a
Strings versus integers
It is important to be completely clear on this: the string
"123" is not the
same as the number
123. The quotes makes the first value a string, while the
last value is an integer.
You can try the code below to see that the two are indeed not considered equal by Python.
Casting to integers
To cast a value means to change its type.
You can use the function
int to cast a string to an integer.
Here are some examples:
x = int("123") y = int("999")
Note that strings go into the
int function and integers come out.
Try casting to an integer
The code below casts the string
"1234" to the integer
1234 using the
Change the code so that it instead casts the string
"777" to the integer
777 before printing the result.
Try casting from scratch
Based on the previous examples, write code that uses the
int function to
cast the string
"999" to an integer. Then print the result.
Casting to strings
You can use the function
str to go in the other direction, casting an
integer to a string.
The code below is an example. It casts the integer
123 to the string
"123" and prints the result.
Change the program to cast the integer
42 to a string instead, while still
printing the result.
Try using str from scratch
Write code that computes
56*66, casts the result to a string, then prints
Uses for casting
By now you should understand why the
say_age function below is wrong and
causes an error if you run it.
say_age function adds a string to an integer, which isn't allowed in
Python. You can only add a string to a string. So the
years variable must
first be cast to a string.
Fix the function so that the call
say_age(99) correctly prints out "You are
99 years old".