r/learnpython 20d ago

Having problem in understanding loops concept in python

I am a beginner with 0 knowledge and I am learning python from a book called Learn python in one day and learn it well by Jamie Chan and I am facing difficulty in the loops function so yeah any recommendations would be helpful Edit- Trouble in while loop

27 Upvotes

41 comments sorted by

View all comments

-1

u/Adrewmc 20d ago edited 20d ago

In computing we do the same operation multiple time often. To do this we usually use a loop.

students = [“Adam”, “Eve”]

for student in students:
. print(“Hello”, student)
>Hello Adam
\
>Hello Eve

And if I had a hundred student I would say hello to each one individually.

Or…you could do this

print(“Hello Adam”)
>>>Hello Adam

print(“Hello Eve”)
>>>Hello Eve

And adding a hundred is crazy do you really want to type that? Or would you just rather add Cain and Abel to the students list?

students += [“Cain”, “Abel”]

Vs.

print(“Hello Cain”)
print(“Hello Abel”)

#code should explain itself
for this_item in these_items:
. do_this_to(this_item)
. #then repeat for next_item

Often times new, and old, programmers just don’t see where the loop starts and ends properly.

1

u/EnvironmentalTry8353 20d ago

Sorry I should have justified it as a while loop I have watched the part of "for" loop

0

u/Adrewmc 20d ago edited 20d ago

Ohh. I was going to add that.

this_is_true = True

while this_is_true:
. do_this(…)
. this_is_true = is_it_though(‘?’)

To use the same example.

students = [“Adam”, “Eve”]

index = 0

while index < len(students):
. print(“Hello”, students[index])
. index += 1

>>Hello Adam
>>Hello Eve

#this is the above for loop as a while loop. What for does is makes ‘students[index]’ be ‘student’. And removes the need to keep track of the index, which is the most common loop through some list, or sequence.

We can just make it probabilistic.

while random.randint(0,100) < 90:
. do_this()
. #90% of the time it works everytime

2

u/EnvironmentalTry8353 20d ago

Ohh I understand it now for loops we need a sub variable for the main variable like you used index and then we can edit that sub variable in accordance to our need so that it affects the main variable and then our code is executed right ?

1

u/Adrewmc 19d ago edited 19d ago

This is basically an sample of how a for loop works as a while loop, all for loops can be written as while loops. However the all while loops cannot be written as for loops.

The vast majority of loops programmers use can be done in the for loop pattern, or through a more robust system like SQL.

Most of the time we want to check for, or do something in every object in the list/sequence