Agenda
- if
- elif
- else
- Nested if
- Pass statement
if Statement in Python
- Syntax:
- The
if
statement is written using theif
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.
- The
a = 33
b = 200
if b > a:
print("b is greater than a")
# Output: b is greater than a
Key Points
- if Keyword:
- The
if
statement starts with theif
keyword followed by a condition and a colon (:
).
- The
- Condition:
- The condition is an expression that evaluates to
True
orFalse
. - If the condition is
True
, the indented block of code following theif
statement is executed.
- The condition is an expression that evaluates to
- 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
.
- Indentation is crucial in Python and defines the block of code associated with the
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.
- Proper indentation is necessary to define nested
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.
- The
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
- elif Keyword:
- The
elif
statement is used after anif
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 toTrue
.
- The
- Multiple Conditions:
- You can have multiple
elif
statements to check several conditions in sequence.
- You can have multiple
- 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 theelif
andelse
statements are skipped.
- Conditions are evaluated in the order they appear. As soon as one condition is met (evaluates to
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 initialif
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 precedingif
andelif
conditions.
- The
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
- else Keyword:
- The
else
statement is used after anif
orelif
statement. - It defines a block of code to be executed if all preceding conditions are false.
- The
- Default Action:
- The
else
block will execute if none of the precedingif
orelif
conditions are met. - It acts as a fallback mechanism for handling cases not covered by specific conditions.
- The
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 inif
orelif
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 areif
statements placed inside anotherif
statement. They allow for more complex conditions by checking additional conditions within the initial condition.
- Nested
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.
- The
a = 33
b = 200
if b > a:
pass # This if statement is not empty but does nothing
Key Points
- 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.
- Allows for checking additional conditions within the scope of the outer
- 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
- 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.
- The
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 ifa
is greater thanb
. - The condition
c > a
checks ifc
is greater thana
. - Since both conditions are true, the code inside the
if
block is executed.
- 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.
- The
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 ifa
is greater thanb
. - The condition
a > c
checks ifa
is greater thanc
. - Since the first condition is true (
a > b
), the code inside theif
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
- While loop
- Break statement
- Continue statement
While Loop in Python
- Definition:
- Python has two primitive loop commands:
while
loops andfor
loops. - The
while
loop allows you to execute a set of statements as long as a given condition is true.
- Python has two primitive loop commands:
Example:
i = 1
while i < 6:
print(i)
i += 1
# Output:
# 1
# 2
# 3
# 4
# 5
Key Points
- Initialization:
- The loop variable
i
is initialized before thewhile
loop starts.
- The loop variable
- 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.
- The loop condition
- Increment:
- The loop variable
i
is incremented within the loop usingi += 1
. - This ensures that the condition will eventually become false, preventing an infinite loop.
- The loop variable
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
andcontinue
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.
- The
Example:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
# Output:
# 1
# 2
# 3
Key Points
- Condition Check:
- The loop starts with
i
initialized to 1. - The
while
loop conditioni < 6
is true, so the loop starts executing.
- The loop starts with
- Print Statement:
- The current value of
i
is printed.
- The current value of
- Break Condition:
- The
if
statement checks ifi
is equal to 3. - When
i
equals 3, thebreak
statement is executed, causing the loop to terminate immediately.
- The
- Increment:
- The loop variable
i
is incremented by 1 after each iteration.
- The loop variable
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.
- The
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 bothwhile
andfor
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.
- The
Example:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
# Output:
# 1
# 2
# 4
# 5
# 6
Key Points
- Condition Check:
- The loop starts with
i
initialized to 0. - The
while
loop conditioni < 6
is true, so the loop starts executing.
- The loop starts with
- Increment:
- The loop variable
i
is incremented by 1 at the beginning of each iteration.
- The loop variable
- Continue Condition:
- The
if
statement checks ifi
is equal to 3. - When
i
equals 3, thecontinue
statement is executed, causing the loop to skip theprint(i)
statement for that iteration and move to the next iteration.
- The
- Print Statement:
- The current value of
i
is printed for each iteration wherei
is not equal to 3.
- The current value of
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.
- The
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 bothwhile
andfor
loops in Python.
for loop in Python
Agenda
- For Loop
- Break Statement
- Continue Statement
- range() Function
- Nested Loop
Python Loop Commands
- while Loops
- 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.
- A
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# Output:
# apple
# banana
# cherry
Key Points
- Sequence:
- The
for
loop iterates over a sequence of elements. In the example, the sequence is a list of fruits.
- The
- Iteration:
- For each iteration, the variable
x
takes the value of the next item in the sequence.
- For each iteration, the variable
- Code Block:
- The code block inside the
for
loop (indented) is executed once for each item in the sequence.
- The code block inside the
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.
- The
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
# Output:
# apple
# banana
Key Points
- Loop Over Sequence:
- The
for
loop iterates over the listfruits
.
- The
- Print Statement:
- For each iteration, the current item
x
is printed.
- For each iteration, the current item
- Break Condition:
- The
if
statement checks if the current itemx
is equal to “banana”. - When
x
equals “banana”, thebreak
statement is executed, causing the loop to terminate immediately.
- The
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.
- The
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 bothwhile
andfor
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”, thecontinue
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 whenx
is “banana”.
- A list named
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:
- 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 tostop - 1
.range(start, stop)
: Generates numbers fromstart
tostop - 1
.range(start, stop, step)
: Generates numbers fromstart
tostop - 1
, incrementing bystep
.
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