= 1
i while i <= 5:
print(i)
+= 1 i
1
2
3
4
5
Loops are one of the most powerful features in programming, enabling the repeated execution of a block of code. This repetition is often necessary for tasks such as processing elements in a collection, generating sequences of values, and executing complex algorithms. Understanding loops is essential for developing efficient and concise programs, as they reduce redundancy and simplify code that would otherwise require numerous repetitive statements.
Loops are used to automate repetitive tasks, making code more efficient and easier to manage. Here are some key reasons to use loops:
Python supports two primary types of loops:
while
Loop: Executes a block of code as long as a specified condition is True
. The condition is checked before each iteration.for
Loop: Iterates over a sequence and executes a block of code for each item in the sequence.while
LoopThe while
loop is one of the fundamental control structures in Python, allowing the repeated execution of a block of code as long as a specified condition is True
. This type of loop is particularly useful when the number of iterations is not known beforehand and depends on dynamic conditions during runtime.
The basic syntax of a while
loop is:
while condition:
statement(s)
True
or False
.True
.while
LoopConsider a simple example where we print numbers from 1 to 5:
= 1
i while i <= 5:
print(i)
+= 1 i
1
2
3
4
5
In this example, the variable i
is initialized to 1. The while
loop checks if i
is less than or equal to 5. If the condition is True
, it prints the value of i
and increments i
by 1. The loop continues until i
becomes greater than 5.
A common pitfall with while
loops is the creation of infinite loops, which occur when the loop’s condition never becomes False
. This can cause the program to run indefinitely, potentially causing it to become unresponsive.
Example of an infinite loop:
while True:
print("This loop will run forever.")
To prevent infinite loops, ensure that the loop’s condition will eventually become False
.
while
Loop with Else ClausePython allows an optional else
clause with while
loops. The else
block is executed when the loop condition becomes False
.
Example:
= 1
i while i <= 5:
print(i)
+= 1
i else:
print("Loop ended naturally.")
1
2
3
4
5
Loop ended naturally.
In this example, the else
block is executed after the while
loop finishes executing, printing “Loop ended naturally.”
while
Loopswhile
loops can be nested within other loops to handle more complex tasks, such as iterating over multi-dimensional data structures.
Example:
= 1
i while i <= 3:
= 1
j while j <= 3:
print(j)
+= 1
j += 1 i
In this example, the outer while
loop iterates over the variable i
from 1 to 3, and for each iteration, the inner while
loop iterates over the variable j
from 1 to 3.
Python provides several statements to control the execution of while
loops:
break
: Terminates the loop prematurely.continue
: Skips the rest of the loop body for the current iteration and proceeds to the next iteration.pass
: Does nothing and is used as a placeholder in loops or functions where code will be added later.Examples:
Using break
:
= 1
i while i <= 10:
if i == 5:
break
print(i)
+= 1 i
1
2
3
4
Using continue
:
= 1
i while i <= 10:
if i % 2 == 0:
+= 1
i continue
print(i)
+= 1 i
1
3
5
7
9
Using pass
:
= 1
i while i <= 10:
if i % 2 == 0:
pass # Placeholder for future code
else:
print(i)
+= 1 i
1
3
5
7
9
for
LoopThe for
loop in Python is used for iterating over a sequence. Unlike the while
loop, the for
loop is preferred for its simplicity and readability when working with sequences. It provides a straightforward way to traverse elements in a collection, making it easier to write and understand.
The basic syntax of a for
loop is:
for variable in sequence:
statement(s)
Consider an example where we iterate over a list of numbers and print each number:
= [1, 2, 3, 4, 5]
numbers for num in numbers:
print(num)
1
2
3
4
5
In this example, the for
loop iterates over the list numbers
, and the variable num
takes the value of each item in the list during each iteration.
range()
FunctionThe range()
function generates a sequence of numbers, which is particularly useful for creating loops that run a specific number of times. The range()
function can take up to three arguments: start
, stop
, and step
.
Example using range()
:
for i in range(1, 6):
print(i)
1
2
3
4
5
This loop prints numbers from 1 to 5. The range(1, 6)
function generates the numbers 1, 2, 3, 4, and 5.
Strings are sequences of characters, and you can use a for
loop to iterate over each character in a string.
Example:
= "Hello, World!"
message for char in message:
print(char)
H
e
l
l
o
,
W
o
r
l
d
!
In this example, the for
loop iterates over the string message
, and the variable char
takes the value of each character in the string during each iteration.
As with while
loops, Python provides several statements to control the execution of for
loops:
break
: Terminates the loop prematurely.continue
: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.pass
: Does nothing and is used as a placeholder in loops or functions where code will be added later.Examples:
Using break
:
for i in range(1, 10):
if i == 5:
break
print(i)
1
2
3
4
Using continue
:
for i in range(1, 10):
if i % 2 == 0:
continue
print(i)
1
3
5
7
9
Using pass
:
for i in range(1, 10):
if i % 2 == 0:
pass # Placeholder for future code
else:
print(i)
1
3
5
7
9
for
loops are used in a wide range of practical applications, from data processing to generating patterns. Here are some examples:
Example: Summing Numbers in a List
Calculate the sum of all numbers in a list:
= [23, 45, 12, 89, 34]
numbers = 0
total
for num in numbers:
+= num
total
print("Sum:", total)
Sum: 203
In this example, the for
loop iterates over the list numbers
, adding each number to the variable total
, which holds the sum.
Example: Finding the Maximum Value
Find the maximum value in a list:
= [23, 45, 12, 89, 34]
numbers = numbers[0]
max_value
for num in numbers:
if num > max_value:
= num
max_value
print("Maximum value:", max_value)
Maximum value: 89
In this example, the for
loop iterates over the list numbers
, updating the variable max_value
if a larger number is found.
Write a program that counts down from 10 to 1 using a while
loop.
Write a program that repeatedly asks the user for a number until they enter a negative number. The program should then print the sum of all positive numbers entered.
input()
The input()
function is used to display the given string to the console and wait for user input. The value entered by the user will be a string. Thus, the input must be converted to an int
if an integer is needed in the rest of the code.
For this exercise, you can get the user input with the command
= int(input("Enter a number (negative number to stop): ")) num
Write a program to calculate the factorial of a number using a while
loop. Print the end result. Use an input()
function as in Exercise 2.
Write a number guessing game where the program generates a random number between 1 and 100, and the user has to guess it. The program should give hints if the guess is too high or too low and keep asking until the user guesses correctly.
Use the following code to generate the random number:
import random
= random.randint(1, 100) number
Write a program to calculate the sum of all even numbers between 1 and 50.
Write a program to print all prime numbers between 1 and 50 using a for
loop and conditional statements.