Advance Python - Session 3 : Python Conditionals and Loops

Home Page

 Advance Python - Session 3 : Python Conditionals and Loops

The range() function

The range() function of Python generates a list which is a special sequence type.

A sequence in Python is a succession of values bound together by a single name. Some Python sequence are : Strings, lists, tuples, etc.

Syntax

1)range(<lower limit>, <upper limit>)

E.g : range (0, 5)

It will produce a list as [0,1 ,2 ,3 ,4]

Note: The lower limit is included in the list but upper limit is not included in the list.

2) range(<lower limit>,<upper limit><step value>)   

# all values should be integers

E.g : range(l, u, s) will produce         l, l+s, l+2s, ..... <=u-1

range (0,10, 2) will produce list as [0, 2, 4, 6, 8]

3) range (5) will produce list [0, 1, 2, 3, 4]


The for LOOP

The for loop of Python is designed to process the items of any sequence, such as a list or a string, one by one.

Syntax:

for<variable>in <sequence>:

statements_to_repeat

E.g : for a in [1, 4, 7]:

        print(a)

Output: 

1

4

7

A for loop in Python is processed as:

- The loop-variable is assigned the first value in the sequence.

- All the statements in the body of for loop are executed with assigned value of loop variable.

- Then the loop variable is assigned the next value in the sequence and the loop-body is executed with the new value of loop variable.

- This continues untill all values in the sequences are processed.

Comments

Popular posts from this blog

Class X - Artificial Intelligence / Information Technology CBSE Notes by JAINAL ABEDIN

Class X Science Notes

Chapter 5 - Life Processes - Nutrition