Day3: Python Basics: Conditionals, Logical Operators, and Projects

Day3: Python Basics: Conditionals, Logical Operators, and Projects

In this lesson, I worked through conditionals like if, else, elif, and explored nested conditionals and logical operators in Python. I also built practical projects to apply these concepts, such as a Pizza Order Program, a Rollercoaster Ride, and a Treasure Island Adventure game. Here's a breakdown of what I learned and implemented.


?? If-Else Conditionals in Python:

Conditionals allow you to check whether certain conditions are true or false and execute specific code blocks based on that result.

if condition:
    # code to run if condition is True
else:
    # code to run if condition is False        

For example:

if 5 > 2:
    print("Yes, 5 is greater than 2.")
else:
    print("No, this won't run.")        

?? Comparator Operators:

Used to compare values:

1. Greater Than (>)

a = 10
b = 5

if a > b:
    print(f"{a} is greater than {b}")
a = 10
b = 5

if a > b:
    print(f"{a} is greater than {b}")        

Explanation: Since 10 is greater than 5, the condition a > b evaluates to True, and it prints 10 is greater than 5.


2. Less Than (<)

x = 3
y = 8

if x < y:
    print(f"{x} is less than {y}")        

Explanation: Since 3 is less than 8, the condition x < y evaluates to True, and it prints 3 is less than 8.


3. Greater Than or Equal To (>=)

age = 18

if age >= 18:
    print("You are eligible to vote")        

Explanation: Since age is exactly 18, the condition age >= 18 evaluates to True, so it prints You are eligible to vote.


4. Less Than or Equal To (<=)

temperature = 32

if temperature <= 32:
    print("It's freezing point or below")        

Explanation: Since temperature is exactly 32, the condition temperature <= 32 evaluates to True, so it prints It's freezing point or below.


5. Equal To (==)

password = "admin123"
entered_password = "admin123"

if password == entered_password:
    print("Access granted")
else:
    print("Access denied")        

Explanation: The condition password == entered_password checks if both values are the same. Since they match, the condition evaluates to True, so it prints Access granted.


6. Not Equal To (!=)

num1 = 7
num2 = 10

if num1 != num2:
    print(f"{num1} is not equal to {num2}")        

Explanation: Since 7 is not equal to 10, the condition num1 != num2 evaluates to True, and it prints 7 is not equal to 10.


Combining Multiple Comparators:

You can also combine comparators for more complex conditions:

a = 15
b = 10
c = 20

if b < a <= c:
    print(f"{a} is between {b} and {c}")        

Explanation: Here, both conditions b < a and a <= c must be True for the entire expression to evaluate to True. Since 15 is between 10 and 20, the condition is True, and it prints 15 is between 10 and 20.


?? Modulo Operator:

The modulo operator % gives you the remainder of division, which is useful for checking if a number is even or odd.

PAUSE 1 - What is 10 % 3?

print(10 % 3)  # Outputs 1 (since 10 divided by 3 gives a remainder of 1)        

PAUSE 2 - Check Odd or Even:

Using modulo to check if a number is odd or even:

number = int(input("Enter a number: "))
if number % 2 == 0:
    print("Even")
else:
    print("Odd")        

?? Nested If-Else Statements:

You can nest if statements inside other if or else blocks to check more specific conditions.

age = int(input("Enter your age: "))
if age >= 18:
    if age >= 65:
        print("Senior citizen")
    else:
        print("Adult")
else:
    print("Minor")        

?? Multiple If vs If-Elif-Else:

  • If-Elif-Else: Only one condition is executed, starting from the top.
  • Multiple If: All conditions are checked independently, and multiple conditions can be true at the same time.

Example:

# If-Elif-Else block
if condition1:
    # do something
elif condition2:
    # do something else
else:
    # default action

# Multiple If block
if condition1:
    # do something
if condition2:
    # do something else        

?? Rollercoaster Ride Project:


Flowchart

This project checks user input for height, age, and preferences (like a photo) to calculate the final bill.

print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
bill = 0

if height >= 120:
    print("You can ride the rollercoaster!")
    age = int(input("What is your age? "))
    if age < 12:
        bill = 5
        print("Child tickets are $5.")
    elif age <= 18:
        bill = 7
        print("Youth tickets are $7.")
    elif 45 <= age <= 55:  # Age 45-55 rides for free
        print("Have a free ride on us!")
    else:
        bill = 12
        print("Adult tickets are $12.")

    wants_photo = input("Do you want a photo taken? Y or N. ")
    if wants_photo == "Y":
        bill += 3

    print(f"Your final bill is ${bill}")

else:
    print("Sorry, you need to grow taller to ride.")        

?? Pizza Order Project:

Congratulations, you've got a job at Python Pizza! Your first job is to build an automatic pizza order program.

Based on a user's order, work out their final bill. Use the input() function to get a user's preferences and then add up the total for their order and tell them how much they have to pay.

Small pizza (S): $15

Medium pizza (M): $20

Large pizza (L): $25

Add pepperoni for small pizza (Y or N): +$2

Add pepperoni for medium or large pizza (Y or N): +$3

Add extra cheese for any size pizza (Y or N): +$1

Example Interaction

Welcome to Python Pizza Deliveries!
What size pizza do you want? S, M or L: L
Do you want pepperoni on your pizza? Y or N: Y
Do you want extra cheese? Y or N: N
Your final bill is: $28.        

Solution: An automatic pizza order program based on user input for pizza size, pepperoni, and extra cheese.

print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L: ")
pepperoni = input("Do you want pepperoni on your pizza? Y or N: ")
extra_cheese = input("Do you want extra cheese? Y or N: ")

bill = 0

if size == "S":
    bill += 15
elif size == "M":
    bill += 20
elif size == "L":
    bill += 25

if pepperoni == "Y":
    if size == "S":
        bill += 2
    else:
        bill += 3

if extra_cheese == "Y":
    bill += 1

print(f"Your final bill is: ${bill}.")        

?? Logical Operators:

You can combine conditions using logical operators:

  • and: Both conditions must be true.
  • or: At least one condition must be true.
  • not: The condition must be false.

1. and Operator

The and operator requires both conditions to be True for the overall expression to be True.

age = 25
has_id = True

if age >= 18 and has_id:
    print("You are allowed to enter")
else:
    print("Entry denied")        

Explanation: Since age >= 18 is True (age is 25), and has_id is also True, both conditions are satisfied. Therefore, the overall expression is True, and it prints "You are allowed to enter".


2. or Operator

The or operator requires at least one condition to be True for the overall expression to be True.

is_weekend = False
on_vacation = True

if is_weekend or on_vacation:
    print("You can relax today")
else:
    print("You have to work today")        

Explanation: Even though is_weekend is False, on_vacation is True, and since at least one condition is True, the overall expression evaluates to True, so it prints "You can relax today".


3. not Operator

The not operator reverses the condition, making True become False and vice versa.

raining = False

if not raining:
    print("You can go for a walk")
else:
    print("Better stay indoors")        

Explanation: Since raining is False, not raining becomes True, and it prints "You can go for a walk".


Combining Logical Operators

You can combine multiple logical operators for more complex conditions.

age = 20
has_license = True
has_permit = False

if age >= 18 and (has_license or has_permit):
    print("You are allowed to drive")
else:
    print("You are not allowed to drive")        

Explanation:

  • age >= 18 is True.
  • has_license or has_permit checks if the person has either a license or a permit. Since has_license is True, this part evaluates to True.

Because both conditions (age >= 18 and has_license or has_permit) are True, the overall expression evaluates to True, and it prints "You are allowed to drive".


Example with all three: and, or, and not

is_raining = False
has_umbrella = True
is_sunny = True

if not is_raining and (has_umbrella or is_sunny):
    print("You can go outside")
else:
    print("Better stay indoors")        

Explanation:

  • not is_raining evaluates to True because is_raining is False.
  • has_umbrella or is_sunny is True because at least one of them is True (here, both are True).

Since both conditions are True, the final result is True, and it prints "You can go outside".


??? Treasure Island Project:


Flowchart

An adventure game where the user makes choices to find the treasure or meet their doom.

print('''
*******************************************************************************
          |                   |                  |                     |
 _________|________________.=""_;=.______________|_____________________|_______
|                   |  ,-"_,=""     `"=.|                  |
|___________________|__"=._o`"-._        `"=.______________|___________________
          |                `"=._o`"=._      _`"=._                     |
 _________|_____________________:=._o "=._."_.-="'"=.__________________|_______
|                   |    __.--" , ; `"=._o." ,-"""-._ ".   |
|___________________|_._"  ,. .` ` `` ,  `"-._"-._   ". '__|___________________
          |           |o`"=._` , "` `; .". ,  "-._"-._; ;              |
 _________|___________| ;`-.o`"=._; ." ` '`."\ ` . "-._ /_______________|_______
|                   | |o ;    `"-.o`"=._``  '` " ,__.--o;   |
|___________________|_| ;     (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._    "      `".o|o_.--"    ;o;____/______/______/____
/______/______/______/_"=._o--._        ; | ;        ; ;/______/______/______/_
____/______/______/______/__"=._o--._   ;o|o;     _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
choice1 = input('You\'re at a crossroad, where do you want to go? '
                'Type "left" or "right".\n').lower()

if choice1 == "left":
    choice2 = input('You\'ve come to a lake. '
                    'There is an island in the middle of the lake. '
                    'Type "wait" to wait for a boat. '
                    'Type "swim" to swim across.\n').lower()
    if choice2 == "wait":
        choice3 = input("You arrive at the island unharmed. "
                        "There is house with 3 doors. One red, "
                        "one yellow and one blue. "
                        "Which colour do you choose?\n").lower()
        if choice3 == "red":
            print("It's a room full of fire. Game Over")
        elif choice3 == "yellow":
            print("You found the treasure. You Win!")
        elif choice3 == "blue":
            print("You enter a room of beasts. Game Over.")
        else:
            print("You chose a door that doesn't exist. Game Over.")
    else:
        print("You got attacked by an angry trout. Game Over.")

else:
    print("You fell in to a hole. Game Over.")        

Here I used the .lower() function to make user input case-insensitive. This ensures that the program handles user input in a consistent way, regardless of whether the user enters text in uppercase, lowercase, or mixed case.

For example:

user_input = input("Enter your choice: ").lower()

if user_input == "yes":
    print("You chose yes!")
else:
    print("You didn't choose yes.")        

Explanation of .lower():

  • The .lower() function converts all characters of the input string to lowercase, so it doesn't matter if the user types YES, Yes, or yes — all will be interpreted the same.

Using ASCII Art:

Regarding the ASCII art you mentioned from https://ascii.co.uk/art, that’s a great way to enhance your programs by adding creative visual elements!

You can integrate ASCII art directly into your Python programs as multi-line strings. Here’s an example:

# Example of ASCII art integration in Python
ascii_art = """
   __      _
  o'')}____//
   `_/      )
   (_(_/-(_/
"""

print("Here is some cool ASCII art:")
print(ascii_art)        

This approach adds a visual component to your project, giving it more personality or a theme. Just make sure to attribute the website where the art was sourced from when sharing your project, as you've done.


?? Key Takeaways:

  1. Conditionals allow decision-making in programs.
  2. Modulo operator is useful for checking even/odd numbers.
  3. Nested and Multiple Ifs help handle more complex scenarios.
  4. Logical Operators (and, or, not) allow combining multiple conditions.
  5. Built practical projects using conditionals for real-world scenarios like calculating bills or building adventure games.

Stay tuned as I continue to apply these concepts during my #100DaysOfCode journey! ??


要查看或添加评论,请登录

Muhammad Hanzala的更多文章

社区洞察

其他会员也浏览了