0
Can somebody explain me for and while loops? Because I know that they are in course for python but I just don't understand them.
Loops
2 Respostas
+ 7
Well with while loops you can do the exact same as for loops, but also you can change the rate of incrementation and the stop condition. Personally, I use while loops when I don't know when I want to stop 😅😅
For example, imagine you have a function prime() and you want to print the first n prime numbers. How do you do it with a for loop ? Honestly I don't know, because we need to stop the loop somewhere and with a for loop in this case it is tricky to find the end.
So we'll do this:
number_primes=0
while not number_primes==n:
if prime(number_primes):
print(number_primes)
number_primes=number_primes+1
So there's an example where you can use a while loop but can't use a for loop. I hope it helped...
+ 3
I have written two detailled tutorials about what you can do with 'for' in Python.
I'll have to let someone else handle while. 😉
https://code.sololearn.com/cSdiWZr4Cdp7/?ref=app
https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app