Welcome to Day 6 of the 100 Days of Python series!
Today we dive into how Python handles numbers, performs math operations, and lets you switch between data types. Whether you're building a calculator, processing data, or doing game development, these are must-know concepts.
📦 What You'll Learn Today
- Numeric types in Python:
int
,float
,complex
- Basic arithmetic operations
- Useful math functions and the
math
module - Type conversion between strings and numbers
🔢 1. Python Number Types
Python supports several types of numbers:
🔹 Integer (int
)
Whole numbers, positive or negative:
a = 10
b = -3
🔹 Floating Point (float
)
Numbers with decimals:
pi = 3.1415
price = 99.99
🔹 Complex Numbers (complex
)
Less common, used in scientific applications:
z = 2 + 3j
➕ 2. Basic Arithmetic Operators
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition | 3 + 2 |
5 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 4 * 2 |
8 |
/ |
Division (float) | 10 / 4 |
2.5 |
// |
Floor Division | 10 // 4 |
2 |
% |
Modulus (remainder) | 10 % 4 |
2 |
** |
Exponentiation | 2 ** 3 |
8 |
🧪 Example:
a = 7
b = 2
print(a + b) # 9
print(a - b) # 5
print(a * b) # 14
print(a / b) # 3.5
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 49
📚 3. Useful Built-in Functions
abs(-10) # 10 → Absolute value
round(3.1415) # 3 → Rounds to nearest whole
pow(2, 4) # 16 → Same as 2**4
📐 4. Using the math
Module
For more advanced math operations, import Python’s built-in math
module:
import math
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4
print(math.floor(3.9)) # 3
print(math.pi) # 3.1415926535...
print(math.sin(math.pi)) # Very close to 0
🔁 5. Type Conversion
Python allows you to convert between different data types using built-in functions:
Convert int
↔ float
:
x = 5
y = float(x) # 5.0
z = 3.14
w = int(z) # 3 (decimal part removed)
Convert str
↔ int
or float
:
age_str = "25"
age = int(age_str) # 25
height_str = "5.9"
height = float(height_str) # 5.9
⚠️ Be Careful:
int("abc") # ❌ Error: invalid literal for int()
Always validate or check input before conversion in real-world apps.
✅ Real-World Example
price = input("Enter price: ")
price = float(price)
tax = price * 0.18
total = price + tax
print(f"Total after 18% tax: ₹{round(total, 2)}")
🚀 Recap
Today you learned:
- Python number types:
int
,float
,complex
- Arithmetic operations and math functions
- How to use the
math
module - Type conversion between strings and numbers