Type Casting

Convert values between types with int(), float() and str().

Syntaxint(value) float(value) str(value)

Casting converts a value from one type to another using the type's function.

  • int(x) — convert to a whole number.
  • float(x) — convert to a decimal number.
  • str(x) — convert to text.

This matters because you cannot add a number to a string directly. Casting also fixes input from input(), which always arrives as text.

Example

Example · python
age_text = '25'
age = int(age_text)
print(age + 5)

print(float('3.14'))
print('Total: ' + str(100))

# Output:
# 30
# 3.14
# Total: 100

When to use it

  • A CLI tool converts a command-line argument string to an integer before using it as a repeat count.
  • A CSV reader casts each price column from string to float so arithmetic can be applied.
  • A display function converts a float result to a string for concatenation in a user-facing message.

More examples

String to int and float

Converts a string from user input to int and float so it can be used in arithmetic.

Example · python
user_input = '42'
count = int(user_input)
price_str = '9.99'
price = float(price_str)
print(count * 2)         # 84
print(price + 0.01)      # 10.0

Number to string for display

Casts a float to str so it can be joined with another string using +.

Example · python
total = 149.95
message = 'Your total is $' + str(total)
print(message)

# Output:
# Your total is $149.95

Int to float and truncation

Shows that int() truncates toward zero, not rounds, when casting from float.

Example · python
a = 7
b = float(a)    # 7.0
c = int(b)      # 7
d = int(3.9)    # 3 (truncates, not rounds)
print(b, c, d)

# Output:
# 7.0 7 3

Discussion

  • Be the first to comment on this lesson.