🎓 A1Learner
🔍

Python Casting

Casting is changing a value from one type to another type. Casting can turn text from input() into a number.

Text adds like text

Both values are text here, so + joins them.

first = "5"
second = "3"
print(first + second)

Turn text into a whole number

Now the value can join in maths.

text = "42"
number = int(text)
print(number)
print(number + 8)

Turn text into a decimal number

float() keeps the decimal part.

text = "2.5"
number = float(text)
print(number)

Turn a number into text

str() lets the number join with text.

number = 7
text = str(number)
print("Level " + text)

int() cuts the fraction

The part after the point is dropped.

print(int(3.9))

Bad text raises ValueError

Words that are not numbers cannot convert.

print(int("hello"))

Example

first_text = input("First price: ")
second_text = input("Second price: ")
first_price = int(first_text)
second_price = int(second_text)
total = first_price + second_price
print("Total:", total)

Key points

  • Casting: changing a value from one type to another
  • Use int() to turn a value into a whole number
  • Use float() to turn a value into a decimal number
  • Use str() to turn a value into text
  • ValueError: an error when the text is not a valid number
  • int() cuts off the fraction of a decimal number

In this example, you type 12 for the first price. You type 8 for the second price. Each input line stores text. Each int() line turns that text into a number. Python adds the two numbers to get the total. The last line prints the total.

Note

Casting makes a new value.

Store it if you want to keep it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What is int("15") + 5?