UNIT-2 PYTHON PROGRAMMING-II MARKS:-04
Introduction to Iteration
Iteration is a fundamental concept in programming and algorithm design. It refers to the process of
repeating a set of instructions or statements in a loop until a certain condition is met. Iteration is a key
technique for handling repetitive tasks and can be implemented using various looping constructs.
Types of Loops in Python
Python offers two types of loops to handle iteration, allowing you to execute a block of code multiple times based on
different conditions.
1. For Loop
The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or
other iterable objects. It is ideal when you know in advance how many times you need to iterate.
Syntax:
for iterator_var in sequence:
statements(s)
Example:
n=4
for i in range(0, n):
print(i)
Output
0
1
2
3
2. While Loop
The while loop continues to execute a block of code as long as a specified condition remains true. It is used
when the number of iterations is not known in advance and depends on a condition.
Syntax:
while condition:
# Code block to execute
Example:
ount = 0
while (count < 3):
count = count + 1
print("Hello Geek")
output
Hello Geek
Hello Geek
Hello Geek
Jump Statements:- In Python, jump statements are used to alter the flow of execution within loops
and control structures. The primary jump statements in Python are break, continue, and return. Each serves a
distinct purpose:
1. break Statement
The break statement is used to exit from the current loop prematurely. It stops the loop from executing
further, regardless of whether the loop's condition has been met or not.
Usage:
• Inside for or while loops.
• Typically used when a condition is met that makes further iteration unnecessary.
Syntax:
for variable in iterable:
if condition:
break
# More code
Example:
for i in range(10):
if i == 5:
break # Exit the loop when i is 5
print(i)
# Output: 0 1 2 3 4
2. continue Statement
The continue statement skips the remaining code inside the current iteration of a loop and proceeds with the
next iteration. It is often used to skip specific conditions or values without terminating the loop.
Usage:
• Inside for or while loops.
• Useful for skipping over certain iterations based on a condition.
Syntax:
for variable in iterable:
if condition:
continue
# More code
Example:
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
# Output: 1 3 5 7 9
Loop Else Statement:- In Python, the else statement can be used with loops (for and while) to specify a
block of code that should be executed after the loop completes normally. The else block is executed when
the loop terminates due to the loop condition becoming false or when all items in the sequence have been
iterated over. It is not executed if the loop is terminated prematurely by a break statement.
else with for Loop
When used with a for loop, the else block executes after the loop has finished iterating over all items in the
sequence, provided that the loop was not terminated by a break.
Syntax:
for variable in iterable:
# Code to execute for each item
else:
# Code to execute after the loop completes
Example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
else:
print("Loop completed successfully.")
1
2
3
4
5
Loop completed successfully.
In this example, the else block runs after the loop finishes iterating through all the numbers
else with while Loop
When used with a while loop, the else block executes after the loop condition becomes False, provided that
the loop was not terminated by a break.
Syntax:
while condition:
# Code to execute while condition is True
else:
# Code to execute after the loop ends
Example:
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop finished successfully.")
0
1
2
3
4
Loop finished successfully.
In this example, the else block runs after the while loop has finished executing, because the loop condition
(count < 5) is no longer true.
Nested Loops:- Nested loops in Python are loops placed inside other loops. They are used to handle
more complex iteration scenarios, particularly when working with multi-dimensional data structures like
matrices or grids. Here’s a detailed guide on nested loops, including syntax, examples, and use cases.
Syntax of Nested Loops
A nested loop in Python is simply a loop within another loop. The inner loop executes completely every time
the outer loop executes once.
Syntax:
for outer_variable in outer_iterable:
for inner_variable in inner_iterable:
# Code to execute for each combination of outer_variable and inner_variable
Example:
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
Output:
14
15
24
25
What is a String?
A string is a sequence of characters enclosed within quotes. Strings can include letters, numbers, symbols,
and whitespace
Creating Strings
Strings can be created using single quotes, double quotes, or triple quotes for multi-line strings.
Examples:
single_quote_str = 'Hello, World!' # Single quotes
double_quote_str = "Hello, World!" # Double quotes
multi_line_str = """This is a multi-line
string that spans multiple lines.""" # Triple quotes for multi-line strings
raversing a string in Python involves iterating over each character in the string, which can be done using
loops or various methods. This process is essential for tasks like searching for characters, performing
operations on each character, or analyzing the content of the string.
Here’s a guide to traversing strings in Python:
1. Using a for Loop
A for loop can iterate over each character in a string directly. This is one of the simplest and most common
methods for traversing strings.
Example:
text = "Python"
for char in text:
print(char)
P
y
t
h
o
n
String Operators:- Python provides several operators to work with strings, allowing you to perform
operations such as concatenation, repetition, and comparison. Here’s an overview of the primary string
operators in Python:
1. Concatenation (+ Operator)
The + operator is used to concatenate two or more strings, creating a new string that combines the original
strings.
Example:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
2. Membership (in Operator)
The in operator checks if a substring exists within a string. It returns True if the substring is found, and False
otherwise.
Example:
text = "Python programming"
result = "programming" in text
print(result) # Output: True
3. Membership (not in Operator)
The not in operator checks if a substring does not exist within a string. It returns True if the substring is not
found, and False otherwise.
Example:
text = "Python programming"
result = "Java" not in text
print(result) # Output: True
4. Comparison Operators (==, !=, <, <=, >, >=)
Python supports various comparison operators for strings, which can be used to compare strings
lexicographically (i.e., based on alphabetical order).
Examples:
str1 = "apple"
str2 = "banana"
print(str1 == str2) # Output: False
print(str1 != str2) # Output: True
print(str1 < str2) # Output: True (because 'apple' comes before 'banana')
print(str1 <= str2) # Output: True
print(str1 > str2) # Output: False
print(str1 >= str2) # Output: False
String functions and methods:- Python provides a rich set of string functions and methods
for manipulating and processing text. These built-in methods and functions allow you to perform a wide
range of operations on strings, such as searching, replacing, and formatting.
Common String Methods
1. str.upper()
Converts all characters in the string to uppercase.
Example:
text = "hello"
print(text.upper()) # Output: HELLO
2. str.lower()
Converts all characters in the string to lowercase.
Example:
text = "HELLO"
print(text.lower()) # Output: hello
3. str.capitalize()
Converts the first character to uppercase and the rest to lowercase.
Example:
text = "hello"
print(text.capitalize()) # Output: Hello