Week 2 Lecture: Variables, Data Types and Operators
Table of Contents
- How Python Runs: Interpretation vs Compilation
- Variables
- Data Types
- Operators
- Operator Precedence
- Type Conversion
- String Formatting
- Interesting Python Behaviors
How Python Runs: Interpretation vs Compilation
Compilation (e.g., C++)
# First compile the code
c++ program.cpp
# Then run the executable
./a.out
- Source code is translated entirely to machine code before execution
- Creates a standalone executable file
- Faster execution, but slower development cycle
Pure Interpretation (e.g., old Python)
python script.py
- Code is read and executed line by line
- No separate compilation step
- Slower execution, but faster development
Hybrid Approach (Python with imports)
python script.py
- Python compiles source code to bytecode (.pyc files)
- Bytecode is then interpreted by Python Virtual Machine (PVM)
- You can see .pyc files in
__pycache__
directory - Combines benefits: relatively fast execution + portability
Variables
Variables are containers for storing data values. Python uses dynamic typing, meaning you don’t need to declare the type.
# Variable assignment
name = "Aziza"
age = 20
height = 1.6
is_student = True
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
Naming Rules
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive (
age
andAge
are different) - Cannot use reserved Python keywords
Data Types
Python has four basic data types:
1. Integer (int
)
Whole numbers, positive or negative, without decimals.
x = 5
y = -10
z = 0
2. Float (float
)
Numbers with decimal points.
pi = 3.14159
temperature = -5.5
3. String (str
)
Text data enclosed in quotes (single or double).
name = "Dilshod"
message = 'Assalomu alaykum!'
4. Boolean (bool
)
Logical values: True
or False
.
is_valid = True
is_empty = False
Operators
Arithmetic Operators
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division (float) | 5 / 2 |
2.5 |
// |
Floor Division | 5 // 2 |
2 |
% |
Modulus (remainder) | 5 % 2 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
Relational (Comparison) Operators
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 5 > 3 |
True |
< |
Less than | 5 < 3 |
False |
>= |
Greater or equal | 5 >= 5 |
True |
<= |
Less or equal | 5 <= 3 |
False |
Logical Operators
Operator | Description | Example |
---|---|---|
and |
Returns True if both are True | True and False → False |
or |
Returns True if at least one is True | True or False → True |
not |
Reverses the boolean value | not True → False |
Operator Precedence
Operators are evaluated in a specific order. Remember PEMDAS:
- Parentheses
()
- Exponents
**
- Multiplication, Division, Floor Division, Modulus
*
,/
,//
,%
(left to right) - Addition, Subtraction
+
,-
(left to right) - Comparison operators
<
,<=
,>
,>=
,==
,!=
- Logical
not
- Logical
and
- Logical
or
Tip: Use parentheses ()
to make your code clearer and control evaluation order!
# Without parentheses
result = 2 + 3 * 4 # 14 (multiplication first)
# With parentheses
result = (2 + 3) * 4 # 20 (addition first)
# Complex expression
result = 5 + 3 * 2 ** 2 # 5 + 3 * 4 = 5 + 12 = 17
Type Conversion
Implicit Conversion
Python automatically converts types in some cases:
x = 5 # int
y = 2.0 # float
z = x + y # z is 7.0 (float)
Explicit Conversion (Type Casting)
# To integer
int(3.14) # 3 (truncates decimal)
int("42") # 42
int(True) # 1
int(False) # 0
# To float
float(5) # 5.0
float("3.14") # 3.14
float(True) # 1.0
# To string
str(42) # "42"
str(3.14) # "3.14"
str(True) # "True"
# To boolean
bool(0) # False
bool(1) # True
bool("") # False (empty string)
bool("anything") # True (non-empty string)
String Formatting
1. f-strings (Python 3.6+) - Recommended
name = "Sardor"
age = 20
height = 5.6
# Basic usage
print(f"My name is {name}")
# Multiple variables
print(f"{name} is {age} years old")
# Expressions inside {}
print(f"Next year, {name} will be {age + 1}")
# Formatting numbers
print(f"Height: {height:.1f} feet") # One decimal place
print(f"Pi: {3.14159:.2f}") # Two decimal places
2. .format()
method
name = "Malika"
age = 19
# Positional arguments
print("My name is {} and I am {}".format(name, age))
# Named arguments
print("My name is {n} and I am {a}".format(n=name, a=age))
# Formatting numbers
print("Pi: {:.2f}".format(3.14159))
Interesting Python Behaviors
1. Boolean Surprises
bool("") # False (empty string is falsy)
bool("False") # True! (non-empty string is truthy)
# Comparison stored in variable
x = 5 == 5 # x is True
# Booleans as numbers
True + True # 2
True > False # True
Truthy vs Falsy values:
- Falsy:
False
,0
,0.0
,""
,[]
,{}
,None
- Truthy: Everything else!
2. Floor Division Quirks
print(7 // 2) # 3 (normal)
print(-7 // 2) # -4 (floors DOWN, not toward zero!)
Floor division always rounds down (toward negative infinity), not toward zero.
3. String Comparisons
Strings are compared lexicographically (dictionary order) based on Unicode values:
'aaaa' > 'bbb' # False (a comes before b)
'aaaa' < 'bbb' # True
'b' > 'aaaa' # True (b comes after a)
'apple' < 'app' # False (when prefixes match, longer is "greater")
'apple' > 'app' # True
'abc' < 'abd' # True (third character: c < d)
# Character to Unicode value
ord('a') # 97
ord('b') # 98
4. Type Checking
print(type(5)) # <class 'int'>
print(type(5.0)) # <class 'float'>
print(type("5")) # <class 'str'>
print(5 == 5.0) # True (values are equal)
print(5 is 5.0) # False ('is' checks identity, not value)
Note: ==
compares values, while is
compares identity (whether they’re the same object in memory).
5. Short-Circuit Evaluation
Logical operators don’t always evaluate all operands:
print(True or print("Hello")) # Prints: True
# Doesn't execute print (short-circuits)
print(False and print("Hello")) # Prints: False
# Doesn't execute print
# Return values of logical operators
print(5 and 10) # 10 (returns second value if first is truthy)
print(0 or 20) # 20 (returns first truthy value)
print('' or 'hello') # 'hello'
6. Floating Point Precision
Computers store floating-point numbers in binary, which can lead to precision issues:
print(0.1 + 0.2) # 0.30000000000000004 (not exactly 0.3!)
Why does this happen? Let’s understand step by step:
Step 1: How humans represent fractions
In decimal (base 10), some fractions are easy:
- 1/2 = 0.5 (exact)
- 1/4 = 0.25 (exact)
- 1/3 = 0.333… (infinite, repeating)
Step 2: How computers represent fractions
Computers use binary (base 2). In binary, different fractions become problematic:
- 1/2 = 0.1 in binary (exact)
- 1/4 = 0.01 in binary (exact)
- 1/10 = 0.0001100110011… in binary (infinite, repeating!)
Step 3: The problem with 0.1
The decimal number 0.1
(which is 1/10) cannot be represented exactly in binary. It’s like trying to write 1/3 in decimal - you get 0.333… forever.
In binary, 0.1 looks like: 0.00011001100110011001100110011...
(repeating forever)
Step 4: Computer memory is limited
Since computers can’t store infinite digits, they have to round. When you store 0.1
, the computer stores a very close approximation, but not the exact value.
Step 5: Errors accumulate
When you add two approximations:
0.1
(stored as ~0.1000000000000000055511151…)+0.2
(stored as ~0.2000000000000000111022302…)= 0.3000000000000000444089209...
The small errors add up, giving us 0.30000000000000004
instead of exactly 0.3
.
Real-world analogy:
Imagine you’re measuring ingredients:
- Your measuring cup can only show 2 decimal places
- Recipe calls for 1/3 cup (0.333…)
- You measure 0.33 cup
- Recipe calls for another 1/3 cup
- You measure 0.33 cup again
- Total: 0.66 cup (but should be 0.666… or 2/3 cup)
- You’re missing a tiny bit!
Live Coding Examples
Example 1: Personal Information Card
This program takes user information and displays it in a formatted card:
name = input("enter your name: ")
age = int(input("enter your age: "))
height = float(input("enter your height: "))
age_in_months = age * 12
adult_status = age >= 18
print(f"\n\n{'=' * 40}")
print('Personal Information Card')
print(f"{'=' * 40}")
print(f"Name: {name}")
print(f"Age: {age} years, ({age_in_months} months)")
print(f"Height: {height}m")
print(f"Adult Status: {adult_status}")
print(f"{'=' * 40}\n\n")
What this demonstrates:
- Taking user input with
input()
- Type conversion:
int()
andfloat()
- Arithmetic operations
- Boolean expressions (
age >= 18
) - f-string formatting with expressions
- String repetition for visual formatting (
'=' * 40
)
Example 2: Price Calculator with Discount and Tax
Calculate the final price of an item after applying discount and tax:
item_name = input('enter item name: ')
original_price = float(input('enter price (sum): '))
discount_percentage = float(input('enter discount percentage: '))
tax_percentage = float(input('enter tax percentage: '))
budget = float(input('enter your budget: '))
discount_amount = original_price * (discount_percentage / 100)
price_after_discount = original_price - discount_amount
tax_amount = price_after_discount * (tax_percentage / 100)
final_price = price_after_discount + tax_amount
print(f"\n\n{'=' * 50}")
print(f"Receipt for: {item_name}")
print(f"{'=' * 50}")
print(f"Original Price: {original_price} sum")
print(f"Discount ({discount_percentage}%): -{discount_amount:.2f} sum")
print(f"Price after discount: {price_after_discount:.2f} sum")
print(f"Tax ({tax_percentage}%) +{tax_amount:.2f} sum")
print(f"{'=' * 50}")
print(f"FINAL PRICE: {final_price:.2f} sum")
print(f"Your Budget: {budget} sum")
print(f"Can Afford: {'Yes' if budget >= final_price else 'No'}")
print(f"You saved: {(original_price - final_price):.2f} sum")
print(f"{'=' * 50}\n\n")
What this demonstrates:
- Multiple user inputs and type conversions
- Sequential calculations (step-by-step problem solving)
- Percentage calculations
- Number formatting with
.2f
(two decimal places) - Embedded expressions in f-strings
- Relational operators in output (
budget >= final_price
) - Real-world application of programming concepts
This content will be available starting October 07, 2025.