Course Outline (Part 7)

There may be times when you want to specify a type onto a variable. This can be done with casting. Python is an object-oriented language, and as such it uses classes to define data types, including its primitive types.

Casting in Python is therefore done using constructor functions.


1. Implicit Casting

Implicit casting (or implicit type conversion) is automatically performed by the Python interpreter without any user involvement. Python automatically converts a smaller data type to a larger data type to prevent data loss.

For example, when you add an int and a float, Python will implicitly convert the int to a float.

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

print(type(integer_number)) # <class 'int'>
print(type(float_number))   # <class 'float'>

print("Value:", new_number) # Value: 124.23
print("Type:", type(new_number)) # <class 'float'>

As seen above, Python implicitly cast the integer 123 to 123.0 before adding it to 1.23.


2. Explicit Casting (int(), float(), str())

Explicit casting is when you force a variable to be a specific data type using built-in functions.

Casting to Integers (int())

Constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number).

x = int(1)     # x will be 1
y = int(2.8)   # y will be 2
z = int("3")   # z will be 3

Casting to Floats (float())

Constructs a float number from an integer literal, a float literal, or a string literal (providing the string represents a float or an integer).

x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2

Casting to Strings (str())

Constructs a string from a wide variety of data types, including strings, integer literals, and float literals.

x = str("s1")  # x will be 's1'
y = str(2)     # y will be '2'
z = str(3.0)   # z will be '3.0'

3. When to use casting

Casting is primarily used when:

  1. Handling User Input: The input() function always returns a string. If you need the user to input a number to perform math, you must cast it.
    age = input("Enter your age: ")
    # age is a string. If we want to add to it, we must cast:
    age_next_year = int(age) + 1
  2. String Concatenation: Python will not implicitly cast integers to strings during concatenation. You must do it explicitly.
    score = 100
    # print("Your score is " + score) # ERROR!
    print("Your score is " + str(score)) # Correct
  3. Data Processing: When parsing files (like CSV or text files) where numbers are read as text strings and need to be converted to actual numeric types for data analysis.

Discussion

Loading comments...