Programming with PythonUnit 28 min read
Data Types, Variables & Operators in Python
Unit 2 of Programming with Python covers fundamental building blocks—data types (numeric, boolean, sequence, mapping), variable assignment, type conversion, and operators (arithmetic, comparison, logical, bitwise)—with visual traces of operations and real-world applications in Nepalese tech (e.g., Khalti’s transaction
Core Concepts
Data Types in Python
Python has five primary data types (and many derived types). Each determines how data is stored and manipulated.
1. Numeric Types
# Integer, Float, Complex
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
Visual Trace: Memory Representation
- Integer (
int): Whole numbers (positive/negative), unlimited size (e.g.,10,-5,1000000). - Float (
float): Decimal numbers (64-bit precision), e.g.,3.14,-0.001. - Complex (
complex): Real + imaginary parts (e.g.,3+4j).
Worked Example: Khalti Transaction Fee Khalti calculates a 2.5% fee on transactions. Write code to compute the fee for a ₹5000 order:
order_amount = 5000
fee_rate = 0.025
fee = order_amount * fee_rate
print(f"Fee: ₹{fee:.2f}") # Output: Fee: ₹125.00
2. Boolean Type
is_valid = True # bool
- Represents
True/False(1/0 in operations). - Used in conditions (e.g.,
if x > 0:).
3. Sequence Types
text = "Python" # str
numbers = [1, 2, 3] # list
frozen = (1, 2, 3) # tuple
Visual: Sequence Storage
- String (
str): Immutable sequence of Unicode characters (e.g.,"Hello"). - List (
list): Mutable, ordered collection (e.g.,[1, 2, 3]). - Tuple (
tuple): Immutable, ordered collection (e.g.,(1, 2, 3)).
Real-World Tie: Daraz Order Processing Daraz uses lists to track orders in a queue. When an order is processed, it’s removed from the list (FIFO).
orders = ["Order123", "Order456", "Order789"]
processed_order = orders.pop(0) # Removes "Order123"
print(f"Processing: {processed_order}")
4. Mapping Type
user = {"name": "Alice", "age": 25} # dict
- Dictionary (
dict): Key-value pairs (e.g.,{"key": "value"}). - Keys must be immutable (e.g.,
str,int,tuple).
Visual: Dictionary Internals
```mermaid
graph TD
A["user = {'name': 'Alice', 'age': 25}"] --> B["Hash Table"]
B --> C["Key: 'name' → Hash Index 1"]
B --> D["Key: 'age' → Hash Index 2"]
C --> E["Value: 'Alice'"]
D --> F["Value: 25"]
#### 5. **Set Type**
```python
unique_numbers = {1, 2, 3} # set
- Set (
set): Unordered, mutable collection of unique elements. - Used for membership tests (e.g.,
if 1 in unique_numbers:).
Variables and Assignment
- Variable: Named storage location for data (e.g.,
x = 10). - Rules:
- Start with letter/underscore (no numbers/symbols).
- Case-sensitive (
age≠Age). - No Python keywords (e.g.,
if,for).
Visual: Variable Assignment
```mermaid
flowchart LR
A["x = 10"] --> B["Memory Allocation"]
B --> C["x → [10]"]
C --> D["Stack Frame"]
**Worked Example: Ncell Data Usage**
Ncell charges ₹100 for 1GB data. Calculate remaining data after using 300MB:
```python
total_data = 1000 # MB
used_data = 300 # MB
remaining = total_data - used_data
print(f"Remaining: {remaining}MB") # Output: 700MB
Type Conversion
Convert between types using:
int(),float(),str(),list(),tuple(),set(),dict().
Example: Converting User Input
user_input = "10"
number = int(user_input) # Converts string to int
print(number + 5) # Output: 15
Visual: Type Conversion Flow
```mermaid
flowchart TD
A["str '10'"] --> B["int()"] --> C["int 10"]
A --> D["float()"] --> E["float 10.0"]
Operators in Python
1. Arithmetic Operators
| Operator | Example | Description |
|---|---|---|
+ |
x + y |
Addition |
- |
x - y |
Subtraction |
* |
x * y |
Multiplication |
/ |
x / y |
Division (float) |
// |
x // y |
Floor division (int) |
% |
x % y |
Modulus (remainder) |
** |
x ** y |
Exponentiation |
Worked Example: NEPSE Share Price A share costs ₹500. Calculate profit after selling 10 shares at ₹550:
cost_price = 500
selling_price = 550
profit_per_share = selling_price - cost_price
total_profit = profit_per_share * 10
print(f"Total Profit: ₹{total_profit}") # Output: ₹500
2. Comparison Operators
| Operator | Example | Description |
|---|---|---|
== |
x == y |
Equal |
!= |
x != y |
Not equal |
> |
x > y |
Greater than |
< |
x < y |
Less than |
>= |
x >= y |
Greater or equal |
<= |
x <= y |
Less or equal |
Visual: Comparison Result Table
3. Logical Operators
| Operator | Example | Description |
|---|---|---|
and |
x > 0 and y < 10 |
Both conditions true |
or |
x > 0 or y < 10 |
Either condition true |
not |
not x |
Inverts boolean |
Worked Example: eSewa Payment Validation Validate if a user has enough balance (≥₹100) and the amount is ≤₹5000:
balance = 1500
amount = 2000
is_valid = balance >= 100 and amount <= 5000
print(f"Payment Valid: {is_valid}") # Output: True
4. Bitwise Operators
| Operator | Example | Description |
|---|---|---|
& |
x & y |
Bitwise AND |
| ` | ` | `x |
^ |
x ^ y |
Bitwise XOR |
~ |
~x |
Bitwise NOT |
<< |
x << y |
Left shift |
>> |
x >> y |
Right shift |
Visual: Bitwise AND Example
```mermaid
graph TD
A["x = 5 (0101)"] --> B["y = 3 (0011)"]
B --> C["x & y = 0001 (1)"]
In the Real World
Khalti (Transaction Validation)
- Uses boolean logic (
if balance >= amount:) to validate payments. - Bitwise operations (rarely) might optimize low-level checks in backend systems.
- Uses boolean logic (
Daraz (Order Queue Management)
- Lists store pending orders.
orders.pop(0)processes the oldest order (FIFO). - Dictionaries map order IDs to customer details (e.g.,
{"Order123": {"user": "Alice", "status": "Processing"}}).
- Lists store pending orders.
Ncell (Data Usage Calculation)
- Arithmetic operators (
total_data - used_data) track remaining data. - Comparison operators (
if remaining < 100:) trigger warnings.
- Arithmetic operators (
NEPSE (Share Price Analysis)
- Floats store share prices (e.g.,
500.50). - Lists track historical prices for trend analysis.
- Floats store share prices (e.g.,
Exam Tip
Data Type Questions:
- Memorize numeric types (
int,float,complex) and their use cases. - Know when to use lists (mutable) vs tuples (immutable).
- Dictionaries are key-value stores; sets enforce uniqueness.
- Memorize numeric types (
Operators:
- Arithmetic: Practice
//(floor division) and%(modulus). - Comparison: Watch for
==(value) vsis(identity). - Logical:
and/orshort-circuit (e.g.,if x > 0 and y/x > 1:).
- Arithmetic: Practice
Variable Rules:
- Avoid reserved keywords (e.g.,
class = 10is invalid). - Use snake_case for variables (e.g.,
user_age).
- Avoid reserved keywords (e.g.,
Type Conversion:
int("10")works, butint("10.5")raisesValueError.str(10) + "MB"concatenates strings.
Real-World Scenarios:
- Expect questions on transaction validation (Khalti), order processing (Daraz), or data usage (Ncell).
- Trace operations step-by-step (e.g., "After
orders.pop(0), what remains?").
Practice Problem: Write a program to:
- Store 3 user names in a list.
- Convert the list to a tuple.
- Check if "Alice" is in the tuple using
in. - Print the result of
tuple[0] + " is in the system". Solution:
users = ["Alice", "Bob", "Charlie"]
user_tuple = tuple(users)
is_alice = "Alice" in user_tuple
print(f"{user_tuple[0]} is in the system") # Output: Alice is in the system
Based on the TU BITM syllabus for Programming with Python (IT243), unit 2.
Discussion
Loading…