Casting in Python is a way to convert a value from one datatype to another. For example, let's say you have a variable called age
that stores your age as a whole number (an int
datatype).
But you want to convert the value of that variable to a string so that you can print it out as part of a sentence.
To do that, you can use the str()
function to cast the value of the age
variable to a string, like this:
age = 10 # The age variable is an integer
# Use the str() function to cast the age to a string
age_str = str(age)
# Print out a sentence with the age
print("I am " + age_str + " years old.")
In this example, the str()
function is used to cast the value of the age
variable from an integer to a string.
This allows us to combine the value of the age
variable with some other text to create a sentence. Does that make sense? Let me know if you have any other questions.
QUIZ
-
What is casting in Python?
-
A) A way to convert a value from one data type to another
-
B) A way to combine values from different variables
-
C) A way to print out a sentence with a variable value
-
D) A way to define a new variable with a different data type
-
-
What function is used in the example to cast an integer to a string?
-
A) int()
-
B) str()
-
C) print()
-
D) variable()
-
-
What is the value of the age variable in the example?
-
A) "I am 10 years old"
-
B) 10
-
C) "10"
-
D) "age"
-
-
What is the value of the age_str variable in the example?
-
A) "I am 10 years old"
-
B) 10
-
C) "10"
-
D) "age"
-
-
What is the output of the print statement in the example?
-
A) I am 10 years old.
-
B) 10
-
C) 10 years old
-
D) age
-