First find what loop you need. If the number of iterations is known beforehand then for. If not known then while. Then find how to draw a random number. Test in the python interpreter. Then find how to use the input function. Test in tje python interpreter. Brick by brick you will build you way ;) Answer from kowkeeper on reddit.com
🌐
Reddit
reddit.com › r/learnpython › how do you loop until correct input is given?
r/learnpython on Reddit: How do you loop until correct input is given?
February 25, 2022 -

I'm doing an assignment that requires I make a code that creates random numbers in a loop until I give a specific input. I just don't know how to get the loop to run while an input is requested. PLZ HELP!

EDIT:

To clarify the assignment:

Write a program that enters a number of positive integers.

The program ends when the user gives in a negative number.

a) Before the program ends, the largest number is printed.

b) Before the program ends, the smallest number is printed.

c) Before the program ends, the sum of the even numbers and the sum of the odd numbers are printed.

(I can do the a,b,c part no problem. It's the Program that creates the numbers i have problems with)

I asked my teacher what he meant by "a number of positive integers". He stated that the program should create numbers until the negative number is given.

EDIT 2:

I have concluded that I'm an idiot. It is the user who inputs the numbers. Thank you all for the help and not giving up with my dense skull :) (great community👍)

🌐
Reddit
reddit.com › r/learnpython › new to python and i need some help with loops.
r/learnpython on Reddit: New to python and I need some help with loops.
August 31, 2023 -

For the past 2 months I have been doing the Codecademy Python 3 course and last month I went into loops and functions and I was incredibly overwhelmed just like I was in Java. Functions are easy nothing special, at least yet, but loops are made me take that month break.

I know the theory of loops. I think I know what commands should be used where and when but for the love of god I can not write a simple loop, even after countless errors. Could anyone point me in the right direction? I really dont want to quit another language for the same reason.

Edit: a user pointed out that I need to elaborate on "simple loops". For example if I had a list and wanted to print a sentence as many times as the length of the list I know I would use len and range and have the print statement inside the loop but I can't implement it

Top answer
1 of 5
2
Loops allow you to repeat a block of code over and over again. There are two main types of loops in Python - for loops and while loops. For loops are used when you know how many times you want to repeat the code. # This will print the numbers 0 to 4 for i in range(5): print(i) The range(5) part creates numbers from 0 to 4. The for loop will go through each of those numbers, storing them in the variable i, and print them out. While loops are used when you don't know exactly how many times you need to repeat the code. You keep looping as long as some condition is true. # This will print numbers as long as x is less than 5 x = 0 while x < 5: print(x) x = x + 1 This starts x at 0, then keeps looping as long as x is less than 5. Each time, it prints x and then adds 1 to x. Once x reaches 5, the loop stops.
2 of 5
2
There are 3 kinds of loops that i can come up with that doesnt include itertools. 1: you have a loop that continues for x amount of iterations by being specific on how many iterations. This loop doesnt let you do anything with the values themself since they are all ints. Example: for i in range(5): (this will do the block of code 5 times starting from 0 and excluding the 5 and i will only be the integers 0 to 4) 2: you have a loop that will do the same as the first loop but this time its through all values in what you are looping through unless you specify on which values you want to loop through using indecies [start, stop, skip] if its a list or a string that is. Example: for my_value in my_list: (this will go through all the values in our list since we didnt specify what values to go through) 3: a condition based loop that will continue until the condition is met. Example of similar principal as the first loop: while i < 5: i+=1 (this will do the code block until i isnt less than 5, if you dont add to i it will never break since then i can never become not less than 5) So if you want to look through the actual values in something you have go with (2), if you want something to go a set number of times go with (1), if you want something to go until you tell it to stop do (3). If you want to know how to write better loops you should look into best practices for that, it doesnt mean like do tasks but just what to think about when making a loop and other things, there is ofc a bunch of mixed thoughts in what is the best and what not but being the best doesnt really mean anything, if it works it works. For your problem you dont need a loop, you already know len() so if you do print("hello")*len(my_list) it will print the msg as many times as the lenght of the list, but you can ofc use loops too, you can have that as excercise by knowing (1) and (3) and len and range.
🌐
Reddit
reddit.com › r/python › why not add do-while loops to python?
r/Python on Reddit: Why not add do-while loops to Python?
August 30, 2019 -

It continues to puzzle me why we have no do-while loop in Python.

In Python code, it's common to see the following pattern:

# ... some code ....
while condition:
    # ... same code copied here ...

This is of course prone to problems because of the "minor" code duplication.

Alternatively, you might see this better option:

def some_code():
    # ... some code ...

some_code()
while condition:
    some_code()

This involves creating a function even though IMHO it often serves to bloat the code unnecessarily.

And than there's this variation:

while True:
    # ... do something ...
    if not condition:
        break

IMHO, this approach, especially when the body of the loop is fairly large, fails to communicate the logical intent of the code in a clean manner.

Of course - all of these approaches do work. But IMHO a syntax which could clarify programmer's intent in the most precise and concise way is the following classical do-while:

do:
    # ... do something ...
    while some_condition

I know that years ago do-while style constructs have been proposed in PEPs and rejected.

But isn't it time we review the idea again? I think there is a considerable amount of code which could benefit from this.

Would love to hear your thoughts :)

🌐
Reddit
reddit.com › r/learnprogramming › [python] for loops vs while loops
r/learnprogramming on Reddit: [python] For loops vs while loops
August 26, 2013 -

I have just started learning python and I am really confused between the while loops and the for loops. I don't seem to understand that if there is a while loop then whats the point of a for loop?? when we have a while loop. why would somebody use for loops over while loops??? Can somebody plz give me some examples over when would I use for for loops over while loops cos I am going really frustrated right now cos of for loops

Top answer
1 of 5
54

Why would somebody use a loop construct when there is goto? Why would somebody use a high-level language when there is assembly language? Why would somebody name their variables when they can just use the memory addresses?

Answer: Because writing code that intuitively "looks like" the thing it is intended to do, both a) makes writing programs much less work, b) dramatically reduces the number of bugs, and c) greatly decreases the difficulty of reading, understanding, and maintaining the code later.

We use for loops when we want to loop over a range, or loop over the elements of a set. This is a fixed operation over a known amount of steps. Essentially, we are saying something along the lines of "for each employee, calculate the salary and submit a payment", so we call it "for" to highlight this relationship. In the case of Python, for loops also provide a special efficient syntax for looping over the elements of a set, so it's less work to type the thing in too. Some other languages call that variant of the for statement "foreach".

We use while loops when we want to continue repeating an operation while a condition continues to hold. For example, we continue looping as long as we encounter no errors, or as long as we receive more data from a network connection. These are not fixed ranges, but take place while a condition holds, so we call it "while".

2 of 5
16

Typically, you use a for-loop when you know how many times you want to loop, for example when iterating over a list. You use a while-loop when you don't know how many times you want to loop - for example, if you want to loop until the user enters the string "quit" from the keyboard.

Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › python loops explained?
r/learnpython on Reddit: Python loops explained?
March 25, 2022 -

About a month in to my Intro to Python class at my local community college, this week was the lecture and HW on "While" and "For In" Loops. I gotta say, I'm completely lost. Anyone have any tips or possibly helpful material for a noobie? Genuinely just seems like everything before this was linear and somewhat straightforward on what the solution or answer was going to become. Now print statements are not what they seem or not in the order in which I believe they were gonna print. The formulas as well, just seems like the difficulty level was raised tremendously lol. Either way Thanks and any help is appreciated.

Top answer
1 of 4
12
for loops (in Python at least) are used when you have some kind of sequence or container, and want to do something with each element/item. As a common real-life example, you might want to buy things from a grocery list, which could look something like enter the shop get a basket for each item on my grocery list: try to find the item if found, add it to the basket otherwise, try to find an alternative if found, add it to the basket # move on go to the counter total_cost = 0 for each item in the basket add item.cost to the total put the item into my backpack pay total_cost take the backpack home while loops are instead focused on doing the same process repeatedly while some condition hasn’t been met yet, e.g. while hole is not big enough, dig for a bit longer It’s useful to have both options, because if you know all the things/steps you need to go through then you can use a for loop, but if you just know the process and know that it will eventually end (but don’t necessarily know how many steps/attempts/iterations it will take to get there) you can use a while loop :-) Then there are extra considerations, like if you run out of money in the shop, or your shovel gets broken, you might want to finish early (break), and if you find a rotten/broken item in your basket you might want to skip paying for it and adding it to your backpack, so you continue to the next loop iteration instead. Sometimes it can be useful to do something extra specifically if the looping process finished ‘normally’, instead of by breaking out of it, in which case you can use else after the loop, e.g. while hole isn’t big enough: dig some more if shovel damaged order a new shovel break elif hands get painful blisters apply some bandaids break else # finished normally admire the completed work pack up equipment # always needs to happen
2 of 4
4
Can you give us an example where you've gotten lost?
🌐
Reddit
reddit.com › r/learnpython › is it weird that i never use while loops? it’s just not something i’ve felt like i needed, ever. what are some situations where using a while loop is necessary?
r/learnpython on Reddit: Is it weird that I NEVER use while loops? It’s just not something I’ve felt like I needed, ever. What are some situations where using a while loop is necessary?
September 29, 2022 -

I’ve written a lot of python code over the last few months, but I can’t think of a single time I’ve ever used a while loop. I mean, I use for loops pretty often, but not while loops.

Is this just down to personal preference, and I’m just using what I’m comfortable with? Or can you guys think of some situations where a while loop would be the easiest way to do things, but it’s possible to do it with a for loop? Maybe I’m using for loops in situations that I should be using while loops.

EDIT: Thanks for the suggestions. I found a few places in my code where a while loop makes sense.

First, I check if a folder has any files in it, and while it does, I delete the first one in the list:

useless_files = os.listdir("MGF_HR_Data") # I think these are files it creates when downloading the MGF data but they are extra and don't do anything 
while len(useless_files)>0: 
    os.remove(f"MGF_HR_Data/{useless_files[0]}") 
    useless_files = os.listdir("MGF_HR_Data") 
    print("Deleting useless file from MGF_HR_Data") 

I also used a while loop to check if the data has been downloaded, and if it hasn't prompt the user to download it and then press enter to check again. This way, the code doesn't break if the user forgot to download the file first:

# Check if you downloaded the file in Matlab already. If not, ask the user to download it and try again. 
while os.path.exists(file1)==False: 
    print(f"{file1} not found. Please open Matlab and run the following code to download the MGF data:" )
    print(f"download({wstime.year}, {wstime.month}, {wstime.day})")
    input("Press enter to try again after downloading the MGF data. \n") 

(Okay, I know this isn't the most efficient way to do this. There must be a way to use python to open matlab and run a matlab command, rather than asking the user to do it themselves. However, I don't know how to do that, so this works for now.)

🌐
Reddit
reddit.com › r/learnpython › python loops
r/learnpython on Reddit: Python Loops
November 9, 2024 -

Completely stuck on the concept of loops. Ive looked through all the recourses possible to get a grasp of it but i just cannot get my mind to understand it!

Someone that has tips to cure this illness of mine?

Top answer
1 of 5
90
When I was learning python, most examples would look like this: colors = ["red", "green", "blue"] for i in range(len(colors)): print(colors[i]) Output: > red > green > blue But you can simplify this a lot: colors = ["red", "green", "blue"] for color in colors: print(color) Output: > red > green > blue Then, if you need the index, you can use enumerate: colors = ["red", "green", "blue"] for i, color in enumerate(colors): print(i, color) Output: > 0 red > 1 green > 2 blue Enumerate basically turns the list of colors into the equivalent of this: colors = [ (0, "red"), (1, "green"), (2, "blue"), ] When you write 'for i, color in ...', you're assigning the first element of each pair to 'i', and the second to 'color', which translates to: i = 0 color = "red" print(i, color) i = 1 color = "green" print(i, color) i = 2 color = "blue" print(i, color) Output: > 0 red > 1 green > 2 blue (You can name i and color anything you want by the way, but it's common to use i to refer to the iteration or index.) You can do something similar with dictionaries: fruit_colors = { "apple": "red", "kiwi": "green", "blueberry": "blue", } for fruit, color in fruit_colors.items(): print(fruit, color) Output: > apple red > kiwi green > blueberry blue Using '.items()' on a dictionary basically turns it into this: fruit_colors = [ ("apple", "red"), ("kiwi", "green"), ("blueberry", "blue"), ] So it's actually very similar to what enumerate does, only the first element of each pair is now the dictionary key rather than the list index. So now you're instructing the program to do this: fruit = "apple" color = "red" print(fruit, color) fruit = "kiwi" color = "green" print(fruit, color) fruit = "blueberry" color = "blue" print(fruit, color) Output: > apple red > kiwi green > blueberry blue Lots of things can be iterators, e.g., characters in a string: sentence = "hello world" for char in sentence: print(char) Output: > h > e > l > l > o > > w > o > r > l > d Nested loops are a bit messy, but let's try to dissect what happens: fruits = ["apple", "kiwi", "blueberry"] colors = ["red", "green", "blue"] for fruit in fruits: for color in colors: print(fruit, color) Output: > apple red > apple green > apple blue > kiwi red > kiwi green > kiwi blue > blueberry red > blueberry green > blueberry blue In the first iteration, you set fruit to "apple". Then you initiate a second loop, that goes through each color one by one in turn. So it's equivalent to this: fruit = "apple" color = "red" print(fruit, color) fruit = "apple" color = "green" print(fruit, color) fruit = "apple" color = "blue" print(fruit, color) ... Once you have gone through all colors, fruit is set to "kiwi", and then all colors are looped through again. When doing a nested loop like this, it's kind of like creating a single list that looks like this: fruit_colors = [ ("apple", ("red", "green", "blue")), ("kiwi", ("red", "green", "blue")), ("blueberry", ("red", "green", "blue")), ] Notice that the fruit changes on each row, but the list of colors stay the same. So when we loop through fruits in the first loop we get: # fruits: 1st iteration fruit = "apple" colors = ("red", "green", "blue") # fruits: 2nd iteration fruit = "kiwi" colors = ("red", "green", "blue") # fruits: 3rd iteration fruit = "apple" colors = ("red", "green", "blue") When we create a second loop for each color in colors inside the fruit loop, we now get: # fruits: 1st iteration fruit = "apple" # colors: 1st iteration color = "red" # colors: 2nd iteration color = "green" # colors: 3rd iteration color = "blue" # fruits: 2nd iteration fruit = "kiwi" # colors: 1st iteration color = "red" # colors: 2nd iteration color = "green" # colors: 3rd iteration color = "blue" ... And so on. A while loop is different from a for loop in that it doesn't loop through an iterator, instead it checks a condition on each iteration, and if the condition is True, then it keeps going. For example: iterations = 0 max_iterations = 3 while iterations < max_iterations: print(iterations) Output: > 0 > 0 > 0 > 0 ... Notice that it just keeps going, since iterations never changes, and 0 is always less than max_iterations = 3. But if we increment iterations by 1 each time, like so: iterations = 0 max_iterations = 3 while iterations < max_iterations: print(iterations) iterations += 1 We get the equivalent of this: # 1st iteration if 0 < 3 is True: print(iterations) iterations = 0 + 1 # 2nd iteration if 1 < 3 is True: print(iterations) iterations = 1 + 1 # 3rd iteration if 2 < 3 is True: print(iterations) iterations = 2 + 1 # 4th iteration if 3 < 3 is True: print(iterations) iterations = 3 + 1 Since the statement in the 4th iteration is '3 < 3', which is False, that code never runs. You can give it any condition you want, like for instance: user_input = "" while user_input =! "quit": user_input = input("write something:") print("user:", user_input) Which will keep asking the user to write something and then print it until the user writes "quit", at which point the loop ends. So basically use for loops when you want to do something once for each item in an iterable, and use while loops when you want to keep doing something until some specific thing happens (like the user wanting to exit the program).
2 of 5
20
Maybe explain what you don't get about them?
🌐
Reddit
reddit.com › r/learnpython › difficulty with basic for loops, while loops, and functions
r/learnpython on Reddit: Difficulty with basic for loops, while loops, and functions
June 28, 2023 -

Complete beginner to python and programming and just enrolled in Angela Yu's 100 Day Python course. I'm only on Day 10 and I am super confused about for loops, while loops, and using the loops in functions. I feel like it's progressing too fast for me.

I'm never able to build the projects without looking at the solutions and I feel like if I continue relying on the solutions to complete the project, I won't actually learn anything.

Does anyone have any advice on how to get a better grip on these basic concepts, and how to practice these concepts by myself?

Top answer
1 of 5
9
I took and finished her Python course, and I agree, it’s VERY fast paced. I highly recommend taking Udacity’s free course (choose no cert) to get the basics down first. You will feel a lot less thrown to the wind afterwards.
2 of 5
7
Let me try an ELI5 approach. A function, at its core, is a program. Because they're often very small and do one thing, it wouldn't be a bad idea to think of them as sub-programs. For example, here's a function that adds two numbers and returns the sum: def add(first, second): return first + second To use it, we call it. result = add(1, 2) # 3 We can use it however many times we want. result = add(add(add(1, 2), 3), 4) # 10 In other words, we have a reusable piece of code we don't need to write again. Of course this is very much a simplified example. As far as loops go, every time you want to repeat an action, you'll probably want a loop. The exact type of loop depends on the specifics, but the core idea is the same. If you know how many times you want to loop, generally speaking you'll want a for-loop. For example, to repeat some action a fixed number of times, or looping over a list. Situations where you know, or at least the interpreter knows, how many times to do something. for num in [3, 1, 4, 1, 5, 9]: print(num) If you don't know how many times you want to loop ahead of time, such as if you're asking the user to give valid input and want to loop until the input is acceptable, or if you want to go over a data structure without going over the values in a sequence (eg. binary search), a while-loop is the way to go. It gives you more granular control at the expense of usually making your job a bit more involved. while not (num := input("Number: ")).isnumeric(): print("That's not a valid number, try again!") print(f"The number was {num}") Did this help at all?
🌐
Reddit
reddit.com › r/python › what is the most pythonic way to limit while loop iterations?
r/Python on Reddit: What is the most pythonic way to limit while loop iterations?
March 26, 2022 -

Hi all

Whenever I write a while loop, I always want to limit the number of iterations it can run to avoid infinite loops while developing the program, what would the most pythonic way of doing that?

theres obviously the basic

n = 0
while condition and n < 100:
    n += 1

but the n+=1 can easily get lost or commented out when you are working on the code

Ive also tried

def count_generator():
    n = 0
    while True:
        yield n
        n += 1

counter = count_generator()

while condition and next(counter) < 100:

or

class Counter:
    def __init__(self):
        self.count = 0

    def inc(self):
        self.count += 1
        return self.count

counter = Counter()

while condition and counter.inc() < 100:

both of these feel like a lot of boiler plate for what should be a simple task, is there anything better?

🌐
W3Schools
w3schools.com › python › python_while_loops.asp
Python While Loops
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... With the while loop we can execute a set of statements as long as a condition is true.
🌐
Reddit
reddit.com › r/learnpython › understanding the for loop
r/learnpython on Reddit: Understanding the For Loop
October 9, 2020 -

Hey All,

I'm having the hardest time understanding for loops in Python.

Could someone explain what is happening in this example? I see we have a variable v. I somewhat understand that "range" is built into Python. I don't understand the output.

for v in range(3, 10, 3):
    print(v)

Output:

3

6

9

I keep seeing examples online but they lose me every time. Thank you in advance.

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

*Edit Thanks to everyone who replied. My misunderstanding was not knowing what range was fully doing.

range(start, stop, step)

🌐
Reddit
reddit.com › r/learnpython › how do i make my program loop?
r/learnpython on Reddit: How do I make my program loop?
May 31, 2024 -

I started learning python a couple of days ago and decided to make a little text adventure game to practice if, elif, and else stuff. The code might be a little clunky right now, I'm not quite sure, but I'm pretty proud of it. There's several endings, but I'm not sure how to get it to loop back to the start once an ending is reached. Is that possible, and if possible, how would I go about doing it?

I posted the code to GitHub (this is the link Text-Adventure-The-Woods/Text Adventure.py at main · novarowan13/Text-Adventure-The-Woods (github.com) )

I'm also a bit curious on how to loop back to the same prompt if the invalid option is taken, make it so that it doesn't move on until a valid option is picked.

🌐
Reddit
reddit.com › r/learnpython › whats the difference between a while loop and a for loop?
r/learnpython on Reddit: Whats the difference between a while loop and a for loop?
July 15, 2024 -

I want to ask, whats the difference between looping using the while and the for function? I know both of these functions loops through stuff but what exactly is the difference between them? I have trouble understanding so I decide to ask this question on here