Loop Control Statements - Jupyter Notebook
Loop Control Statements - Jupyter Notebook
Escape characters in Python are special backslash sequences used within strings to represent
characters that are otherwise difficult or impossible to include directly. They allow you to include
special characters, such as newlines, tabs, quotes, or other non-printable characters, in a string
without causing syntax errors. Escape characters start with a backslash ( \ ), followed by the
specific character that represents the desired action or symbol.
Syntax:
To create an f-string, you just add an f or F before the string and place the variables or
expressions inside curly braces {} .
Examples:
1. Embedding Variables: You can insert variables directly into the string.
In [1]: name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)
2. Evaluating Expressions: You can perform operations or call functions inside the curly
braces.
In [3]: a = 5
b = 10
print(f"Sum of {a} and {b} is {a + b}.")
3. Formatting Numbers: You can use f-strings to format numbers with precision.
In [4]: pi = 3.14159
radius = 5
area = pi * radius ** 2
print(f"The area of a circle with radius {radius:.2f} is {area:.3f}")
{radius:.2f} : The radius value is formatted to show two decimal places ( .2f ).
{area:.3f} : The area value is formatted to show three decimal places ( .3f ).
Advantages of F-strings:
while loops
A while loop in Python is a control flow statement that repeatedly executes a block of code
as long as a specified condition remains True . It's a versatile tool for performing actions until
a certain criteria is met.
Syntax:
while condition:
# Code to be executed
How it Works:
Example:
0
1
2
3
4
Key Points:
Use for loops when you know the exact number of iterations beforehand.
Ideal for iterating over sequences like lists, tuples, and strings.
Efficient for processing elements in a defined order.
While Loops:
Use while loops when you need to repeat a block of code until a specific condition is no
longer met.
Suitable for indefinite iteration or when the number of repetitions depends on runtime
conditions.
Provide more flexibility for controlling the loop's execution based on dynamic criteria.
Select the loop type that best matches your program's logic and requirements. Consider factors
such as the known number of iterations, the need for dynamic conditions, and the desired
control over the loop's execution.
1. break Statement
The break statement is used to exit a loop prematurely. When Python encounters a
break inside a loop, it immediately stops the loop and moves on to the next part of the
code after the loop.
Example:
1
2
In this case, the loop stops when i is 3 , so the numbers 1 and 2 are printed, but the loop
does not continue beyond that.
2. continue Statement
The continue statement skips the current iteration of the loop and moves on to the next
one. It does not exit the loop, but it allows you to skip certain parts of the loop based on
conditions.
Example:
1
2
4
5
In this example, the loop skips printing 3 because of the continue statement and moves on
to the next iteration.
3. pass statement
The pass statement is a null operation; it does nothing when executed. It's useful as a
placeholder in code where a statement is syntactically required but you don't want to
execute any code. This can be helpful when you're planning to implement a feature later or
want to have an empty loop body.
Example:
1
2
3
4
5
Here, the pass statement does nothing when i == 3 , and the loop continues as normal.
4. else with Loops:
In Python, you can attach an else block to both for and while loops. The else block
runs only when the loop finishes normally, meaning it doesn't encounter a break statement. If
a break statement is executed during the loop, the else block is skipped.
In [9]: total = 0
count = 1
while count <= 5:
total += count
count += 1
else:
print("Loop completed successfully.")
print("Sum of numbers from 1 to 5:", total)
Explanation: The while loop runs until count exceeds 5. Since no break occurs, the
else block is executed.
# Check a condition
if count == 3:
print("Breaking the loop")
break # Exit the loop when count equals 3
else:
print("Loop terminated without encountering a break statement")
Count: 0
Count: 1
Count: 2
Breaking the loop
Explanation: The loop exits when count reaches 3 due to the break statement, so the else
block is skipped.
The else block with a for loop works similarly. The else block executes only if the loop
completes without a break .
Basic Structure:
Explanation: Since there is no break , the else block runs after the loop completes.
Explanation: The for loop iterates through the list but doesn't find "mango" , so it completes
normally and the else block is executed.
Key Points:
The else block runs only if the loop completes without encountering a break .
If a break statement is encountered, the else block is skipped.
else with loops can be useful for scenarios like searching through lists or performing
tasks that depend on the completion of loops.
A common use case for while loops is to create a menu-driven program where the user can
choose to continue or quit.
Example:
In [13]: while True:
print("Menu:")
print("1. Option 1")
print("2. Option 2")
print("3. Quit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
# Code for Option 1
pass
elif choice == '2':
# Code for Option 2
pass
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
Menu:
1. Option 1
2. Option 2
3. Quit
Enter your choice (1-3): 1
Menu:
1. Option 1
2. Option 2
3. Quit
Enter your choice (1-3): 2
Menu:
1. Option 1
2. Option 2
3. Quit
Enter your choice (1-3): 3
Goodbye!
if user_input == 'quit':
print("Goodbye!")
break
else:
print(f"You entered: {user_input}")
Explanation: The loop runs indefinitely ( while True ) until the user enters 'quit', which
i h h l
2. Using a Flag:
A flag is a variable that can be used to control the execution of a while loop. You can set the
flag to a certain value initially, and then modify it within the loop to determine whether to
continue or break out of the loop.
Example:
if user_input == 'quit':
active = False # Set the flag to False to exit the loop
else:
print(f"You entered: {user_input}")
Explanation: The active flag controls the loop. When the user types 'quit', the flag is set to
False , which breaks the loop.
3. Infinite loops:
While infinite loops are generally avoided, they can be useful in certain scenarios, such as
creating a continuous process or waiting for user input. However, it's important to include a way
to break out of the loop to prevent the program from running indefinitely.
Example:
while True:
# Code to be executed
if user_wants_to_quit:
break
Explanation: This loop will run forever unless you introduce a condition to break out or stop the
program manually.
4. Input Validation:
while loops can be used to validate user input and ensure that it meets certain criteria before
proceeding.
Example:
Explanation: The loop will continue asking for input until the user enters a valid number (using
the .isdigit() method).
The isdigit() method in Python is a string method that checks if all the characters in a
string are digits. If the string consists entirely of digits, the method returns True ; otherwise, it
returns False .
You can use a while loop to traverse a list and stop once a condition is met.
Example:
Found cherry!
Explanation: The loop runs through the list and stops once it finds 'cherry'.