Type Conversions
1. Implicit Type Conversion (Automatic)
This happens when Python automatically converts one data type to another without explicit
instructions from the programmer. Usually, this happens when different data types are used
together, and Python promotes smaller data types to larger ones to avoid loss of data.
Example of Implicit Conversion:
# Integer and float together
num_int = 5
num_float = 2.5
result = num_int + num_float
print(result)
# Output: 7.5
print(type(result))
# Output: <class 'float'>
In this example, Python automatically converts the integer num_int to a float during addition
to avoid loss of precision.
2. Explicit Type Conversion (Type Casting)
In explicit type conversion, also called type casting, the programmer manually converts one
data type to another. This is done using Python’s built-in functions.
Common Functions for Explicit Conversion:
int() — Converts to integer
float() — Converts to float
str() — Converts to string
list() — Converts to list
tuple() — Converts to tuple
set() — Converts to set
dict() — Converts to dictionary
bool() — Converts to boolean
Example of Explicit Conversion:
# Convert float to int
num_float = 3.8
num_int = int(num_float)
print(num_int)
# Output: 3
# Convert string to int
num_str = "10"
num_int = int(num_str)
print(num_int)
# Output: 10
# Convert int to string
num = 50
num_str = str(num)
print(num_str)
# Output: '50'
print(type(num_str))
# Output: <class 'str'>
Important Notes:
int() truncates the decimal part when converting from a float.
str() can convert almost any object to a string.
int(), float() conversions raise a ValueError if the string cannot be properly parsed as
a number (e.g., int("abc") raises an error).
Complex conversions (like converting a list to a string, etc.) may involve different
strategies or helper functions.
Summary of Conversion Functions:
Function Description
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 value
list(x) Converts x to a list
tuple(x) Converts x to a tuple
set(x) Converts x to a set
dict(x) Converts x to a dictionary
The `int()` function
The `int()` function in Python is used to convert a value into an integer. It can be used with
strings, floating-point numbers, or other data types to cast them to integers, depending on the
format of the input.
Syntax:
Python Code:
int(value, base)
Parameters:
- **value**: The data to be converted to an integer. It can be a string or a number.
- **base** (optional): The base of the number in the string. The default base is 10.
Examples:
1. **Converting a float to an integer** (it truncates the decimal part):
Python Code:
x = 10.5
y = int(x)
print(y)
# Output: 10
2. **Converting a string to an integer**:
s = "25"
y = int(s)
print(y)
# Output: 25
3. **Converting a string with a different base**:
binary_string = "1010"
y = int(binary_string, 2)
print(y)
# Output: 10 (binary 1010 is 10 in decimal)
4. **Invalid conversions**:
If the string is not a valid representation of a number, it will raise a `ValueError`:
```python
s = "abc"
y = int(s)
# This will raise ValueError
Notes:
- If the input is a floating-point number, `int()` will discard the fractional part (no rounding).
- If the input is a string, the string must represent a valid integer in the given base (default is
base 10).
Basic Python codes that beginners often start with:
1. **Hello, World!**
A simple code to print a message.
```python
print("Hello, World!")
```
2. **Variables and Data Types**
Assigning values to variables.
```python
# Strings
name = "Alice"
# Integer
age = 25
# Float
height = 5.6
# Boolean
is_student = True
print(name, age, height, is_student)
```
3. **Basic Arithmetic Operations**
Performing simple math operations.
```python
a = 10
b=3
# Addition
print(a + b)
# Output: 13
# Subtraction
print(a - b)
# Output: 7
# Multiplication
print(a * b)
# Output: 30
# Division
print(a / b)
# Output: 3.3333
# Modulus (remainder)
print(a % b)
# Output: 1
```
4. **Conditional Statements**
Using `if`, `elif`, and `else` to make decisions.
```python
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
```
5. **Loops**
Using `for` and `while` loops to repeat actions.
- **For Loop**
```python
for i in range(5):
print(i)
# Prints 0 to 4
```
- **While Loop**
```python
count = 0
while count < 5:
print(count)
count += 1
```
6. **Functions**
Creating and using functions.
```python
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# Output: Hello, Alice!
```
7. **Lists**
Storing multiple values in a single variable.
```python
fruits = ["apple", "banana", "cherry"]
# Accessing list elements
print(fruits[0])
# Output: apple
# Adding a new element
fruits.append("orange")
# Looping through a list
for fruit in fruits:
print(fruit)
```
8. **Dictionaries**
Storing key-value pairs.
```python
person = {"name": "Alice", "age": 25, "city": "New York"}
# Accessing dictionary elements
print(person["name"])
# Output: Alice
# Adding a new key-value pair
person["profession"] = "Engineer"
# Looping through keys and values
for key, value in person.items():
print(f"{key}: {value}")
```
9. **User Input**
Getting input from the user.
```python
name = input("Enter your name: ")
print(f"Hello, {name}!")
```
10. **File Handling**
Reading from and writing to a file.
- **Writing to a file:**
```python
with open("example.txt", "w") as file:
file.write("This is a test file.")
```
**Reading from a file:**
```python
with open("example.txt", "r") as file:
content = file.read()
print(content)
```