loops-python
loops-python
Syntax • while- The while keyword marks the beginning of the loop.
of while Loop • condition- This is an expression that is evaluated before
each iteration. As long as the condition is True, the loop will
continue executing.
• :(Colon)- The colon signifies the beginning of the indented
block of code, which will be executed in each iteration.
number = 1
while number <= 5:
print(number)
number += 1
In this example:
• number is an iteration variable initialized to 1.
• The while loop continues as long as the condition number <= 5 is true.
• Inside the loop, the current value of number is printed, and number is
incremented by 1 in each iteration.
Example of a
while loop:
The output will be:
1
2
3
4
5
print('Blastoff')
Example 4:
count = 1
Output:
No Yes
count = 1 count< 3 ?
while count <= 3:
number = int(input("enter a number"))
print("The square is " , (number * Input number
print(number*number)
number))
count += 1
count = count +1
end of loop
In Python, you can generate random numbers using the random module.
• Using the random.randint() function: This function generates a random integer between two specified values (inclusive).
Example:
import random
# Generate a random integer between 1 and 10 (inclusive)
random_number = random.randint(1, 10)
print(random_number)
• Using the random.random() function: This function generates a random float between 0 and 1 (excluding 1).
Example:
import random
# Generate a random float between 0 and 1
random_float = random.random()
print(random_float)
for loop in python
A for loop in Python is a control structure that allows you to
execute a block of code repeatedly for a specified number of
times or for each item in a sequence (e.g., a list, tuple, or
string).
PRESENTATION TITLE 11
range() function
(Execute a block of code repeatedly for a specified
number of times)
PRESENTATION TITLE 12
Example 1: number =1
for number in range(1,6):
print(number)
Is
number
<6
5 5
By default the variable number increment by 1
PRESENTATION TITLE 13
Execute a set of statements for each item in a sequence
for variable in sequence:
# Code to be executed in each iteration
PRESENTATION TITLE 14
2:
PRESENTATION TITLE 15
i =5
Example 3:
Is
i>1
print(i)
print('Descending
order!')
PRESENTATION TITLE 16