Card 6: Complex Logic

Module 2: Making Decisions

1 The Hook

Sometimes one check isn't enough.
Think of a VIP Club Bouncer.

  • To enter, you need ID AND a Ticket. (Both must be True)
  • To win a prize, you need a Red Ticket OR Blue Ticket. (Only one needed)

2 Worked Example

We use and, or, and elif (else if) for complex choices.

age = 16
has_ticket = True
if age >= 18 and has_ticket: # Both need to be True
print("Enter VIP")
elif has_ticket: # Runs only if first check failed
print("Enter Regular")
else: # If nothing else worked
print("Go Home")

Common Logic Traps

Trap 1: The Lazy IF

WRONG: if x > 5 and < 10:

Python forgets 'x' in the second part.

RIGHT: if x > 5 and x < 10:

Trap 2: The Negative OR

WRONG: if color != "Red" or color != "Blue":

This is ALWAYS True! (If it's Red, it's not Blue).

RIGHT: if color != "Red" and color != "Blue":

PREDICT

score is 50. What prints?

if score > 80:
  print("Gold")
elif score > 40:
  print("Silver")
else:
  print("Bronze")

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Rollercoaster

1. Copy the code.
2. Change the height requirement to 140.
3. Run it to see if you can still ride.

height = 135
age = 12
if height > 120 and age >= 10:
  print("You can ride")
> _
SILVER (FIX)

🥈 Lazy Logic

This code tries to check if a number is between 10 and 20.
But Python doesn't understand and < 20 without repeating the variable.
Fix it so it reads and num < 20.

> _
GOLD (MAKE)

🥇 Login System

Create a secure login.
1. Ask for user.
2. Ask for password.
3. If user == "admin" and password == "1234", print "Access Granted".
4. Else print "Access Denied".

> _