FOR in Python

Loops are used for sequential traversal, that’s mean used for repeating variables such as numbers, strings, lists or sets. The loop continues until it is terminated by the variable or by terminating the loop with the Break command. In this section, we want to learn how to use loops. loop in programming languages is an iterative method and is also found in other object-oriented languages. With a loop, we can execute a set of commands, once for each item. Loops in every programming language start with a set of rules, but they may be slightly different in structure. Python also has statements and conditional loops.

In the first part, we will introduce the FOR-loop Python. With this loop, we can iterate through instructions based on the number considered in the loop. First, we examine its structure:

for <var> in <iterable>:

<statement(s)>

In this structure, the “statement” repeats i times

let’s to see some example

for i in “Hello”:

print(i)

The output of this command: in five lines it prints Hello, line 1 first character, line 2 second character and … 

for i in “Hello”:

print(1)

The output of this command: in five lines it prints 1, line 1 print 1, line 2 print 1 and … 

for i in “55”:

print(i)

The output of this command: in two lines it prints 55, line 1 print 5, line 2 print 5 and … 

if we want to print for example from 1 to 50, we can use command range(): in this command we can make [start,stop,step] 

for i in range (3):

print(i)

The output of this command: in three lines it prints: line 1 print 0, line 2 print 1 and line 3 print 2

We must know range (3), prints 0,1,2. If we want to print 1,2,3 = for i in range (1,3+1)

With [step] we can skip numbers, for example: this prints 1,3,5 = for i in range (1,5+1,2):

let’s to see video from our YouTube channel

If you want to learn more Python, please click here.

Share :
217
keyboard_arrow_up