FREE INTERACTIVE ONLINE COURSE

Python 3

FOR BEGINNERS


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)


ALL REVIEWS
LESSON 12
PAGE 2 / 3
The for and while Statements
Home >>> Free Online Lessons, Python 3

The Classic Form of for

We used the for statement to navigate sequentially through all the elements of a data collection.

Often, it is necessary to repeat a set of instructions a certain number of times, similar to classic programming in Pascal/C++/Java, etc.

EXAMPLES

Analyze the program below:
Editor - lesson_12.py
       
Console/Output done
DETAILS

The range(final) function takes a positive integer as a parameter and generates a sequence of numbers from 0 to final-1. At each step, an element is used, from left to right, held by the variable n, for processing.

The general form of the range function is

range(start, final, step)

Of course, start (default, 0) and step (default, 1) are optional.

If we write range(1, 6), the numbers will be displayed



and if we use range(1, 10, 2), the odd numbers from 1 to 9 (from 1, in steps of two):



Try it out!

More About range()

The range() function returns a sequence of data, which has the type range in the Python language. You cannot access it directly, for example to print it, but you can iterate over it with for or while.

But... we can use explicit conversion to another type, right?

We can create a list that contains the numbers from 1 to 100 by writing:

my_list = list(range(1, 101))
print(my_list)


The variable my_list will hold a list with 100 elements that we can manipulate. But hey, my_list[0] contains 1, my_list[1] holds 2, and so on. Pay attention to the indices!

Cool, right?
Proceed to the next page.
 home   list  CONTENTS   perm_identity   arrow_upward