Python Guide Sidebar

Python Type Casting

Why Study Python Type Casting?

Understanding Python Type Casting is crucial for efficient coding. Whether you’re working on small scripts or large projects, type casting ensures that you can manipulate different data types seamlessly. With Python’s flexibility, type casting allows you to convert values between different types without errors.

What Will Be Covered?

we’ll cover:

  • Introduction to Type Casting in Python
  • Implicit Type Casting vs Explicit Type Casting
  • Real-time Examples that are easy to relate to
  • Practical use cases for each type of casting
  • Common Interview Questions on this topic
  • Practice exercises to reinforce your learning

Introduction to Type Casting in Python

Python Type Casting is the process of converting one data type into another. Python is a dynamically typed language, so you don’t need to declare the type of a variable when you create it. However, sometimes you must explicitly convert data types to perform tasks like calculations or string concatenations.

There are two main types of type casting in Python:

Implicit Type Casting (Automatic Conversion)

Implicit Type Casting occurs automatically in Python when you combine two different data types. For instance, if you add an integer to a float, Python automatically converts the integer into a float to ensure the operation runs smoothly.

Example:

codeint_val = 5
float_val = 2.5
result = int_val + float_val  # Python automatically converts int to float
print(result)  # Output: 7.5

In the above example, Python converted the integer 5 to a float before performing the addition.

Explicit Type Casting (Manual Conversion)

1.1 Integer to Float Conversion

In Python, an integer can be explicitly converted to a float using the float() function. This is useful when you want to perform division or work with decimal values.

Example:

codeint_val = 7
float_val = float(int_val)  # Convert integer to float
print(float_val)  # Output: 7.0

Here, the integer 7 is converted to the floating-point value 7.0.

1.2 Float to Integer Conversion

You can convert a float to an integer using the int() function. This will truncate the decimal and return only the integer part.

Example:

codefloat_val = 3.99
int_val = int(float_val)  # Convert float to integer
print(int_val)  # Output: 3

The float 3.99 is converted to 3 (decimal part is discarded).

1.3 Integer to String Conversion

To convert an integer to a string, the str() function is used. This is particularly useful when working with user input, string concatenation, or output formatting.

Example:

codeint_val = 100
str_val = str(int_val)  # Convert integer to string
print(str_val)  # Output: '100'

The integer 100 is now a string '100'.

1.4 Float to String Conversion

To convert a float to a string, the str() function is also used. This is helpful when you need to format floating-point values into readable text or combine them with other strings.

Example:

codefloat_val = 7.85
str_val = str(float_val)  # Convert float to string
print(str_val)  # Output: '7.85'

The float 7.85 is now a string '7.85'.

1.5 String to Integer Conversion

To convert a string to an integer, you use the int() function. This conversion works when the string represents a valid integer.

Example:

codestr_val = "123"
int_val = int(str_val)  # Convert string to integer
print(int_val)  # Output: 123

The string "123" is converted to the integer 123.

Important Note: If the string doesn’t represent a valid integer (e.g., "abc"), it will throw a ValueError.

1.6 String to Float Conversion

To convert a string to a float, use the float() function. This is useful when the string represents a decimal number.

Example:

codestr_val = "12.34"
float_val = float(str_val)  # Convert string to float
print(float_val)  # Output: 12.34

The string "12.34" is converted to the float 12.34.

Important Note: If the string is not a valid number (e.g., "abc"), it will throw a ValueError.

1.7 List to String Conversion

A list of items can be converted into a string using the str() function, but typically, the join() method is preferred when working with lists of strings.

Example:

list_val = ["Python", "is", "fun"]
str_val = " ".join(list_val)  # Convert list to string
print(str_val)  # Output: 'Python is fun'

Here, the list ["Python", "is", "fun"] is converted to the string 'Python is fun'.

1.8 Tuple to List Conversion

A tuple can be converted into a list using the list() function. This is helpful when you want to modify the elements, as lists are mutable.

Example:

codetuple_val = (1, 2, 3)
list_val = list(tuple_val)  # Convert tuple to list
print(list_val)  # Output: [1, 2, 3]

The tuple (1, 2, 3) is converted into the list [1, 2, 3].

1.9 Set to List Conversion

A set can be converted into a list using the list() function. This is useful when you need to work with ordered data or access elements by index.

Example:

pythonCopy codeset_val = {1, 2, 3}
list_val = list(set_val)  # Convert set to list
print(list_val)  # Output: [1, 2, 3]

The set {1, 2, 3} is converted into the list [1, 2, 3].

Summary

To summarize, Python provides two types of casting:

  • Implicit Casting: Automatic type conversion .
  • Explicit Casting: Manual conversion using built-in functions.

Understanding these two types of casting will help you write cleaner, error-free code that interacts with various data types.

Learning Outcomes

After completing this topic, you will be able to:

  • Understand Implicit and Explicit Type Casting.
  • Convert between different Python data types.
  • Apply type casting in real-world scenarios like data input and conversion.
  • Utilize type casting effectively in both small projects and larger applications.

Common Interview Questions

1. What is Type Casting in Python?[ACCENTURE]

Answer: Type casting is refers to the conversion of one data type to another. There are two types of type casting: implicit and explicit.


2. What is the difference between Implicit and Explicit Type Casting?[INFOSYS]

Answer: Implicit Type Casting happens automatically by Python, whereas Explicit Type Casting requires the programmer to use functions like int(), str(), and float().


3. Can you provide an example where Explicit Type Casting ?[IBM]

Answer: In the game scenario where you convert a player’s age (input as a string) to an integer for comparison, we use Explicit Type Casting.


4. What happens if you try to convert a string like “abc” into an integer?[GUVI]

Answer: Python will throw a ValueError because the string does not represent a valid integer.


Practice Exercises

Exercise 1: Implicit Type Casting

Write a program that adds an integer and a float, and prints the result.

Exercise 2: Explicit Type Casting

Create a program that takes a string input of a float number, converts it into an integer, and prints it.

Exercise 3: Type Casting in Real-Life Applications

Write a program that asks for a user’s age as a string, converts it to an integer, and checks if they are eligible to vote (18+).


Additional Resources

  • Books: Learning Python by Mark Lutz
  • Articles: Python Official Documentation on Type Casting
  • Tutorials: Python Tutorial

Let’s Play: