If … Else/while/For loop in Python (Part-7)

Posted by

Agenda

  1. if
  2. elif
  3. else
  4. Nested if
  5. Pass statement

if Statement in Python

  • Syntax:
    • The if statement is written using the if keyword.
    • Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly brackets for this purpose.
a = 33
b = 200
if b > a:
    print("b is greater than a")
# Output: b is greater than a

Key Points

  1. if Keyword:
    • The if statement starts with the if keyword followed by a condition and a colon (:).
  2. Condition:
    • The condition is an expression that evaluates to True or False.
    • If the condition is True, the indented block of code following the if statement is executed.
  3. Indentation:
    • Indentation is crucial in Python and defines the block of code associated with the if statement.
    • All statements in the indented block are executed if the condition is True.

Example with Indentation

x = 50
y = 100
if y > x:
    print("y is greater than x")
    print("This is part of the if block")
print("This is outside the if block")
# Output:
# y is greater than x
# This is part of the if block
# This is outside the if block

Importance of Indentation

  • Consistent Indentation:
    • It is essential to maintain consistent indentation within a block. Mixing spaces and tabs can lead to errors.
  • Nested if Statements:
    • Proper indentation is necessary to define nested if statements clearly.

Example of Nested if Statements:

a = 10
b = 20
c = 30
if a < b:
    print("a is less than b")
    if b < c:
        print("b is less than c")
# Output:
# a is less than b
# b is less than c

elif Statement in Python

  • Definition:
    • The elif keyword in Python stands for “else if”. It is used to check multiple conditions sequentially. If the previous conditions were not true, it evaluates the current condition.
a = 33
b = 33
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
# Output: a and b are equal

Key Points

  1. elif Keyword:
    • The elif statement is used after an if statement to check another condition if the first condition is false.
    • It allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.
  2. Multiple Conditions:
    • You can have multiple elif statements to check several conditions in sequence.
  3. Order of Evaluation:
    • Conditions are evaluated in the order they appear. As soon as one condition is met (evaluates to True), the corresponding block of code is executed, and the rest of the elif and else statements are skipped.

Example with Multiple Conditions

x = 20

if x > 30:
    print("x is greater than 30")
elif x > 20:
    print("x is greater than 20")
elif x > 10:
    print("x is greater than 10")
else:
    print("x is 10 or less")
# Output: x is greater than 10

Complete Example with if, elif, and else

temperature = 25

if temperature > 30:
    print("It's a hot day")
elif temperature > 20:
    print("It's a nice day")
elif temperature > 10:
    print("It's a bit chilly")
else:
    print("It's cold")
# Output: It's a nice day

Summary

  • The elif statement allows you to check multiple conditions after the initial if statement.
  • It provides a way to add additional conditions that are evaluated if the previous conditions were not true.
  • Using elif statements can help you avoid deeply nested if statements and make your code more readable.

else Statement in Python

  • Definition:
    • The else keyword in Python catches anything which isn’t caught by the preceding if and elif conditions.
a = 200
b = 33

if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("a is greater than b")
# Output: a is greater than b

Key Points

  1. else Keyword:
    • The else statement is used after an if or elif statement.
    • It defines a block of code to be executed if all preceding conditions are false.
  2. Default Action:
    • The else block will execute if none of the preceding if or elif conditions are met.
    • It acts as a fallback mechanism for handling cases not covered by specific conditions.

Example with if, elif, and else

temperature = 35

if temperature > 40:
    print("It's extremely hot")
elif temperature > 30:
    print("It's hot")
elif temperature > 20:
    print("It's warm")
else:
    print("It's cold")
# Output: It's hot

Example with Multiple Conditions and else

x = 10
y = 20
z = 30

if x > y:
    print("x is greater than y")
elif y > z:
    print("y is greater than z")
else:
    print("None of the above conditions are true")
# Output: None of the above conditions are true

Summary

  • The else statement provides a way to handle cases where none of the specified conditions in if or elif statements are met.
  • It is used to define a block of code that will execute if all preceding conditions are false.
  • Using the else statement ensures that your program can handle unexpected or default cases, providing more robust control flow.

Nested if Statements

  • Definition:
    • Nested if statements are if statements placed inside another if statement. They allow for more complex conditions by checking additional conditions within the initial condition.
x = 41

if x > 10:
    print("Above ten,")
    if x > 20:
        print("and also above 20!")
    else:
        print("but not above 20.")
# Output:
# Above ten,
# and also above 20!

Pass Statement

  • Definition:
    • The pass statement is a null operation; nothing happens when it executes. It is useful as a placeholder for future code, particularly when a statement is syntactically required but you have nothing to write yet.
a = 33
b = 200

if b > a:
    pass  # This if statement is not empty but does nothing

Key Points

  1. Nested if Statements:
    • Allows for checking additional conditions within the scope of the outer if condition.
    • Ensures that additional checks are only performed if the initial condition is true.
  2. Pass Statement:
    • Used as a placeholder to avoid errors in empty blocks of code.
    • Ensures that your program remains syntactically correct even when you have not yet written the complete logic.

Example of Nested if Statements

age = 25

if age >= 18:
    print("You are an adult.")
    if age >= 21:
        print("You can drink alcohol.")
    else:
        print("You cannot drink alcohol yet.")
else:
    print("You are a minor.")
# Output:
# You are an adult.
# You can drink alcohol.

Example of Using the Pass Statement

x = 10

if x > 5:
    pass  # Placeholder for future code
else:
    print("x is 5 or less")

print("This is a placeholder example.")
# Output: This is a placeholder example.

Summary

  • Nested if Statements: Useful for performing additional checks within an initial condition, making your logic more specific.
  • Pass Statement: Useful as a placeholder to maintain syntactical correctness without performing any operations.

Multiple Conditions in Python

  1. Using the and Operator
    • The and operator is used to check if both conditions are true. If both conditions are true, the entire expression evaluates to true.
a = 200
b = 33
c = 500

if a > b and c > a:
    print("Both conditions are True")
# Output: Both conditions are True

Explanation

  • The condition a > b checks if a is greater than b.
  • The condition c > a checks if c is greater than a.
  • Since both conditions are true, the code inside the if block is executed.
  1. Using the or Operator
    • The or operator is used to check if at least one of the conditions is true. If either condition is true, the entire expression evaluates to true.
a = 200
b = 33
c = 500

if a > b or a > c:
    print("At least one of the conditions is True")
# Output: At least one of the conditions is True

Explanation

  • The condition a > b checks if a is greater than b.
  • The condition a > c checks if a is greater than c.
  • Since the first condition is true (a > b), the code inside the if block is executed even though the second condition (a > c) is false.

Summary

  • and Operator:
    • Used to ensure both conditions are true.
    • The code block is executed only if both conditions are true.
  • or Operator:
    • Used to ensure at least one condition is true.
    • The code block is executed if any one of the conditions is true.

While loop in Python

Agenda

  1. While loop
  2. Break statement
  3. Continue statement

While Loop in Python

  • Definition:
    • Python has two primitive loop commands: while loops and for loops.
    • The while loop allows you to execute a set of statements as long as a given condition is true.

Example:

i = 1
while i < 6:
    print(i)
    i += 1
# Output:
# 1
# 2
# 3
# 4
# 5

Key Points

  1. Initialization:
    • The loop variable i is initialized before the while loop starts.
  2. Condition:
    • The loop condition i < 6 is checked before each iteration.
    • If the condition is true, the code block inside the while loop is executed.
    • If the condition is false, the loop terminates, and the program continues with the next statement after the loop.
  3. Increment:
    • The loop variable i is incremented within the loop using i += 1.
    • This ensures that the condition will eventually become false, preventing an infinite loop.

Example with Different Condition

i = 10
while i > 0:
    print(i)
    i -= 2
# Output:
# 10
# 8
# 6
# 4
# 2

Infinite Loop

  • If the condition never becomes false, the while loop will continue to execute indefinitely, creating an infinite loop.

Example of Infinite Loop:

i = 1
while i < 10:
    print(i)
    # Missing increment statement
# This will create an infinite loop printing 1 continuously

Using Break Statement to Exit Loop

  • The break statement can be used to exit the loop prematurely.

Example:

i = 1
while i < 10:
    print(i)
    if i == 5:
        break
    i += 1
# Output:
# 1
# 2
# 3
# 4
# 5

Using Continue Statement to Skip Iteration

  • The continue statement can be used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.

Example

i = 1
while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i)
# Output:
# 3
# 5
# 7
# 9

Summary

  • The while loop is used to execute a block of code repeatedly as long as the given condition is true.
  • Properly initialize and update the loop variable to avoid infinite loops.
  • Use break and continue statements to control the flow within the loop.
  • while loops are useful for situations where the number of iterations is not known beforehand and depends on a condition.

Break Statement in Python

  • Definition:
    • The break statement in Python is used to exit the loop prematurely, even if the loop condition is still true.

Example:

i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1
# Output:
# 1
# 2
# 3

Key Points

  1. Condition Check:
    • The loop starts with i initialized to 1.
    • The while loop condition i < 6 is true, so the loop starts executing.
  2. Print Statement:
    • The current value of i is printed.
  3. Break Condition:
    • The if statement checks if i is equal to 3.
    • When i equals 3, the break statement is executed, causing the loop to terminate immediately.
  4. Increment:
    • The loop variable i is incremented by 1 after each iteration.

Use Cases for the Break Statement

  • Exiting a Loop Early:
    • The break statement is useful when you need to exit the loop before the loop condition becomes false, for example, when a certain condition is met.

Example: Searching for an Item:

numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
    if number == 4:
        print("Number 4 found!")
        break
    print(number)
# Output:
# 1
# 2
# 3
# Number 4 found!

Summary

  • The break statement allows you to exit a loop immediately when a specific condition is met, regardless of the original loop condition.
  • It is useful for terminating loops early, improving the efficiency and control flow of your code.
  • The break statement can be used in both while and for loops in Python.

Continue Statement in Python

  • Definition:
    • The continue statement in Python is used to skip the rest of the code inside the loop for the current iteration and proceed with the next iteration.

Example:

i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)
# Output:
# 1
# 2
# 4
# 5
# 6

Key Points

  1. Condition Check:
    • The loop starts with i initialized to 0.
    • The while loop condition i < 6 is true, so the loop starts executing.
  2. Increment:
    • The loop variable i is incremented by 1 at the beginning of each iteration.
  3. Continue Condition:
    • The if statement checks if i is equal to 3.
    • When i equals 3, the continue statement is executed, causing the loop to skip the print(i) statement for that iteration and move to the next iteration.
  4. Print Statement:
    • The current value of i is printed for each iteration where i is not equal to 3.

Use Cases for the Continue Statement

  • Skipping Specific Iterations:
    • The continue statement is useful when you need to skip certain iterations of the loop based on specific conditions.

Example: Skipping Even Numbers:

i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i)
# Output:
# 1
# 3
# 5
# 7
# 9

Summary

  • The continue statement allows you to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
  • It is useful for bypassing specific parts of the loop when a condition is met, improving the control flow of your code.
  • The continue statement can be used in both while and for loops in Python.

for loop in Python

Agenda

  1. For Loop
  2. Break Statement
  3. Continue Statement
  4. range() Function
  5. Nested Loop

Python Loop Commands

  1. while Loops
  2. for Loops

For Loop

  • Definition:
    • A for loop is used for iterating over a sequence, which can be a list, tuple, dictionary, set, or string.

Example:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)
# Output:
# apple
# banana
# cherry

Key Points

  1. Sequence:
    • The for loop iterates over a sequence of elements. In the example, the sequence is a list of fruits.
  2. Iteration:
    • For each iteration, the variable x takes the value of the next item in the sequence.
  3. Code Block:
    • The code block inside the for loop (indented) is executed once for each item in the sequence.

Examples of Iterating Over Different Sequences

Example with a Tuple:

colors = ("red", "green", "blue")
for color in colors:
    print(color)
# Output:
# red
# green
# blue

Example with a String:

for char in "hello":
    print(char)
# Output:
# h
# e
# l
# l
# o

Example with a Dictionary:

person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
    print(key, person[key])
# Output:
# name John
# age 30
# city New York

Example with a Set:

fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
    print(fruit)
# Output (order might vary):
# apple
# banana
# cherry

Summary

  • while Loops: Used for repeated execution as long as an expression is true.
  • for Loops: Used for iterating over a sequence (list, tuple, dictionary, set, or string).

Break Statement in Python

  • Definition:
    • The break statement in Python is used to exit the loop prematurely, even if the loop has not yet finished iterating over all the items.

Example

fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)
    if x == "banana":
        break
# Output:
# apple
# banana

Key Points

  1. Loop Over Sequence:
    • The for loop iterates over the list fruits.
  2. Print Statement:
    • For each iteration, the current item x is printed.
  3. Break Condition:
    • The if statement checks if the current item x is equal to “banana”.
    • When x equals “banana”, the break statement is executed, causing the loop to terminate immediately.

Use Cases for the Break Statement

  • Exiting a Loop Early:
    • The break statement is useful when you need to exit the loop before it completes all iterations, based on a specific condition.

Example: Finding an Item in a List:

numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
    if number == 4:
        print("Number 4 found!")
        break
    print(number)
# Output:
# 1
# 2
# 3
# Number 4 found!

Summary

  • The break statement allows you to exit a loop immediately when a specific condition is met, regardless of the original loop condition.
  • It is useful for terminating loops early, improving the efficiency and control flow of your code.
  • The break statement can be used in both while and for loops in Python.

Continue Statement

  • Purpose: The continue statement is used to skip the current iteration of a loop and proceed with the next iteration.
  • Example Code
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x == "banana":
        continue
    print(x)
  • Explanation:
    • A list named fruits contains three items: “apple”, “banana”, and “cherry”.
    • A for loop iterates through each item in the list.
    • Inside the loop, there is an if statement that checks if the current item (x) is equal to “banana”.
    • If x is “banana”, the continue statement is executed, which skips the rest of the loop for that iteration and proceeds with the next iteration.
    • The print(x) statement will not be executed when x is “banana”.

Output

Based on the example provided, the output of the code will be:

apple
cherry

Range Function

The range() function generates a sequence of numbers, which is commonly used in loops for iterating over a sequence of numbers.

Examples:

  1. Basic Range:
for x in range(6):
    print(x)

output:
0
1
2
3
4
5

Range with Start and Stop:

for x in range(2, 6):
    print(x)
output:
2
3
4
5

Range with Start, Stop, and Step

for x in range(2, 30, 3):
    print(x)

output:
2
5
8
11
14
17
20
23
26
29

Summary:

  • range(stop): Generates numbers from 0 to stop - 1.
  • range(start, stop): Generates numbers from start to stop - 1.
  • range(start, stop, step): Generates numbers from start to stop - 1, incrementing by step.

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
    for y in fruits:
        print(x, y)

Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x