looping through loops in python?

  • Last Update :
  • Techknowledgy :

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.,The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):,The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):,With the continue statement we can stop the current iteration of the loop, and continue with the next:

fruits = ["apple", "banana", "cherry"]
x fruits
print(x)

Suggestion : 2

Last Updated : 22 Jun, 2022

Syntax :

while expression:
   statement(s)

Output: 

Hello Geek
Hello Geek
Hello Geek

Syntax:

for iterator_var in sequence:
   statements(s)

apple
orange
kiwi

apple
orange
kiwi

Suggestion : 3

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.,We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate through a sequence using indexing. Here is an example.,In this article, you'll learn to iterate over a sequence of elements using the different variations of for loop.,The range object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in, len and __getitem__ operations.

Syntax of for Loop

for val in sequence:
   loop body

Example: Python for Loop

# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum
sum = 0

# iterate over the list
for val in numbers:
   sum = sum + val

print("The sum is", sum)

When you run the program, the output will be:

The sum is 48

Output

range(0, 10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   [2, 3, 4, 5, 6, 7]
   [2, 5, 8, 11, 14, 17]

We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate through a sequence using indexing. Here is an example.

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index
for i in range(len(genre)):
   print("I like", genre[i])

Suggestion : 4

for x in range(0, 3):
   print("We're on time %d" % (x))

x = 1
while True:
   print("To infinity and beyond! We're getting close, on %d now!" % (x))
x += 1

for x in range(1, 11):
   for y in range(1, 11):
   print('%d * %d = %d' % (x, y, x * y))

def my_range(start, end, step):
   while start <= end:
   yield start
start += step

for x in my_range(1, 10, 0.5):
   print(x)