0% found this document useful (0 votes)
17 views12 pages

Loop Control Statements - Jupyter Notebook

The document explains escape characters in Python, which are special sequences used to include difficult characters in strings, and provides examples of common escape characters. It also covers f-strings, introduced in Python 3.6, for formatting strings more efficiently and readably. Additionally, it discusses while loops, their syntax, control statements, and various use cases, emphasizing the importance of choosing the right loop type based on specific conditions.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views12 pages

Loop Control Statements - Jupyter Notebook

The document explains escape characters in Python, which are special sequences used to include difficult characters in strings, and provides examples of common escape characters. It also covers f-strings, introduced in Python 3.6, for formatting strings more efficiently and readably. Additionally, it discusses while loops, their syntax, control statements, and various use cases, emphasizing the importance of choosing the right loop type based on specific conditions.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Escape Characters in Python

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.

Common Escape Characters:

Character Meaning Example

\n Newline print("Hello, world!\nThis is a new line.")

\t Tab print("Tab:\tThis is a tab.")

\r Carriage return print("Carriage return:\rThis overwrites the previous line.")

\b Backspace print("Backspace:\bThis deletes the previous character.")

\\ Backslash print("Backslash:\\This is a literal backslash.")

\' Single quote print("Single quote: \'")

\" Double quote print("Double quote: \"")

F-strings (Formatted String Literals)


F-strings, introduced in Python 3.6, provide a concise and readable way to format strings. They
offer a cleaner and more expressive alternative to traditional string formatting methods like %
formatting or the .format() method.

Syntax:

f"Expression {expression1} {expression2} ..."

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)

Hello, Alice! You are 30 years old.

In [2]: name = "Aleeza"


age = 13

print(f"Hello, {name}! You are {age} years old.")

Hello, Aleeza! You are 13 years old.

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}.")

Sum of 5 and 10 is 15.

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}")

The area of a circle with radius 5.00 is 78.540

{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:

Improved readability and maintainability.


Faster performance compared to older formatting methods.
Support for more advanced formatting options.

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:

1. The condition is evaluated.


2. If the condition is True , the code block inside the loop is executed.
3. The condition is evaluated again.
4. If the condition is still True , the loop repeats.
5. If the condition becomes False , the loop terminates.

Example:

In [5]: count = 0 # Initialization


while count < 5: # Condition
print(count) # Code block
count += 1 # Update: increments the number value by 1

0
1
2
3
4

Key Points:

The while loop continues to execute as long as the condition is True .


Make sure to include a statement within the loop that modifies the condition to eventually
make it False to avoid infinite loops.
Use break and continue statements to control the flow within a while loop.
In summary,
For Loops:

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.

Choosing the Right Loop:

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.

Loop Control Statements


In Python, loop control statements are used to change the flow of loops (like for or while
loops). They help you control how the loop behaves during execution. Python provides three
key loop control statements:

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:

In [6]: for i in range(1, 6):


if i == 3:
break # Loop stops when i equals 3
print(i)

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:

In [7]: for i in range(1, 6):


if i == 3:
continue # Skip the rest of the loop when i equals 3
print(i)

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:

In [8]: for i in range(1, 6):


if i == 3:
pass # Does nothing when i equals 3
print(i)

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.

Example 1: while loop with an else block (No break )

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)

Loop completed successfully.


Sum of numbers from 1 to 5: 15

Explanation: The while loop runs until count exceeds 5. Since no break occurs, the
else block is executed.

Example 2: while loop with a break statement and an else block

In [10]: # Initialize a variable


count = 0

# Start a while loop
while count < 5:
print("Count:", count)

# Increment the count


count += 1

# 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.

else with for Loops

The else block with a for loop works similarly. The else block executes only if the loop
completes without a break .

Basic Structure:

for item in iterable:


# Loop body
if condition:
break # Exit the loop early if condition is met
else:
# Code here executes only if no break was encountered

Example 1: for loop with an else block (No break )

In [11]: for x in range(5):


print (f"iteration no {x+1} in for loop")
else:
print ("else block in loop")
print ("Out of loop")

iteration no 1 in for loop


iteration no 2 in for loop
iteration no 3 in for loop
iteration no 4 in for loop
iteration no 5 in for loop
else block in loop
Out of loop

Explanation: Since there is no break , the else block runs after the loop completes.

Example 2: for loop with a break statement and an else clause


In [12]: fruits = ["apple", "banana", "cherry", "date"]
search_item = "mango"

for fruit in fruits:
if fruit == search_item:
print(f"{search_item} found!")
break
else:
print(f"{search_item} not found in the list.")

mango not found in the list.

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.

Use Cases of while Loops in Python

1. Letting the User Choose When to Quit:

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!

In [14]: prompt = "Enter a word (or type 'quit' to exit): "



while True:
user_input = input(prompt)

if user_input == 'quit':
print("Goodbye!")
break
else:
print(f"You entered: {user_input}")

Enter a word (or type 'quit' to exit): Hi


You entered: Hi
Enter a word (or type 'quit' to exit): quit
Goodbye!

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:

In [15]: active = True



while active:
user_input = input("Enter a number (or type 'quit' to stop): ")

if user_input == 'quit':
active = False # Set the flag to False to exit the loop
else:
print(f"You entered: {user_input}")

Enter a number (or type 'quit' to stop): 10


You entered: 10
Enter a number (or type 'quit' to stop): 5
You entered: 5
Enter a number (or type 'quit' to stop): quit

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:

In [16]: age = input("Enter your age: ")



while not age.isdigit(): # Repeat until the input is a valid number
age = input("Please enter a valid number for your age: ")

print(f"Your age is: {age}")

Enter your age: Twenty


Please enter a valid number for your age: 20
Your age is: 20

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 .

5. Looping Through a List Until a Condition is Met

You can use a while loop to traverse a list and stop once a condition is met.

Example:

In [17]: fruits = ['apple', 'banana', 'cherry', 'mango']


index = 0

while index < len(fruits):
if fruits[index] == 'cherry':
print(f"Found {fruits[index]}!")
break # Stop the loop once 'cherry' is found
index += 1

Found cherry!

Explanation: The loop runs through the list and stops once it finds 'cherry'.

You might also like