coding180 icon
Coding180
Casting in Python

Casting in Python

Home > Tutorials > Python for beginners > Python Datatypes


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

  1. What is casting in Python?

    1. A) A way to convert a value from one data type to another

    2. B) A way to combine values from different variables

    3. C) A way to print out a sentence with a variable value

    4. D) A way to define a new variable with a different data type

  2. What function is used in the example to cast an integer to a string?

    1. A) int()

    2. B) str()

    3. C) print()

    4. D) variable()

  3. What is the value of the age variable in the example?

    1. A) "I am 10 years old"

    2. B) 10

    3. C) "10"

    4. D) "age"

  4. What is the value of the age_str variable in the example?

    1. A) "I am 10 years old"

    2. B) 10

    3. C) "10"

    4. D) "age"

  5. What is the output of the print statement in the example?

    1. A) I am 10 years old.

    2. B) 10

    3. C) 10 years old

    4. D) age


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel