Programming with PythonUnit 211 min read
Data Types, Variables & Operators in Python
Unit 2 of Programming with Python covers fundamental building blocks: numeric types (integers, floats), boolean logic, type conversion, arithmetic/relational operators, and variable assignment rules—with real-world examples from eSewa transactions and Ncell billing.
Core Concepts
1. Data Types in Python
Python has primitive and derived data types. Primitive types are the basic building blocks:
Numeric Types
Integers (
int):- Whole numbers (positive, negative, or zero).
- Example:
age = 25,balance = -1000. - Unlimited precision: Python
intcan handle arbitrarily large numbers (e.g.,10**1000).
Floats (
float):- Decimal numbers (floating-point).
- Example:
temperature = 36.6,pi = 3.14159. - Precision limit: ~15-17 significant digits due to IEEE 754 standard.
Complex Numbers (
complex):- Written as
a + bj(e.g.,z = 3 + 4j). - Used in scientific computing (e.g., signal processing).
- Written as
Boolean Type (bool)
- Represents
TrueorFalse. - Used in conditions and logical operations.
- Example:
is_raining = True has_permission = False
NoneType (None)
- Represents the absence of a value.
- Example:
user_input = None # No input provided yet
2. Variables and Assignment
- Variable: A named storage location for data.
- Assignment: Uses
=to bind a value to a variable.x = 10 # Integer name = "Alice" # String is_active = True # Boolean - Dynamic Typing: Python infers the type at runtime.
var = 100 # int var = "Hello" # Now a str (type changes dynamically)
Variable Naming Rules
| Rule | Example | Invalid Example |
|---|---|---|
| Start with letter/underscore | age, _private |
123age (invalid) |
| Case-sensitive | Name ≠ name |
Name and name are different |
| No keywords | if, for (invalid) |
total = 10 (valid) |
| No spaces | user_name (valid) |
user name (invalid) |
3. Operators in Python
Operators perform operations on variables and values.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 4 |
6 |
* |
Multiplication | 3 * 4 |
12 |
/ |
Division | 10 / 2 |
5.0 |
// |
Floor Division | 10 // 3 |
3 |
% |
Modulus | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
Example: Calculating Ncell Bill Suppose Ncell charges Rs. 120 for 1000 minutes and Rs. 2 per extra minute.
base_charge = 120
minutes_used = 1200
extra_minutes = minutes_used - 1000
total_cost = base_charge + (extra_minutes * 2)
print(f"Total bill: Rs. {total_cost}") # Output: Rs. 440
Comparison Operators
| Operator | Name | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 10 > 5 |
True |
< |
Less than | 3 < 5 |
True |
>= |
Greater or equal | 5 >= 5 |
True |
<= |
Less or equal | 3 <= 5 |
True |
Example: eSewa Transaction Validation
amount = 500
min_amount = 100
max_amount = 10000
if min_amount <= amount <= max_amount:
print("Transaction valid!")
else:
print("Invalid amount!")
Logical Operators
| Operator | Name | Example | Result |
|---|---|---|---|
and |
Logical AND | True and False |
False |
or |
Logical OR | True or False |
True |
not |
Logical NOT | not True |
False |
Example: Daraz Order Eligibility
has_coupon = True
order_total = 2000
min_order = 1500
if has_coupon or order_total >= min_order:
print("Eligible for free shipping!")
else:
print("Not eligible.")
Assignment Operators
| Operator | Example | Equivalent To |
|---|---|---|
+= |
x += 3 |
x = x + 3 |
-= |
x -= 1 |
x = x - 1 |
*= |
x *= 2 |
x = x * 2 |
/= |
x /= 2 |
x = x / 2 |
Example: Bank Loan Interest Calculation
principal = 100000
interest_rate = 0.05 # 5%
years = 3
# Simple interest: I = P * r * t
interest = principal * interest_rate * years
total_amount = principal + interest
print(f"Total amount after {years} years: Rs. {total_amount}")
In the Real World
eSewa Transactions
- Uses comparison operators (
==,>=) to validate transaction amounts before processing payments. - Example: Checks if
amount >= 100andbalance >= amountbefore deducting funds.
- Uses comparison operators (
Ncell Billing System
- Applies arithmetic operators (
+,*) to calculate bills based on usage (e.g.,total_cost = base_charge + (extra_minutes * rate)).
- Applies arithmetic operators (
Pathao Driver App
- Uses logical operators (
and,or) to determine ride eligibility:if (driver_available and ride_requested) or (emergency_ride):accept_ride()
- Uses logical operators (
NEPSE Stock Prices
- Floating-point precision matters when calculating daily returns:
previous_price = 100.50 current_price = 102.75 return_percentage = ((current_price - previous_price) / previous_price) * 100
- Floating-point precision matters when calculating daily returns:
4. Type Conversion
Python allows converting between types using:
int()float()str()bool()
Example: Converting User Input
user_input = "100"
quantity = int(user_input) # Convert str to int
price = 20.50
total = quantity * price
print(f"Total: Rs. {total}") # Output: Rs. 2050.0
Common Pitfalls
| Conversion | Valid Example | Invalid Example |
|---|---|---|
int("3.14") |
❌ ValueError |
int(3.14) → 3 (truncates) |
float("abc") |
❌ ValueError |
float(5) → 5.0 |
str(100) |
✅ "100" |
- |
5. Operator Precedence
Python evaluates operators in this order (highest to lowest priority):
flowchart TD
A["Parentheses"] --> B["Exponentiation"]
B --> C["Multiplication/Division/Modulus"]
C --> D["Addition/Subtraction"]
D --> E["Comparison"]
E --> F["Logical NOT"]
F --> G["Logical AND"]
G --> H["Logical OR"]Example: Evaluating a Complex Expression
result = 10 + 3 * 2 ** 2
# Step-by-step:
# 1. 2 ** 2 = 4
# 2. 3 * 4 = 12
# 3. 10 + 12 = 22
print(result) # Output: 22
Visualizing Data Types and Operations
Memory Representation of Variables
Example: Variable Assignment in Memory
x = 10 # int
y = 3.14 # float
name = "Bob" # str
+------+ +------+ +------+
| x |------>| 10 | +------+
+------+ +------+ | name |
| type |------>| int | +------+
+------+ +------+ | "Bob"|
+------+ +------+
| y |------>| 3.14 |
+------+ +------+
| type |------>| float|
+------+
Step-by-Step Trace: Calculating Compound Interest
Formula: Where:
- = Principal (Rs. 5000)
- = Annual rate (5% = 0.05)
- = Compounding frequency (12 for monthly)
- = Time in years (2)
P = 5000
r = 0.05
n = 12
t = 2
# Step 1: Calculate r/n
r_div_n = r / n # 0.05 / 12 ≈ 0.0041667
# Step 2: Calculate (1 + r/n)
term = 1 + r_div_n # 1.0041667
# Step 3: Calculate nt
nt = n * t # 12 * 2 = 24
# Step 4: Raise to power nt
amount = P * (term ** nt) # 5000 * (1.0041667 ** 24) ≈ 5536.79
| Step | Variable | Value | Operation |
|---|---|---|---|
| 1 | r_div_n |
0.0041667 | 0.05 / 12 |
| 2 | term |
1.0041667 | 1 + r_div_n |
| 3 | nt |
24 | 12 * 2 |
| 4 | amount |
5536.789... | 5000 * (term ** 24) |
Final Output:
After 2 years, Rs. 5000 grows to Rs. 5536.79 (compounded monthly).
Common Mistakes and How to Avoid Them
| Mistake | Example | Fix |
|---|---|---|
| Forgetting parentheses in order | 3 + 4 * 2 → 11 |
(3 + 4) * 2 → 14 |
| Type mismatch in operations | "5" + 3 → Error |
int("5") + 3 → 8 |
| Floating-point precision issues | 0.1 + 0.2 == 0.3 → False |
Use round() or math.isclose() |
| Unintended variable shadowing | x = 10; x = "hello" |
Avoid reusing variable names |
Exam Tip
Focus on Operator Precedence:
- Always use parentheses to clarify intent in complex expressions.
- Example:
(a + b) * cvsa + b * c.
Type Conversion Pitfalls:
int("3.5")raisesValueError. Useint(float("3.5"))if needed.str(10) + 5raisesTypeError. Convert both tostr:str(10) + str(5).
Real-World Scenarios:
- Expect questions on billing systems (Ncell), transaction validation (eSewa), or loan calculations (banks).
- Example:
"A user deposits Rs. 10,000 in a bank with 6% annual interest compounded quarterly. Calculate the amount after 3 years." Solution: Use the compound interest formula with
n = 4andt = 3.
Tracing Variables:
- For marks, show step-by-step variable changes in tables (like the compound interest example above).
- Example:
Answer:x = 5 x += 3 # What is x now?Step Operation xValue1 x = 55 2 x += 38
Boolean Logic:
- Questions may ask to evaluate expressions like:
Trace:(10 > 5) and (2 < 4) or not (3 == 3)(10 > 5)→True(2 < 4)→Trueand→True and True→Truenot (3 == 3)→not True→Falseor→True or False→True
- Questions may ask to evaluate expressions like:
Final Checklist Before Exam
- Can you list all 6 primitive data types in Python?
- Do you know the precedence of
+,*, and==? - Can you trace a variable’s value through 3 assignment operations?
- Can you write a real-world example (e.g., Ncell bill) using arithmetic operators?
- Do you remember how to convert between
int,float, andstrsafely?
Based on the TU BIM syllabus for Programming with Python (IT243), unit 2.
Discussion
Loading…