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

Chapter 3

Python has three main loop structures: the while loop, the for loop, and nested loops. The while loop continuously executes a block of code as long as a condition is true. The for loop iterates over a sequence, executing the block of code for each item. Nested loops have a loop within another loop, allowing iteration over multiple sequences simultaneously. Python also provides break and continue statements to control loop execution flow. Break exits the entire loop, while continue skips the current iteration and continues with the next.

Uploaded by

Elias Petros
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)
44 views12 pages

Chapter 3

Python has three main loop structures: the while loop, the for loop, and nested loops. The while loop continuously executes a block of code as long as a condition is true. The for loop iterates over a sequence, executing the block of code for each item. Nested loops have a loop within another loop, allowing iteration over multiple sequences simultaneously. Python also provides break and continue statements to control loop execution flow. Break exits the entire loop, while continue skips the current iteration and continues with the next.

Uploaded by

Elias Petros
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

Chapter 3.

Understanding Python Loops


❑ Iteration (Loops):
✓ A loop statement allows us to execute a statement or group of statements multiple times as long
as the condition is true. Repeated execution of a set of statements with the help of loops is called
iteration. Loops statements are used when we need to run same code again and again, each time
with a different value.
✓ In python iteration statements there are three types of loops:
1. While loop 2. For loop 3. Nested for loops

4 Basic Flowchart Symbols for Creating a Flowchart

• The Oval. An End or Beginning While Creating a Flowchart. The oval, or terminator, is
used to represent the start and end of a process. ...
• The Rectangle. A Step in the Flowcharting Process. ...
• The Arrow. Indicate Directional Flow. ...
• The Diamond. Indicate a Decision.

1|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
1. Python while loop:

✓ Loops are either infinite or conditional. Python while loop keeps reiterating a block of code
defined inside it until the desired condition is met.
✓ The while loop contains a Boolean expression and the code inside the loop is repeatedly executed
as long as the Boolean expression is true.
✓ The statements that are executed inside while can be a single line of code or a block of multiple
statements.
Syntax: while(expression):
Statement(s)

 While Loop Statement Flowchart:

Example of while loop: Write a python source code which display “Automotive
Engineering “ six times on console.
i =1
while i < = 6:
print("Automotive Engineering")
i=i+1
Output
Automotive Engineering
Automotive Engineering

2|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
Automotive Engineering
Automotive Engineering
Automotive Engineering
Automotive Engineering

2. Python for loop:


Python for loop is used for repeated execution of a group of statements for the desired number of
times. It iterates over the items of lists, tuples, strings, the dictionaries and other iteratable objects.
Syntax:

for x in iterable: for x in sequence:


# code to be executed Or # code to be executed

where, x is any variable


iterable is any object that can be looped over, such as a list, tuple, or string.

 For Loop Statement Flowchart:

Example1: Write python source code which display list of items using python for loop.
fruits =["Apple","Orange","Banana"]
for x in fruits:
print(x)
Output
Apple
Orange
Banana

3|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
Example2: Write python source code which display each character in the string using python for loop.
for x in "Computer":
print(x)
Output
C
o
m
p
u
t
e
r
Pythons enumerate () function
enumerate () is a built-in Python function that can be used to iterate over a sequence (such as a list,
tuple, or string) and return a tuple containing a count (starting from 0 by default) and the
corresponding value of each item in the sequence.
syntax
for index, x in enumerate(iterable)
print(x)
Example 1: write python source code which display an object with index of items using
python for loop.
fruits = ['apple', 'banana', 'orange']
for index, x in enumerate(fruits):
print(index, x)
Output
0 apple
1 banana
2 orange
Exercise: Write a python source code which display an object with index which starts from
specific number using python for loop (The number you want rather than zero)?

Python range () function


The range () is a built-in function that returns a range object that consists series of integer numbers,
which we can iterate using a for loop. In Python, using a for loop with range () , we can repeat an

4|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
action a specific number of times.
Syntax: where, x is any variable
for x in range (start, stop, step):
print(x) default value for start is 0
default value for stop is -1
default value for step is 1
Example1: Write python source code which display number from 0 to 4 using python for loop.
for x in range (0,5): or for x in range (5):
print(x) print(x)
Output Output
0 0
1 1
2 2
3 3
4 4

Example2: Write python source code which display numbers between 2 up to 10 by jumping 2
steps using python for loop.
for x in range (2,11,2):
print(x)
Output
2
4
6
8
10
3. Nested for loop
A nested for loop in python is a loop inside another loop. This is a common programming technique
used to iterate over multiple lists or arrays at the same time.
Nested loop = A loop within another loop (outer, inner)
Syntax of Nested for loop for variable outer in iterable_outer:
for variable_inner in iterable_inner:
# code to be executed

5|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
Example1: Python source code using nested for loop
for x in range (2,4):
for y in range (1,3):
print(x)
Output
2
2
3
3
Example2: Python source code using nested for loop
for x in range (2,4):
for y in range (1,3):
print(y)
Output
1
2
1
2
Example1: Python source code using nested for loop
for i in range(0, 3):
for j in range(0, 2):
print(i, j)
Output
00
01
10
11
20
21
Python Keywords break and continue:
✓ break and continue are two control statements in python that are used to alter the flow of a loop.
1. break is used to terminate the loop immediately, even if the loop condition has not become False
or the entire iterable has not been exhausted. When break is encountered inside a loop, the loop is
exited and the program continues executing from the next statement after the loop.
The syntax of break statement within while loop is as follows:

6|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
while condition:
if some_condition:
break
# code to be executed
Here, condition is the condition that is checked at the start of each iteration of the while
loop. If some_condition evaluates to True, the break statement is executed and the loop
is exited immediately.
Similarly, the syntax of break statement within for loop is as follows:

for variable in sequence:


if some_condition:
break
# code to be executed

Here, variable is the variable that takes the value of each item in the sequence one by one, and the
code block following the for statement is executed for each iteration of the loop. If some_condition
evaluates to True, the break statement is executed and the loop is exited immediately.

Note that the break statement only exits out of the innermost loop that it is contained within. If
the break statement is used within a nested loop, only the inner loop will be exited, and the outer
loop(s) will continue to run.
➢ Example 1. Write a python source code using break keyword within while loop
n=5
while n>0:
n=n-1
if n==2:
break
print(n)
print ("Loop is finished")
➢ Output
4
3
Loop is finished

7|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
➢ Example2. Write a python source code using break keyword within for loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
print("Found 3!")
break
print(number)
print ("Loop ended.")
➢ Output
1
2
Found 3!
Loop ended.
Note that the loop ends after we find the number 3, so the numbers 4 and 5 are not printed.

2. continue is used to skip the current iteration of the loop and continue with the next iteration. When
continue is encountered inside a loop, the loop immediately jumps to the next iteration, without
executing the remaining statements in the loop body for that particular iteration.
The syntax of continue statement within while loop is as follows:

while condition:
if some_condition:
continue
# code to be executed

Similarly, the syntax of continue statement within for loop is as follows:

for variable in sequence:


if some_condition:
continue
# code to be executed

Here, variable is the variable that takes the value of each item in the sequence one by one,
and the code block following the for statement is executed for each iteration of the loop. If
some_condition evaluates to True, the current iteration of the loop is skipped and the loop
moves on to the next iteration.

8|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
Note that the continue keyword only skips the current iteration of the loop, and the loop
continues with the next iteration. If the continue keyword is used within a nested loop, only the
inner loop will skip the current iteration, and the outer loop(s) will continue to run.

➢ Example 1. Write a python source code using continue keyword within while loop
n=5
while n>0:
n=n-1
if n==2:
continue
print(n)
print("Loop is finished")
Output
4
3
1
0
Loop is finished
➢ Example 2. Write a python source code using continue keyword within for loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
print ("Skipping 3...")
continue
print(number)
print ("Loop ended.")
Output
1
2
Skipping 3...
4
5
Loop ended.

9|Page
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
In this example, we have a list of numbers from 1 to 5. We iterate through the list using a for loop,
and for each number, we check if it's equal to 3. If we find the number 3, we print a message indicating
that we're skipping it, and then we skip the current iteration of the loop using the continue keyword.
If we don't find the number 3, we print the number and continue with the next iteration of the loop.
Once the loop has completed, we print a message indicating that the loop has ended.
Note that the number 3 is skipped over, and the loop continues with the numbers 4 and 5.
Example 3.
for i in range(1, 10):
if i == 5:
break
print(i)
Output
1
2
3
4
In the above example, the loop will print all numbers from 1 to 4 but will terminate when i becomes
5.
Example 4. Write a python sources code which print a numbers from 0 to 9 using for loop except 5
number
for i in range(10):
if i == 5:
continue
print(i)
Output
0
1
2
3
4
6
7
8
9

10 | P a g e
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
Exercise
1. Write down the output of python source code given below
for i in range(1, 10):
if i == 5:
break
print(i)
2. What is the output of below python source code given
for i in range(10):
if i == 5:
continue
print(i)
Generating Random numbers in Python

Random number generation in Python involves generating random values that follow certain
probability distributions. The random module in Python provides various functions for generating
random numbers. Here are some commonly used functions:
➢ random.random(): Generates a random floating-point number between 0 and 1.
➢ random.randint(a, b): Generates a random integer between a and b (inclusive).
➢ random.uniform(a, b): Generates a random floating-point number between a and b.
➢ random.randrange(start, stop[, step]): Generates a random integer from the range starting
from start, up to but not including stop, with an optional step parameter.
➢ random.choice(seq): Returns a random element from the given sequence (seq), which can be
a list, tuple, or string.
➢ random.shuffle(seq): Shuffles the elements of a sequence (seq) randomly.
➢ random.sample(population, k): Returns a random sample of length k from a population
sequence (population) without replacement.
These functions are based on pseudorandom number generators (PRNGs) and use a random seed to
initialize the generator. By default, the seed is based on the system time, but you can also set a specific
seed using random.seed() to generate the same sequence of random numbers for reproducibility.
It's worth noting that the random module provides basic random number generation, which may not be
suitable for certain cryptographic or security-sensitive applications. For such cases, you should use the
secrets module, which provides more secure random number generation capabilities.

11 | P a g e
Prepared by: Amank @ AMU 2023 4th year Automotive Eng
Here are a few examples of generating random numbers in different ways:

12 | P a g e
Prepared by: Amank @ AMU 2023 4th year Automotive Eng

You might also like