Operators
Mastering Python's Computational Language — From Arithmetic to Logic
Operator Overview
Operators are symbols that perform specific operations. Python has the following operator categories:
| Category | Examples | Purpose |
|---|---|---|
| Arithmetic operators | +, -, *, / | Mathematical calculations |
| Comparison operators | ==, !=, >, < | Compare values |
| Logical operators | and, or, not | Logical judgments |
| Assignment operators | =, +=, -= | Variable assignment |
| Membership operators | in, not in | Check membership |
Arithmetic Operators
Basic Operations
python
a = 10
b = 3
print(a + b) # 13 addition
print(a - b) # 7 subtraction
print(a * b) # 30 multiplication
print(a / b) # 3.333... division (result is float)
print(a // b) # 3 floor division (rounds down)
print(a % b) # 1 modulus (remainder)
print(a ** b) # 1000 exponentiation (10 to the power of 3)Stata/R Comparison
| Operation | Python | Stata | R |
|---|---|---|---|
| Addition | a + b | a + b | a + b |
| Subtraction | a - b | a - b | a - b |
| Multiplication | a * b | a * b | a * b |
| Division | a / b | a / b | a / b |
| Floor division | a // b | floor(a/b) | a %/% b |
| Modulus | a % b | mod(a, b) | a %% b |
| Exponentiation | a ** b | a^b | a^b or a**b |
Practical Example: Income Tax Calculation
python
# Annual income
annual_income = 85000
# Progressive tax rates
if annual_income <= 50000:
tax = annual_income * 0.10
elif annual_income <= 100000:
tax = 50000 * 0.10 + (annual_income - 50000) * 0.20
else:
tax = 50000 * 0.10 + 50000 * 0.20 + (annual_income - 100000) * 0.30
tax_rate_effective = (tax / annual_income) * 100
net_income = annual_income - tax
print(f"Annual income: ${annual_income:,}")
print(f"Tax owed: ${tax:,.2f}")
print(f"Effective tax rate: {tax_rate_effective:.2f}%")
print(f"After-tax income: ${net_income:,.2f}")Output:
Annual income: $85,000
Tax owed: $12,000.00
Effective tax rate: 14.12%
After-tax income: $73,000.00Comparison Operators
Comparison operators return boolean values (True or False).
python
x = 10
y = 20
print(x == y) # False equal to
print(x != y) # True not equal to
print(x > y) # False greater than
print(x < y) # True less than
print(x >= y) # False greater than or equal to
print(x <= y) # True less than or equal toNote: = vs ==
python
# = is assignment
age = 25
# == is comparison
is_adult = (age == 18) # FalsePractical Example: Filter Respondents
python
# Respondent data
age = 35
income = 75000
education_years = 16
# Filter criteria: 25-45 years old, income $50k-$100k, at least bachelor's
is_target_group = (
(age >= 25 and age <= 45) and
(income >= 50000 and income <= 100000) and
(education_years >= 16)
)
print(f"Target group: {is_target_group}") # TrueLogical Operators
Logical operators combine multiple conditions.
1. and (AND) - All conditions must be true
python
age = 30
has_job = True
is_eligible = (age >= 18) and has_job
print(is_eligible) # True (both conditions met)
# If any is False, result is False
is_eligible = (age >= 50) and has_job
print(is_eligible) # FalseTruth Table:
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
2. or (OR) - At least one condition must be true
python
has_bachelors = True
has_masters = False
has_degree = has_bachelors or has_masters
print(has_degree) # True (at least one is true)
# Both must be False for result to be False
has_degree = (has_bachelors == False) or (has_masters == False)
print(has_degree) # TrueTruth Table:
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
3. not (NOT) - Negation
python
is_student = False
is_employed = not is_student
print(is_employed) # True
# Double negation
is_student = True
is_not_student = not is_student # False
is_student_again = not is_not_student # TrueCombined Usage
python
# Complex condition: filter unemployed youth or high earners
age = 25
is_employed = False
income = 120000
is_target = (age < 30 and not is_employed) or (income > 100000)
print(is_target) # TrueStata/R Comparison
| Operation | Python | Stata | R |
|---|---|---|---|
| AND | and | & | & or && |
| OR | or | ` | ` |
| NOT | not | ! | ! |
Stata Example:
stata
* Stata
gen is_eligible = (age >= 18 & age <= 65) & (income > 0)R Example:
r
# R
is_eligible <- (age >= 18 & age <= 65) & (income > 0)Python Example:
python
# Python
is_eligible = (age >= 18 and age <= 65) and (income > 0)Assignment Operators
Basic Assignment
python
x = 10 # Basic assignmentCompound Assignment Operators
python
x = 10
x += 5 # Equivalent to x = x + 5 → 15
x -= 3 # Equivalent to x = x - 3 → 12
x *= 2 # Equivalent to x = x * 2 → 24
x /= 4 # Equivalent to x = x / 4 → 6.0
x //= 2 # Equivalent to x = x // 2 → 3.0
x %= 2 # Equivalent to x = x % 2 → 1.0
x **= 3 # Equivalent to x = x ** 3 → 1.0
print(x) # 1.0Practical Example: Cumulative Calculation
python
# Calculate total score
total_score = 0
# Add scores incrementally
total_score += 85 # Math score
total_score += 92 # English score
total_score += 78 # Physics score
print(f"Total score: {total_score}") # Total score: 255
# Calculate average
total_score /= 3
print(f"Average score: {total_score:.2f}") # Average score: 85.00Membership Operators
in and not in
python
# Check if element is in sequence
majors = ['Economics', 'Sociology', 'Political Science']
print('Economics' in majors) # True
print('Physics' in majors) # False
print('Physics' not in majors) # True
# Check substring
email = "alice@university.edu"
print('@' in email) # True
print('university' in email) # TruePractical Example: Major Classification
python
# Social science majors list
social_science_majors = [
'Economics', 'Sociology', 'Political Science',
'Psychology', 'Anthropology'
]
# Check student major
student_major = 'Economics'
if student_major in social_science_majors:
print(f"{student_major} is a social science major")
else:
print(f"{student_major} is not a social science major")
# Output: Economics is a social science majorOperator Precedence
From highest to lowest:
()parentheses**exponentiation*,/,//,%multiplication and division+,-addition and subtraction==,!=,>,<,>=,<=comparisonnotlogical NOTandlogical ANDorlogical OR
Examples
python
# Complex expression
result = 2 + 3 * 4 ** 2 > 50 and not False
# Evaluation order:
# 1. 4 ** 2 = 16
# 2. 3 * 16 = 48
# 3. 2 + 48 = 50
# 4. 50 > 50 = False
# 5. not False = True
# 6. False and True = False
print(result) # False
# Use parentheses for clarity
result = ((2 + 3) * 4) ** 2 > 50 and (not False)
# 1. 2 + 3 = 5
# 2. 5 * 4 = 20
# 3. 20 ** 2 = 400
# 4. 400 > 50 = True
# 5. not False = True
# 6. True and True = True
print(result) # TrueRecommendation: Use parentheses to make precedence explicit in complex expressions!
Practical Case: Data Quality Check
python
# Respondent data
respondent_id = 1001
age = 35
gender = "Male"
income = 75000
education_years = 16
marital_status = "Married"
# === Data quality checks ===
# 1. Age validity (18-100 years)
is_age_valid = 18 <= age <= 100
# 2. Gender validity
valid_genders = ["Male", "Female", "Other"]
is_gender_valid = gender in valid_genders
# 3. Income validity (non-negative and not too high)
is_income_valid = 0 <= income <= 10000000
# 4. Education years validity (0-30 years)
is_education_valid = 0 <= education_years <= 30
# 5. Marital status validity
valid_marital = ["Single", "Married", "Divorced", "Widowed"]
is_marital_valid = marital_status in valid_marital
# === Overall judgment ===
is_data_valid = (
is_age_valid and
is_gender_valid and
is_income_valid and
is_education_valid and
is_marital_valid
)
# === Output report ===
print(f"Respondent {respondent_id} data quality check:")
print(f" Age: {'✓' if is_age_valid else '✗'}")
print(f" Gender: {'✓' if is_gender_valid else '✗'}")
print(f" Income: {'✓' if is_income_valid else '✗'}")
print(f" Education: {'✓' if is_education_valid else '✗'}")
print(f" Marital: {'✓' if is_marital_valid else '✗'}")
print(f" Overall: {'✓ Pass' if is_data_valid else '✗ Fail'}")Common Errors
Error 1: Confusing = and ==
python
age = 25 # Assignment
if age = 25: # SyntaxError
if age == 25: # ComparisonError 2: Misunderstanding Chained Comparisons
python
# Python supports chained comparisons (very convenient!)
age = 30
result = 18 <= age <= 65 # True (equivalent to age >= 18 and age <= 65)
# Don't write like this (syntax error)
result = age >= 18 and <= 65 # SyntaxErrorError 3: Logical Operator Typo
python
result = True && False # SyntaxError (this is JavaScript syntax)
result = True and False # Python uses 'and'Practice Exercises
Exercise 1: BMI Calculation and Classification
python
# Given data
height_cm = 175
weight_kg = 70
# Tasks:
# 1. Calculate BMI (weight / (height_m ** 2))
# 2. Determine classification:
# - BMI < 18.5: Underweight
# - 18.5 <= BMI < 25: Normal
# - 25 <= BMI < 30: Overweight
# - BMI >= 30: ObeseExercise 2: Complex Filter Conditions
python
# Given data
age = 28
income = 65000
education = "Bachelor's"
has_job = True
city = "Beijing"
# Task: Filter people who meet the following criteria
# 1. Age between 25-35
# 2. Income between $50k-$100k
# 3. At least bachelor's degree OR employed
# 4. Lives in tier-1 city (Beijing, Shanghai, Guangzhou, Shenzhen)Exercise 3: Data Validation
python
# Given survey data
q1_age = 25
q2_income = -5000 # Possibly erroneous
q3_satisfaction = 7 # Satisfaction (1-5)
q4_email = "alice.example.com" # Missing @
# Task: Check if each question's data is valid
# 1. Age: 18-100
# 2. Income: >= 0
# 3. Satisfaction: 1-5
# 4. Email: contains @Next Steps
In the next section, we'll learn conditional statements (if-else), using the operators we learned today for decision-making.
Keep moving forward!