indusai.co

Type casting

Casting means converting a value from one type to another. Python never converts between text and numbers silently, so you will do this often, especially with user input and file data.

The constructor functions

FunctionConverts toNotes
int(x)integerTruncates floats, parses whole number strings
float(x)floatParses decimal strings
str(x)stringWorks on anything
bool(x)booleanSee the truthiness rules in the Booleans lesson
list(x), tuple(x), set(x)collectionWorks on any iterable

Numbers to numbers

python
print(int(3.99))      # 3, decimal part dropped
print(int(-3.99))     # -3, truncates towards zero
print(float(7))       # 7.0
print(round(3.99))    # 4, if you want rounding instead

Strings to numbers

python
age = int("21")
price = float("49.99")
print(age + 1, price * 2)

Whitespace around the number is fine, but anything else raises a ValueError:

python
print(int("  42  "))
try:
    int("42 rupees")
except ValueError as e:
    print("Error:", e)

int("3.7") also fails because the string is not a whole number. Convert to float first if you need to: int(float("3.7")).

Numbers to strings

The most common need is building a message. str() works, but f-strings are cleaner:

python
count = 3
print("You have " + str(count) + " new messages")
print(f"You have {count} new messages")

Strings and lists

python
print(list("hello"))
print("".join(["h", "e", "l", "l", "o"]))
print("a,b,c".split(","))

Between collections

python
numbers = [3, 1, 3, 2, 1]
print(set(numbers))          # removes duplicates
print(tuple(numbers))
print(sorted(set(numbers)))  # unique and ordered

Reading input

input() always returns a string, even if the user types digits. Cast it before doing maths.

python
raw = input("How many tickets? ")
tickets = int(raw)
print("Total:", tickets * 250, "rupees")

Practice

  1. Convert the string "3.14159" to a float, multiply by 2, and print the result rounded to 3 decimal places.
  2. Take the list ["10", "20", "30"] and produce the integer sum 60.
  3. What does bool("False") return? Run it and explain why.