Hah, that's tricky. The expression if cont == "n" or "N" does not mean what you think it means. The or operator takes two values and returns True if either evaluates to True. The expression cont == "n" evaluates to False. The expression "N" however, being nonzero, evaluates to True. False or True --> True. Answer from fernly on reddit.com
🌐
Reddit
reddit.com › r/learnpython › yes or no for a while loop?
r/learnpython on Reddit: Yes or No for a While Loop?
October 9, 2023 -

(Solved) I'm trying to ask the user if they want to continue by typing in either Y/y for yes or N/n for no. If i type Y twice it sends me to my print(Thank you for playing). What did I do wrong here?

def dmg ():

import random

damage = random.randint(1,12)

longSword(damage)

def longSword(damage):

cont = input("Would you like to attack? (Type Y or y for yes and N or n for N)")

while cont == "y" or "Y":

print('Your longsword hit for', damage, "damage")

cont = input("Would you like to attack again?")

if cont == "n" or "N":

print('Thank you for playing')

break

dmg ()

🌐
Reddit
reddit.com › r/learnpython › how would i loop and create a yes/no conditional loop
r/learnpython on Reddit: How would I loop and create a yes/no conditional loop
September 30, 2025 -

Hi! I'm making a grade converter which is the code attached above. The whole point of my project is to figure out how to make (I think they're called) while loops. With that said, I'm confused on how to make a conditional statement saying "Continue? Y/N" with Y or yes continuing the program from the users input and N or no would "break" the code. My confusion is WHERE I would put the *while TRUE loop. Does it go BEFORE my main code and THEN I put the yes no question. Furthermore, would my "Continue y/n" question be coded as a boolean? If someone can show me how this should look when integrated with the CURRENT code, I would be so thankful, bc Khan Academy is confusing me...

(PS This isn't for a grade or class assignment, but to learn how this loop stuff works)

print("Letter Grade Converter")

grade = int(input("Enter your grade "))

if grade >= 88:

print("Your letter grade is an A")

elif grade >= 80:

print("Your letter grade is a B")

elif grade >= 67:

print("Your grade is a C")

elif grade >= 60:

print("Your grade is a D")

elif grade < 60:

print ("Your grade is an F")

🌐
Reddit
reddit.com › r/learnpython › using a while loop to ask the user (y/n) ?
r/learnpython on Reddit: Using a while loop to ask the user (Y/N) ?
October 31, 2023 -

So I have a program that calculates compound interest, and now I need to add a question at the end of my program that asks the user if they would like to run the program again, if they answer with Y or y the program will restart to the beginning, if they answer “N” or “n” the program is over. And if they answer with anything other than y or n it should repeat the question until the user finally enters y or n

What I have so far:

I have my entire program in a while loop and was able to get it to reset while Var == Y or y. But I can’t get it to repeat the question if the user answers with let’s say “q” or “618” or “L”. Does anyone know how to do something like this, please let me know… thank you

🌐
Reddit
reddit.com › r › learnpython › comments › 3k58yk › while_loop_help
r/learnpython - while loop help...
September 9, 2015 -

Hello anyone, I'm trying to write a program that asks the user if he/she wants to play a game. The user has the option of only entering 'yes' or 'no' and if it's anything other than that, the program should enter a while loop that asks the user to "please enter a valid answer of either 'yes' or 'no'. So far I have this:

print("would you like to play a game?")
answer = raw_input()

if answer == "yes":
print("Let's play!!")
elif answer == "no":
print("Ok, another day...")
else:
answer = False

But where to put the while loop??

Update: Ok guys, thanks for your help. I got!

print("would you like to play a game?")

answer = None

while answer != 'yes' or answer != 'no':
answer = raw_input("Please enter yes or no: ")

if answer == "yes":
print("Let's play!!")
else:
print("Ok, another day...")

I was also trying write a program that has a definition. So far I have this

def game(answer):
if answer == 'yes':
print("Ok, let's begin!")
elif answer == 'no':
print("Ok, another time then...")
print("Would you like to play a game?")
answer = input()

while True:
if answer != 'yes' or answer != no:
answer = input("Please enter a valid response ")
continue
else:
break
game(answer)

but I don't know what I'm doing wrong in block 5.

🌐
Reddit
reddit.com › r/python › til you can use else with a while loop
r/Python on Reddit: TIL you can use else with a while loop
March 1, 2025 -

Not sure why I’ve never heard about this, but apparently you can use else with a while loop. I’ve always used a separate flag variable

This will execute when the while condition is false but not if you break out of the loop early.

For example:

Using flag

nums = [1, 3, 5, 7, 9]
target = 4
found = False
i = 0

while i < len(nums):
    if nums[i] == target:
        found = True
        print("Found:", target)
        break
    i += 1

if not found:
    print("Not found")

Using else

nums = [1, 3, 5, 7, 9]
target = 4
i = 0

while i < len(nums):
    if nums[i] == target:
        print("Found:", target)
        break
    i += 1
else:
    print("Not found")
🌐
Reddit
reddit.com › r/learnprogramming › while loop in python
r/learnprogramming on Reddit: While loop in Python
January 12, 2020 -

Hi!

Sorry if this question has been answered somewhere, I just couldn't find a thread that would help me solve my problem. This little program is supposed to ask a question and if it gets yes/no answer, then print something. If it doesn't get yes or no, it should ask the question again until the user's input is yes/no. However I get stuck in infinite loop then I get asked "Wrong imput! Answer yes or no please: " - this question repeats even if I answer yes/no.

Thanks for any help!

name = input("Enter your name: ")

age = input("Enter your age: ")

print("Hello " + name + "! You are " + age + " years old, right? ")

answer = input ("Answer yes or no please: ")

while answer != "yes" or answer != "no":

    answer = input ("Wrong imput! Answer yes or no please: ")

if answer == "yes":

    print("Haha, I knew it!")

elif answer == "no":

    print("Liar!")

🌐
Reddit
reddit.com › r/learnprogramming › do people actually use while loops?
r/learnprogramming on Reddit: Do people actually use while loops?
August 15, 2022 -

I personally had some really bad experiences with memory leaks, forgotten stop condition, infinite loops… So I only use ‘for’ loops.

Then I was wondering: do some of you actually use ‘while’ loops ? if so, what are the reasons ?

EDIT : the main goal of the post is to LEARN the main while loop use cases. I know they are used in the industry, please just point out the real-life examples you might have encountered instead of making fun of the naive question.

Find elsewhere
🌐
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/programminglanguages › do we need 'for' and 'while' loop?
r/ProgrammingLanguages on Reddit: Do we need 'for' and 'while' loop?
April 29, 2025 -

Edit: Got the answer I was looking for. People want these keywords because actually having these keywords haven't created as many complications but solve many as they increase the readability.

Also, for anyone saying that all the provided examples (1&3) do the same thing. That's what my point was.


It seems to me that both loops can perform like the other one in any language and there's not much restriction

Yes some languages have special syntax for 'for' loops such as Rust, JS, Python have 'for-in'.

But I wonder, what if a language just has 'loop'

Examples below:

        loop x in (range()/a..b/a..=b) {
        
        }
        
        loop x < y {
        
        }
        
        loop x in iterable {
        
        }

I don't know if people would prefer this more but it seems like the simpler thing to do.

I used to often think whether I should use while, for or do-while and they actually don't have that much performance difference so it just seems they create confusions and don't help beginners.

Thoughts?

🌐
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

🌐
Python Forum
python-forum.io › thread-38568.html
Looping a question until correct feedback is given
October 30, 2022 - I'm writing my first python program as a number guessing game. I am trying to loop a question until a 'yes' or 'no' response is given but am having trouble figuring it out. ''' response = input('Do you want to try a guessing game?: [yes or no]') whi...
🌐
Reddit
reddit.com › r/learnpython › is for and while statement completely interchangeable in python?
r/learnpython on Reddit: Is for and while statement completely interchangeable in Python?
July 12, 2021 -

Is for and while statement completely interchangeable in Python? Are there scenarios where one statement cannot be converted to another?

Top answer
1 of 5
4
They are interchangeable but it would require more variables. The only place I can think of where while loops are better is when you have a counter than doesn’t increment every iteration. An example is if your removing every value in a list that is part of another list such as removing [a, b, c] from [a, g, f, t, b, d, c, v] but every time you .pop(), the lift becomes smaller by one so you don’t need to increment by 1
2 of 5
4
Is a cow and a horse interchangeable? You could ride a cow and milk a horse, I suppose, but that would be confusing and not optimal. For loops are meant for iteration. They are intended to be deterministic; that is, you know at the beginning how many times they will happen. Most often, this is because you want to do something to every member of an iterable structure like a list or a tuple. One of the great things about Python is how easy python makes this to do. In fact, the Python for loop is actually more like the foreach loop that some other languages have. list = ["a", "b", "c", "d"] for item in list: print(item) You can also use a for loop with a range object to make something happen a certain number of times, which is also deterministic. for i in range(10): print(i) You can always force the loop to quit with a break statement, making it non-deterministic, but that will be confusing when you look at the code later. The while loop is intended for use in non-deterministic cases, when you don't know at programming time how often the loop will continue. If I have a loop that should continue until the user gets the input correct, or some other condition is met, the while loop is the best choice. You can make a while loop act like a for loop, like this: i = 0 while i < 4: i += 1 print (i) which is functionally identical to for i in range(4): print(i) There's nothing reall wrong with that, but if you want something to act like a for loop, it's generally better to make it a for loop. One goal of coding is the "principle of least astonishment." When you look over your code after a year, you want to be able to understand what it does.
🌐
Reddit
reddit.com › r/learnpython › understanding while loops.
r/learnpython on Reddit: Understanding While loops.
May 25, 2025 -

I'm using solelearn for learning python, and I just cannot figure out why my while loop isn't working.

I am aware that it's probably an oversight on my behalf.

Any help / explanation would be much appreciated.

For these lines of code I have to make it count down to 0.

(# take the number as input) number = int(input())

(# use a while loop for the countdown) while number > 0: print(number) number = number -1

🌐
Reddit
reddit.com › r/learnpython › how do i restart a while loop after the else is triggered and conditions reset to while loop conditions?
r/learnpython on Reddit: How do I restart a While loop after the else is triggered and conditions reset to While loop conditions?
July 27, 2021 -

I'm still learning how to code in python and I decided to experiment on a number of conditional and loop statements. The program should be simple: Request the user to input a positive integer value and correct their behavior if a string is introduced. If the user types '0' it asks the user if he wants to exit the program and is supposed to exit upon confirming the user's request or is supposed to repeat the input request until the user requests and confirms his request to leave.

Problem is even though I reset the 'i' variable to initial conditions the while loop does not trigger again as expected. I need to find a way to trigger this loop indefinitely upon declining the request to leave but instead the while loop ends after the else is triggered and the program terminates. Where did I go wrong?

Note: The code is properly indented. Reddit just displayed it like that.

#This is the following code:

i = 1
while i != "0":
    try:
        i = input('Enter a positive integer: ')
        a = int(i)
    except:
        a = -1
    if a > 0:
        print(a)
    elif a < 0:
        print("Not a positive integer, don't ruin my program!")
else:
    try:
        a = input("Do you want to exit?\n")
        if a == "yes" or a == "y":
            print("Ok, shutting down now, goodbye!")
            exit()
        elif a == "no" or a == "n":
            print("Well I'm shutting down anyway. Bye!")
            i = 1
        else:
            print("Hey, buddy, you're supposed type 'y' or 'n'.")
            exit()
    except:
        print("Hey, buddy, you're supposed to type 'y' or 'n'")
        exit()

My initial assumption was that if you typed 'no' or 'n' the while loop would trigger again. Now I am ata loss as to how to trigger that same while loop.

Another error: I added a try/except condition in case the user types something that might cause a traceback error but instead it prints two error messages printed out on the final else and except if the user types n or no and still prints one error message from the except condition. From my understanding the except is supposed to trigger in case we get a Python error from the try statement, right?

EDIT: SOLVED, I'M SO HAPPY. MY EXPERIMENT WAS A SUCCESS:

i = 0
ii = 0

def positive_int(): #Requests a positive integer
    global i #references global i inside function
    global ii #references global ii inside function
    while i != "0":
        try: #Checks for any str input instead of numbers
            i = input('Enter a positive integer: ')
            a = int(i)
        except:
            a = -1 #Triggers built-in error message by converting str input into a negative integer instead of crashing the program, thus continuing operation.
        if a > 0:
            print(a) #Shows positive input value
        elif a < 0:
            print("Not a positive integer, don't ruin my program!") #Built-in error message
    else:
        a = input("Do you want to exit (y for yes, n for no)?\n") #Asks for confirmation to exit program
        if a == "yes" or a == "y":
            ii = 1 #Cancels the loop and exits the program with a goodbye message
        elif a == "no" or a == "n":
            i = 0 #Resets the loop, resetting user input to 0
        else:
            print("Hey, buddy, you're supposed type 'y' or 'n'.") #Built-in error message, scolds user for inputting nonsense.
            a = 0 #Asks for confirmation again.

while ii == 0:
    positive_int() #loops user input request
else:
    print("Shutting down now, goodbye!") #terminates loop and exits program upon confirmation of user input
    exit()

🌐
Reddit
reddit.com › r/learnprogramming › while loops in python...simple question!
r/learnprogramming on Reddit: While loops in python...simple question!
October 4, 2011 -

Hey guys, brand new to programming. Literally. Only about a week in. Used this forum to get me started, so thanks for all the resources so far.

I'm using the Jump Start Learn Programming book and it uses python as its into language. Just got to the section regarding while loops. I can't even get the first example to properly run :/ I don't know what the problem is, as far as I can tell my code is identical to the books. I had this problem last week when using a different training material. Seems to always happen when I am trying to create a while loop for text that includes a n input. Here is the code.....

answer = "no"
    while answer == "no":
    answer = input("Are we there yet? ")
print ("We're here!") 

Not sure if it matters but I'm writing the code in IDLE. Here is the error message it spits out: Traceback (most recent call last): File "C:/Python27/vb", line 3, in <module> answer = input("Are we there yet? ") File "<string>", line 1, in <module> NameError: name 'no' is not defined

BTW is there any formatting etiquette for pasting lines of code? Sorry if I'm breaking rediquette, first time poster in this subreddit. Thanks in advance for the help guys!!

edit: formatting

🌐
Reddit
reddit.com › r/learnpython › while vs for?
r/learnpython on Reddit: While vs For?
April 20, 2022 -

I am teaching a group Python and several students are struggling to earn when to use a for loop and when to use a while loop. How do you explain it in a way that will help them understand?

🌐
Nemoquiz
nemoquiz.com › python › python-while-loops
Python While Loops | NemoQuiz
You can use the break keyword to finish a loop. Here is an example: while True: a = input('Continue? (yes or no)') if a == 'no': break print('The infinite loop has been broken.')