While loops are control flow statements used to repeatedly execute a block of code as long as a specified condition remains true. They provide a way to iterate over a block of code until a certain condition is met.
We'll learn about the following topics:
A while loop allows you to repeatedly execute a block of code as long as a certain condition is true.
The general syntax of a while loop is as follows:
while condition: code block to execute while the condition is true
Here's a breakdown of the different components:
1. Condition: The condition is an expression that evaluates to either True or False. It determines whether the code block associated with the while loop should be executed or not. The loop continues executing as long as the condition is True.
2. Code Block: The code block is indented and consists of one or more lines of code. It is executed repeatedly as long as the condition is True. The code block may include any valid Python statements.
count = 0
while count < 5:
print(f'Count: {count}')
count += 1
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
In this example, the variable count is initially set to 0. The while loop's condition count < 5 is evaluated. If the condition is True, the code block is executed, which prints the value of count and increments it by 1 using the count += 1 statement. The loop continues executing until the condition becomes False. The loop is executed five times because the condition count < 5 is satisfied until count becomes 5. Once count is 5, the condition becomes False, and the loop terminates.
It's important to be cautious while using while loops to avoid creating infinite loops. An infinite loop occurs when the condition never becomes False, causing the loop to execute indefinitely. To prevent this, ensure that the condition within the while loop eventually evaluates to False or include an appropriate exit condition within the code block.
In Python, you can add an else clause to a while loop. The code within the else block will be executed once the while loop condition becomes False. Here's the modified syntax:
while condition: code block to execute while the condition is true else: code block to execute once the condition is false
count = 0
while count < 5:
print(f'Count: {count}')
count += 1
else:
print('Loop completed successfully')
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Loop completed successfully
In this example, the while loop executes as long as the condition count < 5 is true. Once count becomes 5, the condition becomes False, and the loop terminates. At that point, the code block within the else clause is executed, which prints the message "Loop completed successfully".
The else clause provides a way to include code that should execute after the while loop completes normally, i.e., when the condition becomes False. It is useful when you want to perform some actions or provide feedback once the looping is finished.
1. Pass Statement:
The pass statement in Python is a placeholder statement that does nothing. It is used when you need a statement syntactically but don't want to execute any code. It is often used as a placeholder for future code implementation.
for i in [0,2,4]:
pass
In this example, the pass statement is used inside a for loop. The loop will iterate three times, but since pass does nothing, it effectively does not affect the loop's behavior. It allows you to create a syntactically valid loop without executing any code within the loop body.
2. Break Statement:
The break statement is used to exit a loop prematurely. It terminates the execution of the nearest enclosing loop and transfers control to the next statement after the loop.
x = 0
while x < 10:
print('x is currently: ',x)
print(' x is still less than 10, adding 1 to x')
x+=1
if x==3:
print('Breaking because x==3')
break
x is currently: 0 x is still less than 10, adding 1 to x x is currently: 1 x is still less than 10, adding 1 to x x is currently: 2 x is still less than 10, adding 1 to x Breaking because x==3
3. Continue Statement:
The continue statement is used to skip the remaining code within a loop iteration and move to the next iteration. It allows you to bypass specific parts of the loop's code block based on a certain condition.
for i in [0,1,2,3,4]:
if i == 2:
continue
print(i)
0 1 3 4
In this example, the loop iterates over the numbers 0 to 4. When i equals 2, the continue statement is executed, and the remaining code within that iteration (the print(i) statement) is skipped. The loop then proceeds to the next iteration.
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
1 2 4 5
In this example, the while loop continues as long as count is less than 5. When count equals 3, the continue statement is executed, skipping the remaining code in that iteration (the print(count) statement). The control then goes back to the loop's condition evaluation.
A one-line while loop, also known as an inline while loop or a single-line while loop, allows you to write a compact while loop in a single line of code.
while condition: statement
Here's a breakdown of the components:
1. Condition: The condition is an expression that evaluates to either True or False. It determines whether the loop will continue executing or terminate.
2. Statement: The statement is the code or action to be executed within the loop. It typically performs a specific task or updates variables.
It's important to note that one-line while loops are suitable for simple and concise situations. For more complex scenarios, it is generally recommended to use multi-line while loops for better readability.
count = 0
while count < 5: count += 1; print(f'Count: {count}')
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
In this example, the one-line while loop has two statements separated by a semicolon (;). The first statement count += 1 increments the count variable by 1, and the second statement print(f"Count: {count}")
prints the current value of count. The loop continues executing as long as the condition count < 5 is True. The following multi-line while loops is as follows:
count = 0
while count < 5:
print(f'Count: {count}')
count += 1
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
n = 5
while n > 0: n -= 1; print(n)
4 3 2 1 0
range()
function is used to generate a sequence of numbers within a specified range.range(start, stop, step)
Here's a breakdown of the different parameters:
start (optional): This parameter represents the starting value of the range. If not specified, it defaults to 0.
stop (required): This parameter represents the end value of the range. The range() function generates numbers up to, but not including, this value.
step (optional): This parameter specifies the increment between each number in the sequence. If not specified, it defaults to 1.
range(5)
range(0, 5)
It's important to note that the range() function returns a range object, which is an immutable sequence type. To obtain a list of numbers, you can convert the range object to a list using the list()
function.
list(range(0,11))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = list(range(5, 0, -1))
print(numbers)
[5, 4, 3, 2, 1]
for i in range(1, 10, 2):
print(i)
1 3 5 7 9
for i in range(5):
print(i)
0 1 2 3 4
The range() function is commonly used in combination with loops, such as for and while, to iterate over a sequence of numbers. It provides a convenient way to generate and work with ranges of values.
The general syntax of the enumerate() function is as follows:
enumerate(iterable, start=0)
Here's a breakdown of the different parameters:
Iterable: This parameter represents the sequence, such as a list, tuple, string, or any other iterable object, over which you want to iterate.
Start (optional): This parameter specifies the starting value of the index. It defaults to 0 if not specified.
The enumerate() function returns an enumerate object, which is an iterator that generates pairs of index-value tuples.
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple 1 banana 2 orange
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple 1 banana 2 orange
list(enumerate(fruits))
[(0, 'apple'), (1, 'banana'), (2, 'orange')]
In this example, the enumerate() function is used to iterate over the fruits list. For each item in the list, the function returns a tuple containing the index and the corresponding fruit. The for loop then unpacks the tuples into the variables index and fruit, which are then printed.
It's worth noting that the index values start from 0 by default, but you can specify a different starting value using the start parameter.
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
1 apple 2 banana 3 orange
for i, letter in enumerate('abcde'):
print(f'At index {i} the letter is {letter}')
At index 0 the letter is a At index 1 the letter is b At index 2 the letter is c At index 3 the letter is d At index 4 the letter is e
input()
function is used to receive input from the user through the console or terminal during the execution of a Python program.The input() function pauses the program's execution and waits for the user to enter some text, which is typically followed by pressing the Enter key. The text entered by the user is then returned as a string, which can be stored in a variable or used in any way necessary within the program.
name = input('Enter your name: ')
print('Hello, ' + name + '! Welcome!')
Enter your name: Pegah Hello, Pegah! Welcome!
In this example, the input() function is used to prompt the user to enter their name. The string "Enter your name: " is displayed as a prompt to the user. The program then waits for the user to enter their name and press Enter. The text entered by the user is assigned to the variable name. Finally, the program uses the entered name to print a personalized welcome message.
It's important to note that the input() function always returns a string, even if the user enters a numerical value or any other type of input. If you require a different data type, such as an integer or float, you need to explicitly convert the input using appropriate conversion functions like int() or float().
age = int(input('Enter your age: '))
print('Next year, you will be', age + 1)
Enter your age: 26 Next year, you will be 27
In this example, the input() function is used to receive the user's age as input. The entered value is immediately converted to an integer using the int() function and assigned to the variable age. The program then performs a calculation using the converted integer and displays the result.
min()
and max()
function in Python is used to find the smallest item in an iterable or a series of arguments. It returns the minimum/maximum value from the given inputs.The general syntax of the min()/max() function is as follows:
min(iterable, *args, key=None, default=None) max(iterable, *args, key=None, default=None)
Here's a breakdown of the different parameters:
iterable (required): This parameter represents an iterable object such as a list, tuple, or string. It can also be multiple arguments passed directly to the function.
*args (optional): This parameter allows you to pass additional arguments to the function, which will be included in the calculation of the minimum value.
key (optional): This parameter specifies a function that will be used to determine the value by which the minimum is calculated. It takes a callable as an argument.
default (optional): This parameter specifies the default value to be returned if the iterable is empty and no minimum value is found. If not specified, the min() function raises a ValueError in such cases.
numbers = [5, 2, 8, 1, 9]
minimum = min(numbers)
print(minimum)
1
In this example, the min() function is used to find the minimum value from the numbers list. The minimum value, which is 1, is then assigned to the variable minimum and printed.
maximum = max(5, 2, 8, 1, 9)
print(maximum)
9
words = ['apple', 'banana', 'cherry', 'date']
shortest_word = min(words, key=len)
longest_word = max(words, key=len)
print(shortest_word)
print(longest_word)
date banana
In this example, the min() function is used to find the shortest word from the words list based on their lengths. The key parameter is set to len, which specifies that the length of each word should be considered when determining the minimum. The shortest word, which is 'date', is then assigned to the variable shortest_word and printed.
zip()
function is used to combine multiple iterables (such as lists, tuples, or strings) into a single iterable of tuples. Each tuple contains elements from the corresponding positions of the input iterables.The general syntax of the zip() function is as follows:
zip(*iterables)
Here's a breakdown of the different components:
The zip() function returns an iterator of tuples, where each tuple contains elements from the input iterables at the corresponding positions.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
zipped = zip(names, ages)
print(list(zipped))
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
In this example, the zip() function combines the names and ages lists into a single iterable of tuples. Each tuple contains an element from the names list and the corresponding element from the ages list. The resulting iterable is then converted to a list using the list() function and printed.
It's worth noting that the input iterables passed to zip() do not need to have the same length. The resulting iterable will only contain tuples up to the length of the shortest input iterable. Any extra elements from longer iterables will be ignored.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30]
zipped = zip(names, ages)
print(list(zipped))
[('Alice', 25), ('Bob', 30)]
In this modified example, the ages list has only two elements, while the names list has three. The resulting iterable from zip() contains tuples up to the length of the shortest input iterable, which is two in this case.