Lesson-6: Python For Loop

Python For Loop

Python For loop: used quite a lot in Python and other programming languages. Allows code to run multiple times, just like the while loop. In addition, we can easily make many algorithms that we can’t do with while or have difficulty doing with for loops.

tr_harf = "çşöğüİı"
for i in tr_harf:
       print (i)

In the above example, the tr_harf variable is assigned Turkish letters in a string. with the for loop, we treat the word in the tr_harf variable letter by letter. Each time it assigns a letter to the variable i in order. the screen then prints this letter.

for i in nums:
     print (int(i))
fruit= ["apple","pear","grapes"]
    for i in fruit:
         print (i)


tr_letter = "çşöğüİı"
pass=input ("enter your password :)
for x in pass:
     if x in tr_letter:
          print ("Your password has a Turkish character.")

In the above example, the user is asked to enter a password. Check whether there are Turkish characters in this password entered. the letters in the cipher variable are taken into the variable and thrown into the x variable one by one. If the variable x exists in tr_letter, the screen reads “There is a Turkish character in your password.”the warning is printed.

RANGE Function

The Python range () function creates loop structures in a certain increment according to the start and end values according to the parameters we give.

for i in range (0,10) —-> creates a loop starting from 0 to 10. 10 not included.
for i in range (0,10,2) —–> 0 it forms a cycle starting from dan and increasing from 2 to 10.
for i in range (3,10) ——> 3 it starts from den and forms a loop up to 10 A. 3 is not included if 10 is included.
for i in range (10,2) ——-> 10 it forms a loop starting from dan and decreasing backwards to 2.
for i in range (10,0,-2) ——-> 10 start from 0 to 2 backwards and form a cycle.


for i in range (20):
    print (i)
    print ("Process Finished...")

In the example above, there is a loop from 0 to 20, and every value that the variable I receives is printed on the screen.


k_dizi="Learning Python"
for k in k_dizi:
     if k=="n":
        print (counter,". n letter")

The example above finds how many letters “n” are in k_dizi=”Learning Python”.


list1 = ["red","yellow","white","black"]
list2 = ["apple","pear","strawberry"]

for i in list1:
    print ("-"*15)
    for k in list2:
        print(i+" "+k)

There are 2 nested for loops above. This example circulates inside list2 for each element in list1. As an example, the “red” element will be combined with all the elements in list2 individually. The screen output is:


red apple
red pear
red strawberry
yellow apple
yellow pear
yellow strawberry
white apple
white pear
white strawberry
black apple
black  pear
black strawberry

Process finished with exit code 0

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *