Type Conversions Python Codes
Type Conversions Python Codes
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.
num_int = 5
num_float = 2.5
print(result)
# Output: 7.5
print(type(result))
In this example, Python automatically converts the integer num_int to a float during addition
to avoid loss of precision.
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.
num_float = 3.8
num_int = int(num_float)
print(num_int)
# Output: 3
num_str = "10"
num_int = int(num_str)
print(num_int)
# Output: 10
num = 50
num_str = str(num)
print(num_str)
# Output: '50'
print(type(num_str))
Important Notes:
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 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:
- **base** (optional): The base of the number in the string. The default base is 10.
Examples:
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
binary_string = "1010"
y = int(binary_string, 2)
print(y)
4. **Invalid conversions**:
```python
s = "abc"
y = int(s)
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).
```python
print("Hello, World!")
```
2. **Variables and Data Types**
```python
# Strings
name = "Alice"
# Integer
age = 25
# Float
height = 5.6
# Boolean
is_student = True
```
```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**
```python
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
```
5. **Loops**
- **For Loop**
```python
for i in range(5):
print(i)
# Prints 0 to 4
```
- **While Loop**
```python
count = 0
print(count)
count += 1
```
6. **Functions**
```python
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
```
7. **Lists**
```python
print(fruits[0])
# Output: apple
fruits.append("orange")
print(fruit)
```
8. **Dictionaries**
```python
print(person["name"])
# Output: Alice
person["profession"] = "Engineer"
print(f"{key}: {value}")
```
9. **User Input**
```python
print(f"Hello, {name}!")
```
- **Writing to a file:**
```python
```
```python
content = file.read()
print(content)
```