Skip to main content

Loops in Python

Loops in Python

Loops are used when you have a block of code which you want to repeat a fixed number of times. There are two type of loops in python:

  • While Loop
  • For Loop

While Loop

While loop in python is also known as pre-tested loop, because it first tests the condition then it allows the statement to execute written under it, until it is true.

For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). For loop is written with range function.


The Range() Function

The range is built in function in Python that allows you to generate a series of numbers within a given range. There are three ways you can call range():

  • Range(stop)
  • Range(start, stop)
  • Range(start, stop, step)
Example 1 - 

for x in range(5):
print(x)

Output - 

0
1
2
3
4

Example 2 - 

for x in range(1, 5):
print(x)

Output - 

0
1
2
3
4

Example 3 -

for x in range(1, 10, 2):
print(x)

Output - 

1
3
5
7
9


Comments

Popular posts from this blog

Q & A Chapter 1 | Internet Basics | Class 10 CBSE | Computer Application

 Q & A of Chapter 1 Internet Basics A. Tick the correct options – 1. (b) TCP/IP 2. (a) Internet Service Provider 3. (a) URL 4. (b) HTTP 5. (a) Bridge 6. (a) home page 7. (d) All of these 8. (b) Domain Naming System 9. (b) Rules 10. (d) ARPANET B. Very Short Answer Type Questions – 1. In the URL http://www.myfirm.co.in/about.html , what do the following components depict? (a) http                                                 (b) in (a) Http represents a type of server and the protocol on the Internet (b) ‘in’ represents the domain extension of the website. 2. In the URL http://www.favmusic.com/contactus.html what does www.favmusic stand for? www.favmusic represents the domain name i.e. favmusic in www. 3. W...

Create Composite Key in SQL

What is a composite key? A composite key in SQL can be defined as  a combination of multiple columns , which are used to identify all the rows involved uniquely. Even though a single column can't identify any row uniquely, a combination of over one column can uniquely specify any record. How to create a composite key? EG: