Day 2: Operators, Input/Output & Type Casting

🐍 Day 2: Operators, Input/Output & Type Casting


1. Learning Objectives

By the end of Day 2, you will be able to:

  • Use all major Python operators: arithmetic, comparison, logical, assignment, and identity
  • Understand operator precedence (which operations happen first)
  • Accept user input with input() and process it correctly
  • Convert between data types using int(), float(), str(), and bool()
  • Write interactive programs that respond to the user

2. Concept Explanation

2.1 Arithmetic Operators — Python as a Calculator

Python can do everything a calculator does and far more:

Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division (always returns float) 10 / 3 3.333...
// Floor division (integer result) 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Exponentiation 10 ** 3 1000

Critical detail: / always returns a float, even when dividing evenly:

      
print(10 / 2) # 5.0 — float, not int! print(10 // 2) # 5 — int, floor division drops decimals

% is more useful than it looks:

      
# Is a number even or odd? print(7 % 2) # 1 → odd print(8 % 2) # 0 → even # Extract the last digit print(12345 % 10) # 5 # Check if a year is divisible by 4 print(2024 % 4) # 0 → divisible

2.2 Comparison Operators — Asking Questions

These always return a boolean (True or False):

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 10 > 5 True
< Less than 3 < 1 False
>= Greater than or equal 5 >= 5 True
<= Less than or equal 4 <= 3 False

⚠️ Single = vs. Double ==:
= assigns a value. == compares two values.
This is the #1 beginner mistake!

      
x = 5 # Assignment: put 5 into x x == 5 # Comparison: is x equal to 5? → True x = 10 # Assignment: now x is 10 x == 5 # Comparison: is x equal to 5? → False

2.3 Logical Operators — Combining Conditions

Operator Meaning Example Result
and Both must be True (5 > 3) and (2 < 4) True
or At least one must be True (5 < 3) or (2 < 4) True
not Reverses the boolean not (5 > 3) False

Truth tables for quick reference:

      
AND: OR: NOT: True and True → True True or True → T not True → False True and False → False True or False → T not False → True False and True → False False or True → T False and False→ False False or False→ F

Real-world examples:

      
age = 22 has_license = True # Can this person drive? can_drive = (age >= 18) and has_license print(can_drive) # True # Is a number in range? num = 75 in_range = (num >= 0) and (num <= 100) print(in_range) # True # Is it a weekend day? day = "Saturday" is_weekend = (day == "Saturday") or (day == "Sunday") print(is_weekend) # True

2.4 Assignment Operators — Shorthand

You already know =. Here are the convenient shortcuts:

Operator Equivalent To
x += 5 x = x + 5
x -= 3 x = x - 3
x *= 2 x = x * 2
x /= 4 x = x / 4
x //= 2 x = x // 2
x %= 3 x = x % 3
x **= 2 x = x ** 2
      
score = 100 score += 50 # score is now 150 score -= 30 # score is now 120 score *= 2 # score is now 240 print(score) # 240

2.5 Operator Precedence — Who Goes First?

Python follows PEMDAS (like math class):

      
1. () Parentheses 2. ** Exponentiation 3. +x, -x Unary plus/minus (signs) 4. *, /, //, % Multiplication, division, floor division, modulus 5. +, - Addition, subtraction 6. ==, !=, >, <, >=, <= Comparisons 7. not Logical NOT 8. and Logical AND 9. or Logical OR
      
# What's the result? result = 2 + 3 * 4 # 14, not 20 — multiplication first result = (2 + 3) * 4 # 20 — parentheses override result = 10 - 4 / 2 # 8.0 — division before subtraction result = 2 ** 3 ** 2 # 512 — right-to-left: 2 ** (3 ** 2) = 2 ** 9

💡 Golden Rule: When in doubt, use parentheses. They cost nothing and prevent bugs.


2.6 input() — Talking to Your User

input() pauses your program and waits for the user to type something and press Enter. It always returns a string.

      
name = input("What is your name? ") print("Hello, " + name + "!")

Example run:

      
What is your name? Alice Hello, Alice!

⚠️ The #1 trap: Even if the user types 42, input() returns "42" (a string), not 42 (an integer).

      
age = input("How old are you? ") # User types "25" print(age * 2) # "2525" — string repetition, not 50!

2.7 Type Casting — Converting Between Types

This is how you fix the input() problem:

Function What It Does Example
int() Converts to integer int("42") → 42
float() Converts to float float("3.14") → 3.14
str() Converts to string str(100) → "100"
bool() Converts to boolean bool(1) → True

The correct pattern for numeric input:

      
# Pattern: Wrap input() with the type you need age = int(input("How old are you? ")) # Now age is a real integer! print(age * 2) # Works correctly: 50 print(age + 10) # Works correctly: 35

What can go wrong:

      
int("hello") # ❌ ValueError: invalid literal for int() int("3.14") # ❌ ValueError — can't convert float string directly to int int(float("3.14")) # ✅ 3 — two-step conversion: str → float → int float("42") # ✅ 42.0 — works fine str(3.14) # ✅ "3.14" bool("False") # ⚠️ True! — non-empty strings are truthy!

⚠️ bool("False") is True because the string "False" is non-empty. Only bool("") (empty string) gives False.


3. Code Examples — Putting It All Together

Example 1: Simple Calculator

      
# A basic calculator that adds two user-entered numbers print("=== SIMPLE ADDER ===") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) result = num1 + num2 print("The sum is:", result) # Verify types print("num1 type:", type(num1)) print("result type:", type(result))

Example 2: Age Verifier

      
# Check if someone meets multiple conditions age = int(input("Enter your age: ")) has_id = input("Do you have an ID? (yes/no): ") is_adult = age >= 18 has_id_bool = (has_id == "yes") can_enter = is_adult and has_id_bool print("\n=== ENTRY CHECK ===") print("Over 18?", is_adult) print("Has ID?", has_id_bool) print("Allowed to enter?", can_enter)

Example 3: All Operators in Action

      
# Demonstrating every operator type a = 15 b = 4 print("=== ARITHMETIC ===") print(f"{a} + {b} = {a + b}") print(f"{a} - {b} = {a - b}") print(f"{a} * {b} = {a * b}") print(f"{a} / {b} = {a / b}") # Always float print(f"{a} // {b} = {a // b}") # Integer division print(f"{a} % {b} = {a % b}") # Remainder print(f"{a} ** {b} = {a ** b}") print("\n=== COMPARISON ===") print(f"{a} == {b}: {a == b}") print(f"{a} != {b}: {a != b}") print(f"{a} > {b}: {a > b}") print(f"{a} < {b}: {a < b}") print("\n=== LOGICAL ===") x, y = True, False print(f"{x} and {y} = {x and y}") print(f"{x} or {y} = {x or y}") print(f"not {x} = {not x}")

Note: We're using f-strings (the f before quotes) — they let you embed variables directly inside {}. More on strings on Day 8, but start using them now!


4. Hands-On Exercises

Exercise 1: Temperature Converter

Convert Celsius to Fahrenheit. Formula: F = (C × 9/5) + 32. Ask the user for Celsius and print Fahrenheit.

Exercise 2: Even or Odd Detector

Ask the user for a whole number. Print whether it's even or odd. (Hint: use %)

Exercise 3: Eligibility Checker

Ask the user for their age and years of experience. Print True if they are at least 25 years old AND have 3+ years of experience. Print False otherwise.

Exercise 4: Tip Calculator

Ask for the bill amount and tip percentage (e.g., 15 for 15%). Calculate and print the tip amount, total bill, and amount per person (ask for number of people too).

Exercise 5: Logical Operator Practice

Without running the code, predict the output. Then verify:

      
a, b, c = 10, 20, 30 print((a < b) and (b < c)) print((a > b) or (b < c)) print(not (a == 10)) print((a + b > c) and (b - a == 10)) print((a * 2 == b) or (c / 2 == b) and (a < c))

5. Applied Challenge Task 🏗️

Smart Grade Calculator

Build a program that:

  1. Asks the student for their name
  2. Asks for three test scores (0–100 each)
  3. Calculates the average score (sum ÷ 3)
  4. Determines if the student passed (average ≥ 60)
  5. Determines the letter grade:
    • 90–100: A
    • 80–89: B
    • 70–79: C
    • 60–69: D
    • Below 60: F
  6. Prints a clean summary:
      
=== GRADE REPORT === Student: Alex Scores: 85, 92, 78 Average: 85.0 Letter Grade: B Passed: True =====================

Stretch goals:

  • Validate that scores are between 0–100 (print a warning but don't crash)
  • Use += to accumulate the total score
  • Handle the edge case where average is exactly on a boundary (e.g., 89.5 → round up?)

6. Brief Review Summary

Concept Key Points
Arithmetic +, -, *, /, //, %, ** — / always returns float
Comparison ==, !=, >, <, >=, <= — always return bool
Logical and, or, not — combine boolean expressions
Assignment =, +=, -=, *=, /=, etc. — convenient shortcuts
Precedence PEMDAS + comparisons before logical — use parentheses!
input() Pauses for user input — always returns a string
Type Casting int(), float(), str(), bool() — convert between types
Pattern int(input(...)) — the standard way to get numeric input

7. Preview of Next Topic — Day 3

Tomorrow we enter the world of decision-making:

  • Conditional statements: if, elif, else
  • Boolean logic in depth
  • Nested conditions
  • Ternary expressions (one-line if/else)
  • Writing programs that branch based on conditions

🎯 Your Action Items for Day 2:

  1. ✅ Complete all 5 exercises
  2. ✅ Complete the Smart Grade Calculator challenge
  3. ✅ Experiment with each operator in the interactive shell
  4. ✅ Try breaking int() and float() with bad input — see what errors you get

Comments

Popular posts from this blog

Day 1: Welcome to Python — Your Journey Begins

Day 11: List Comprehensions & Lambda Functions

Python: Your Gateway to Coding Adventures

Earn From the Comfort of Your Home

Build the skills to work comfortably from home, on your own terms.

Get Started Today