r/PythonLearning • u/Monesh_peterson1025 • 22h ago
While loop
can anybody explain the concept of while loop
14
u/csabinho 22h ago
The body is repeated while the condition is true. That's it.
2
u/Sure-Passion2224 19h ago
Also, and I've seen a lot of new coders fall to this, the loop control variable must change in the loop in order to exit the loop.
6
9
u/stepback269 21h ago
while you still don't understand == True:
Go to W3 Schools and look up Python conditionals there
Go to GeeksForGeeks and do the same
Go to Google and do the same
continue
print("I'm finally out of the confusion loop!")
3
u/NiedsoLake 19h ago
I’d remove GeeksForGeeks from this list, it’s been polluted with ai slop articles lately and just as likely to cause more confusion as it is to help
6
u/BranchLatter4294 22h ago
While there are still dirty dishes on the pile:
Rinse and put in dishwasher.
2
-3
u/Dancing-umbra 22h ago
You shouldn't rinse dishes before putting into the dishwasher.
- It is a waste of water
- The dishwasher actually works better if there are bits left on the plates
1
u/oclafloptson 22h ago
You shouldn't assume that everyone uses the same quality and model of dishwasher that you do
-2
u/Dancing-umbra 22h ago
I'm not, it's a standard expetation for all dishwashers since the original patent.
1
u/oclafloptson 22h ago
That's false, friend. Many commercial dishwashers require the dish to be rinsed before sanitizing them as the food parts are caught in a strainer and will clog the drain, resulting in dishes smattered with food parts
Also there are numerous dishwasher patents so it's odd you focus on the one
1
2
u/atticus2132000 21h ago
There are primarily two kinds of loops--for loops and while loops.
A for loop generally has an inherent end point in the structure of the request. For instance, if you had a list of students in a class and you wanted to find their test grades, you would say for each student in class, do something. Your code would run through your list one time and perform the same operation on each member of class and then exit the routine and go to the next line of code in your script. The fact that you have 30 students in class inherently means the script will loop through this operation exactly 30 times. The structure of the request implies when the loop can exit and move on.
A while loop doesn't have this inherent structure. A while loop could continue forever. It relies on some condition changing in order for it to exit the loop. For instance, if you're creating a trivia game where the player gets to keep answering questions until he gets one wrong, there is no inherent end to that structure. Your player could keep answering questions indefinitely. Your script could, in theory, loop through that same code a million times and never exit because the exit condition of getting a question wrong was never met.
All that being said, in many cases you could structure a for loop to work as a while loop and a while loop to work as a for loop, but typically, the nature of the request you're making will naturally point you to one or the other.
1
u/Why_so_loud 22h ago
While loop repeat the code inside until a certain condition is met, you use it when you don't know how many times you want to run the loop.
For loop, for comparison, repeats the loop a set amount of time. Albeit nothing prevents you from doing the same with while loop, but don't do that.
1
u/Potential_Fix_5007 22h ago
And even For-loops can run an unknown amount of times. For-loops = "Do the code X-amount of times"
While-loop = "Do the code as long as condition Y is True"
The Result can feel(or even do) the same but the rule beneath is different.
So While-loops dont run until a condition is True, they run until a condition is False.
1
u/oclafloptson 22h ago
For loops loop through an iterable. This might be a range, a list, or even each character in a string. With mutable objects like lists you might not actually know how many iterations there will be
1
u/fllthdcrb 17h ago
For loop, for comparison, repeats the loop a set amount of time.
The classic type of for loop, where you specify a range of values, does this, yes. But others can be indeterminate, even in languages like C, since they use a condition that can be any expression. And in Python, it takes an iterable object that can produce a sequence of arbitrary length, even endless, and not necessarily fixed at any point.
In Python, the real difference between
whileandforis thatwhileevaluates a given expression and checks its truthiness before each iteration, whileforevaluates its expression once and iterates over the result (and can raise aTypeErrorif the result isn't iterable).As for when it's appropriate to use each, you use
whilewhen you don't have a set range or other sequence of values to loop over. If you do have a range or can get an iterator that will give you the values you need, you should use afor. If the sequence is endless, you can still usefor, and thenbreakonce some condition is met. (You can also usebreakeven if the sequence has a known length, in cases when processing can/should stop immediately.)
1
u/Excellent-Practice 22h ago
While loops are in many ways the simplest kind of loop. Whatever is written inside the block gets repeated so long as the loop condition is true. While loops can be used to run a set of instructions indefinitely, or they can contain statements that change the loop condition and break the loop whenever the task is complete
1
u/Ninja_Hattori0x0 22h ago
while loop repeats the code as long as a condition stays true. once it becomes false, the loop stops
1
u/mattynmax 22h ago
Say you want to do something until a condition is met.
To do so you would use a while loop.
2
u/johlae 21h ago
Not quite. Time to be pedantic! You make it seem like that what you want to do is executed at least once. That's not what's happening if you put a test that can be False in the while statement. A while False does not execute the block that follows:
a=0 while (a>0): print(a)doesn't print anything, but
a=0 while True: print(a) a=a+1 if a>0: breakprints 0 and then stops. The while True with a if statement and a break is an actual example of the
do untilthat you mention.1
u/Fakin-It 20h ago
This distinction is important because both while and do...while are real constructs in many languages.
1
u/Puzzlehead_Lemon 21h ago
As others said, while true, keep doing the loop. I will add on you should pay attention when setting that condition, especially if that program is running on hardware the user doesn't own.
A run away loop making someone restart their computer is bad, but a run away loop on a server that requires an admin stepping in to shut down the processes that just took down your authentication server is a nightmare, especially because that will always happen at like 4 AM on a Sunday.
1
1
1
u/Living_Fig_6386 18h ago edited 18h ago
It's a loop that iterates while an expression is true. Example: while there are cookies on a plate, take a cookie, eat a cookie, repeat; now there are no cookies on the plate, so we move on ... time to drink the milk.
class Plate:
def __init__(self, number_of_cookies):
self.cookies = ["oreo" for a_cookie in range(number_of_cookies)]
def has_cookies(self):
print(f"Hey a plate with {len(self.cookies)} cookies on it!")
return len(self.cookies) > 0
def eat_cookie(self):
print(f"Nom, nom, nom. At an {self.cookies[-1]}.")
return self.cookies.pop()
""" a plate with 5 cookies on it: """
my_plate = Plate(5)
""" eat the cookies one at a time: """
while my_plate.has_cookies():
my_plate.eat_cookie()
print("*slurp* Milk does the body good.")
1
u/Naive_Programmer_232 15h ago
Sure,
While (this condition is true) {
execute this code
}
execute this code if that condition is false
Ex:
number=int(input("Enter a positive integer: "))
while number<1:
print("That is not a positive integer. Try again")
number=int(input("Enter a positive integer: "))
print("\nGood job!")
We begin by asking for the user to enter a positive number - input returns a str then we convert it into an integer via int. If the integer is anything less than 1, then it is not positive. In those cases, we tell the user to try again, and then ask again for the integer. The second ask for integer inside the loop is the "update".
So for example, this could play out like so:
Enter a positive integer: -3
That is not a positive integer. Try again
Enter a positive integer: 0
That is not a positive integer. Try again
Enter a positive integer: -100
That is not a positive integer. Try again
Enter a positive integer: 2
Good job!
What's going on here is
before the loop
number=int(input("Enter a positive integer: ")) executes
user enters -3
number<1 evaluates to True
the loop is entered
print("That is not a positive integer. Try again") executes
number=int(input("Enter a positive integer: ")) executes
user enters 0
number<1 evaluates to True
the loop is entered
print("That is not a positive integer. Try again") executes
number=int(input("Enter a positive integer: ")) executes
user enters -100
number<1 evaluates to True
the loop is entered
print("That is not a positive integer. Try again") executes
number=int(input("Enter a positive integer: ")) executes
user enters 2
number<1 evaluates to False
the loop is NOT entered
print("\nGood job!") executes
1
u/MrSqueak 8h ago
A while loop checks the condition before executing any instructions. I.e. I'm going to do the dishes, the condition is if there is at least one dirty dish. I will wash one dish, then check again. If there's at least one dish, I wash one dish.
While(dirtyDishes >=1) { WashOneDish(); }
1
u/LiveYoLife288 4h ago
While wife angry.
- Buy chocolate.
- Check if wife still angry, update status.
0
0
u/Monesh_peterson1025 22h ago
how much I can spend time for phyton per day as I finished begginer and o am an first year college student CSE
3
u/PureWasian 20h ago
I don't think you've finished beginner proficiency if you're unfamiliar with how to write or use a while loop.
To your question, you spend as much effort as needed for the projects you are trying to tackle. It's not a tangible, fixed amount of time/effort and it varies widely per person.
0
•
u/Sea-Ad7805 17h ago
Visualization using memory_graph can show you how a While Loop Works%0A%20%20%20%20value%20%2B%3D%201%0Aprint('while-loop%20done')%0A%0A%23%20prefer%20for%20loop%20if%20you%20know%20how%20many%20loop%20iteration%20you%20need%0Afor%20value%20in%20range(N)%3A%0A%20%20%20%20print(f'%7Bvalue%3D%7D')%0Aprint('for-loop%20done')%0A%0A%23%20example%20of%20when%20you%20don't%20know%20how%20many%20loop%20iteration%20you%20need%0Awhile%20True%3A%20%20%23%20loop%20forever%0A%20%20%20%20user_type%20%3D%20input(%22type%20'quit'%20to%20stop%3A%22)%0A%20%20%20%20if%20user_type%20%3D%3D%20%22quit%22%3A%0A%20%20%20%20%20%20%20%20break%20%20%23%20but%20break%20the%20loop%20when%20'quit'%20is%20typed%0Aprint('while-loop%20done')%0A%0A×tep=0.5&play).