1.2.2 Casting

Video

1.2.2 Casting

Some variable types are incompatible. In order to get output that contains both strings and floats in I'll Be the Judge of That, we will need to learn how to use casting to change a variable from one type to another.

Hint: If you turn a float into an int it will also remove any numbers after the decimal point!

Try It Yourself

The code editor below is pre-loaded with the casting.py file. This example shows how to:

  1. Get user input - input() always returns a string
  2. Cast to integer - Use int() to convert a string to an integer for math
  3. Cast to string - Use str() to convert a number back to a string for printing

Steps to follow:

  1. Run the code - Click "Run" and enter a number when prompted
  2. Watch the Variable Explorer - See how the type changes from string to int
  3. Experiment - Try different numbers and see what happens
  4. Modify the code - Try casting a float to an int and see what happens!
my_number = input("What's your favorite number? ")
# input() always gives us a string
my_number = int(my_number)  # Cast to integer for math
my_number = my_number + 2
result = "Your result is " + str(my_number)  # Cast back to string
print(result)

Note: The video shows creating a file in Spyder, but you're using the browser-based editor instead. The concepts are the same - you can edit code, run it, and see the output just like in the video!

Loading Python environment...