Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Type Conversion and Casting
Understanding type conversion is essential because incorrect type handling can lead to runtime errors, unexpected results, and data loss. This guide will cover implicit and explicit type conversion, their functions, best practices, and real-world use cases.
1. What is Type Conversion?
Type conversion refers to changing the data type of a variable. Python provides two types of type conversion:
- Implicit Type Conversion (Automatic)
- Explicit Type Conversion (Manual or Type Casting)
Each has its specific use cases, advantages, and limitations.
2. Implicit Type Conversion (Automatic)
Python automatically converts one data type to another without explicit instruction. This is known as implicit type conversion.
Example 1: Integer to Float Conversion
num_int = 10 # Integernum_float = 3.5 # Float
result = num_int + num_floatprint(result) # Output: 13.5print(type(result)) # Output: <class 'float'>
✅ Here, Python automatically converts num_int
(integer) to a float before performing addition, avoiding data loss.
Example 2: Integer to Complex Number Conversion
num = 5complex_num = num + 2j # Complex number
print(complex_num) # Output: (5+2j)print(type(complex_num)) # Output: <class 'complex'>
✅ Python implicitly converts the integer 5
into a complex number for seamless computation.
When Does Python Perform Implicit Conversion?
- When combining integers and floats → Result is a float
- When combining integers and complex numbers → Result is a complex number
- When handling boolean values in arithmetic operations
Example 3: Boolean in Arithmetic Operations
print(True + 5) # Output: 6 (True is treated as 1)print(False + 10) # Output: 10 (False is treated as 0)
✅ Python converts True
to 1
and False
to 0
, making mathematical operations possible.
⚠️ Limitations of Implicit Conversion
- Python does not automatically convert a string to an integer or float.
- Python does not convert a complex number to any other type.
3. Explicit Type Conversion (Type Casting)
When Python does not automatically convert types, we need to manually convert them using built-in functions. This is called explicit type conversion or type casting.
Common Type Casting Functions in Python
Function | Converts To |
---|---|
int(x) | Converts x to an integer |
float(x) | Converts x to a floating-point number |
str(x) | Converts x to a string |
bool(x) | Converts x to a boolean (True or False ) |
complex(x) | Converts x to a complex number |
list(x) | Converts x to a list |
tuple(x) | Converts x to a tuple |
4. Converting Between Different Data Types
1. Converting String to Integer
num_str = "100"num_int = int(num_str)
print(num_int) # Output: 100print(type(num_int)) # Output: <class 'int'>
✅ int()
converts the string "100"
into an integer.
⚠️ If the string contains non-numeric characters, it will raise an error:
num_str = "100abc"num_int = int(num_str) # ValueError: invalid literal for int()
2. Converting Integer to String
num = 123num_str = str(num)
print(num_str) # Output: "123"print(type(num_str)) # Output: <class 'str'>
✅ str()
converts an integer into a string, allowing concatenation with text.
age = 25print("My age is " + str(age)) # Output: My age is 25
⚠️ Without str()
conversion, this would raise an error:
print("My age is " + age) # TypeError: can only concatenate str (not "int")
3. Converting Float to Integer
num_float = 9.99num_int = int(num_float)
print(num_int) # Output: 9print(type(num_int)) # Output: <class 'int'>
✅ int()
removes the decimal part without rounding (it truncates).
⚠️ For rounding, use round()
instead:
print(round(9.99)) # Output: 10
4. Converting List to Tuple and Vice Versa
my_list = [1, 2, 3]my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)print(type(my_tuple)) # Output: <class 'tuple'>
✅ Useful when you want to prevent modification of data.
my_tuple = (4, 5, 6)my_list = list(my_tuple)
print(my_list) # Output: [4, 5, 6]
✅ list()
allows you to modify elements.
5. Converting Boolean Values
print(int(True)) # Output: 1print(int(False)) # Output: 0print(bool(1)) # Output: Trueprint(bool(0)) # Output: False
✅ Any non-zero value is True
, and 0
is False
.
6. Real-World Use Cases of Type Conversion
1. User Input Handling
age = input("Enter your age: ") # Always returns a stringage = int(age) # Convert to integer for calculations
print("You will be", age + 5, "years old in 5 years.")
✅ input()
always returns a string, so we convert it to an integer.
2. Data Processing
In data science, converting strings to numbers is essential for calculations.
import pandas as pd
data = {"age": ["25", "30", "35"], "salary": ["50000", "60000", "70000"]}df = pd.DataFrame(data)
df["age"] = df["age"].astype(int) # Convert to integerdf["salary"] = df["salary"].astype(float) # Convert to float
✅ Ensures numerical operations work correctly.