Skip to content

Latest commit

 

History

History
518 lines (373 loc) · 9.46 KB

README.md

File metadata and controls

518 lines (373 loc) · 9.46 KB

Chapter 4: Control Flow and Conditionals

Table of Contents

Conditional Statements

Conditional statements allow you to execute different blocks of code based on certain conditions.

if Statement

The if statement executes a block of code if a specified condition is true.

x = 10
if x > 5:
    print("x is greater than 5")

Output:

x is greater than 5

if-else Statement

The if-else statement executes one block of code if the condition is true, and another block if the condition is false.

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

Output:

x is not greater than 5

if-elif-else Statement

The if-elif-else statement allows you to check multiple conditions.

x = 7
if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but less than or equal to 10")
else:
    print("x is 5 or less")

Output:

x is greater than 5 but less than or equal to 10

Nested if Statements

You can nest if statements inside other if statements.

x = 15
if x > 10:
    print("x is greater than 10")
    if x > 20:
        print("x is also greater than 20")
    else:
        print("x is not greater than 20")

Output:

x is greater than 10
x is not greater than 20

Comparison Operators

Comparison operators are used to compare two values.

x = 10
y = 20

print(x == y)  # Equal to
print(x != y)  # Not equal to
print(x > y)   # Greater than
print(x < y)   # Less than
print(x >= y)  # Greater than or equal to
print(x <= y)  # Less than or equal to

Output:

False
True
False
True
False
True

Example: Checking Age

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are an adult.

Logical Operators

Logical operators are used to combine conditional statements.

and Operator

The and operator returns True if both conditions are true.

x = 10
y = 20

print(x > 5 and y > 15)  # True
print(x > 15 and y > 15)  # False

Output:

True
False

or Operator

The or operator returns True if at least one condition is true.

x = 10
y = 20

print(x > 5 or y > 25)  # True
print(x > 15 or y > 25)  # False

Output:

True
False

not Operator

The not operator returns True if the condition is false.

x = 10

print(not (x > 15))  # True
print(not (x > 5))   # False

Output:

True
False

Example: Checking Multiple Conditions

age = 25
income = 50000

if age > 18 and income > 30000:
    print("You are eligible for the loan.")
else:
    print("You are not eligible for the loan.")

Output:

You are eligible for the loan.

Identity Operators

Identity operators are used to compare the memory locations of two objects.

is Operator

The is operator returns True if both variables point to the same object.

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)  # True because z is the same object as x
print(x is y)  # False because x is not the same object as y
print(x == y)  # True because x is equal to y

Output:

True
False
True

is not Operator

The is not operator returns True if both variables do not point to the same object.

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is not z)  # False because z is the same object as x
print(x is not y)  # True because x is not the same object as y

Output:

False
True

Membership Operators

Membership operators are used to test if a sequence is presented in an object.

in Operator

The in operator returns True if a specified value is present in the object.

x = ["apple", "banana"]

print("banana" in x)  # True because "banana" is in the list
print("cherry" in x)  # False because "cherry" is not in the list

Output:

True
False

not in Operator

The not in operator returns True if a specified value is not present in the object.

x = ["apple", "banana"]

print("banana" not in x)  # False because "banana" is in the list
print("cherry" not in x)  # True because "cherry" is not in the list

Output:

False
True

Ternary Operator

The ternary operator allows you to assign a value to a variable based on a condition.

x = 10
y = 20

result = "x is greater" if x > y else "y is greater"
print(result)

Output:

y is greater

Example: Checking Even or Odd

number = 5
result = "Even" if number % 2 == 0 else "Odd"
print(result)

Output:

Odd

Match-Case Statement

The match-case statement is used for pattern matching and is similar to the switch statement in other languages.

def http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:
            return "Unknown Status"

print(http_status(200))
print(http_status(404))
print(http_status(500))
print(http_status(123))

Output:

OK
Not Found
Internal Server Error
Unknown Status

Example: Day of the Week

def day_of_week(day):
    match day:
        case 1:
            return "Monday"
        case 2:
            return "Tuesday"
        case 3:
            return "Wednesday"
        case 4:
            return "Thursday"
        case 5:
            return "Friday"
        case 6:
            return "Saturday"
        case 7:
            return "Sunday"
        case _:
            return "Invalid day"

print(day_of_week(1))
print(day_of_week(5))
print(day_of_week(7))
print(day_of_week(0))

Output:

Monday
Friday
Sunday
Invalid day

Operator Precedence

Operator precedence determines the order in which operations are performed in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Precedence Table

Here is a table of operators in Python, listed from highest to lowest precedence:

  1. ** (Exponentiation)
  2. +x, -x, ~x (Unary plus, Unary minus, Bitwise NOT)
  3. *, /, //, % (Multiplication, Division, Floor Division, Modulus)
  4. +, - (Addition, Subtraction)
  5. <<, >> (Bitwise shift operators)
  6. & (Bitwise AND)
  7. ^ (Bitwise XOR)
  8. | (Bitwise OR)
  9. ==, !=, >, >=, <, <=, is, is not, in, not in (Comparisons, Identity, Membership)
  10. not (Logical NOT)
  11. and (Logical AND)
  12. or (Logical OR)
  13. if - else (Ternary operator)
  14. = (Assignment) and other assignment operators (+=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, >>=, <<=)

Examples

Example 1: Exponentiation and Multiplication

result = 2 ** 3 * 4
print(result)

Output:

32

Explanation: Exponentiation (**) has higher precedence than multiplication (*), so 2 ** 3 is evaluated first, resulting in 8, and then 8 * 4 is evaluated, resulting in 32.

Example 2: Addition and Multiplication

result = 2 + 3 * 4
print(result)

Output:

14

Explanation: Multiplication (*) has higher precedence than addition (+), so 3 * 4 is evaluated first, resulting in 12, and then 2 + 12 is evaluated, resulting in 14.

Example 3: Parentheses

result = (2 + 3) * 4
print(result)

Output:

20

Explanation: Parentheses have the highest precedence, so the expression inside the parentheses (2 + 3) is evaluated first, resulting in 5, and then 5 * 4 is evaluated, resulting in 20.

Example 4: Logical Operators

result = not (True and False) or True
print(result)

Output:

True

Explanation: The and operator has higher precedence than not, so True and False is evaluated first, resulting in False. Then not False is evaluated, resulting in True. Finally, True or True is evaluated, resulting in True.

Example 5: Comparison and Logical Operators

x = 10
y = 20
result = x < y and y > 15
print(result)

Output:

True

Explanation: Comparison operators (<, >) have higher precedence than logical operators (and), so x < y and y > 15 are evaluated first, resulting in True and True respectively. Then True and True is evaluated, resulting in True.

Summary

In this chapter, we covered conditional statements, comparison operators, logical operators, identity operators, membership operators, the ternary operator, the match-case statement, and operator precedence.

Tasks

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Write a program that checks if a number is even or odd.
  3. Write a program that takes a grade as input and prints the corresponding letter grade (A, B, C, D, F).
  4. Write a program that uses the match-case statement to print the name of the day of the week based on a number (1 for Monday, 2 for Tuesday, etc.).
  5. Write a program that demonstrates operator precedence by using different operators in a single expression.

Next Chapter: Loops and Iteration