Ask coding questions

← Back to all posts
How to use for loops and while loops in python
ParthChawla (15)

Hi guys, I am wondering how to Use the for loops and while loops in python. Please write the full explanation that how did it work and please give me the exact and correct syntax of for and while loops. I have already watched many videos about that but I did'nt understand what did they try to say and what was the syntax. The ones who will explain me properly how to use them and their syntax then I will select their answer only and I will publish it in the Python daily dose series.

Answered by DynamicSquid (5027) [earned 5 cycles]
View Answer
Comments
hotnewtop
DynamicSquid (5027)
while SOMETHING_IS_TRUE:
  # do something

------------------------------------

a = 5
while a > 0:
  print(a)
  a -= 1

------------------------------------

for VARIABLE in ARRAY/RANGE:
  # do something

------------------------------------

for a in range(5):
  print(a)

------------------------------------

arr = [ 5, 6, 7 ]

for a in arr:
  print(a)

try these examples out yourself!

ParthChawla (15)

@DynamicSquid, Thank you so much for the answer. This is easy to understand and has the correct syntax. That is why I have marked your answer the best one.

CodeLongAndPros (1632)

You use for with an iteraterable.
for item in [1, 2, 3]:

for i, l in enumerate([1, 2, 3])

for i in range(1, 10)

and a for loop takes a bool:

while 1 < 2:

Bookie0 (6407)

hi there!

let me explain them to you:

for loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

for example:

for i in range(5): #will repeat for 5 times
  # remember to indent
  print("Hello")

output:

Hello
Hello
Hello
Hello
Hello

another example: a countdown program

import time

countdown = 60 # setting a variable for the countdown
for i in range(60): # repeats 60 times
  print("Countdown: "+str(countdown)) # prints what number we are at
  countdown -= 1	# takes 1 off the countdown (because it has been counted)
  time.sleep(1) #waits 1 sec before continuing

output:

Countdown: 60
Countdown: 59
Countdown: 58
Countdown: 57
Countdown: 56
Countdown: 55
Countdown: 54
# etc until Countdown = 1

learn more about for loops here:
https://www.w3schools.com/python/python_for_loops.asp

https://www.learnpython.org/en/Loops

https://wiki.python.org/moin/ForLoop

https://www.geeksforgeeks.org/loops-in-python/

https://www.tutorialspoint.com/python/python_for_loop.htm


while loops

With the while loop we can execute a set of statements as long as a condition is true.

example:

while True:
  print("Hello")

output:

Hello
Hello
Hello
Hello
Hello

# until infinity

another example: a sort of password guesser:

password = 100 #sets the password

guess = input("guess password: ") #asks for the guss

while guess != password: #keeps on going until password is found
  print("try again!") 
  guess = input("guess password: ") 

  if guess == "100": # if user finds password
    print("youve guessed it!")
    break #ends the loop

output:

learn more about while loops here:

https://www.w3schools.com/python/python_while_loops.asp

https://realpython.com/python-while-loop/

https://www.programiz.com/python-programming/while-loop

https://www.geeksforgeeks.org/python-while-loops/


tell me if you have any other questions ;)
(link to repl with examples: https://repl.it/@Bookie0/helpprob#main.py)

ParthChawla (15)

@Bookie0. If I wanted I would mark you the second one who had the best answer. Currently I have marked @DyanmicSquid's answer as the best

PattanAhmed (1412)

@ParthChawla Hi again,
As you said, Here is my own definition:-
There are two types of Loops:-

1. While Loop

A While Loop is basically a structure in Python which allows us to loop through and execute a block of code multiple times.

Correct syntax of writing a While Loop:

i = 1
while i <= 10:
  print(i)
  i+=1

print('Done with While Loop!')

2. For Loop

A For Loop is a special type of loop in Python which allows us to loop over a different collection of items. It can be used in strings, numbers, and etc...

Correct syntax of writing a For Loop

for letter in "Hello World\n":
  print(letter)

If you need theory beyond these types, Comment me!
Thanks!

Hope this helps

ParthChawla (15)

@PattanAhmed I commented. Now tell me the theory

Coder100 (18930)

Hello, there is no "real" for loop in python. Here's the closest thing:

// C
for (int i = 0; i < 10; i ++) { /* ... */ }
for i in range(10):
  # code

read more

However, a while loop behaves as you expect.
click me

PattanAhmed (1412)

@ParthChawla Hi,
There are two types of Loops in Python
While Loop:-
Check these amazing websites to know more about While Loop:-
Click here

For loop:-
Check this amazing website to know more about For Loop
Click here
Thanks!

Hope this helps

ParthChawla (15)

@PattanAhmed, You answered my question so quick. That is amazing. You really are one of the most top contributers of repl.it. I would have appreciated you if you gave the answers on your own.

PattanAhmed (1412)

@ParthChawla I can't type that much here...
So, I redirected there
Thanks!

Hope that helps

ParthChawla (15)

@PattanAhmed, You are good in coding. I invite you to code with daily ds everyday from 8 to 9pm, India time

ParthChawla (15)

@PattanAhmed, As you are good in coding. Visit the python daily ds and answer the question asked in the python daily dose. If it was right then you can be featured in the next python daily dose

PattanAhmed (1412)

@ParthChawla What is Python ds?
Where is it?

ParthChawla (15)

@PattanAhmed, It is actuall python daily dose which I post everyday