Python 3: Can't exit a "while" loop - python

The program asks:
would you like to repeat the execution? (Y/N)
If user enters "Y" or "N", the program starts again or exit, respectively.
If user enters something different from "Y" or "N", the program should print "I can't understand you, bye!"
I defined a function with the operations that I'm interested in. I call this function from a while loop. If user enters "Y" it calls the function, if user enters "N" it prints a message and exit, if user enters another character it prints the error message.
It works OK when I enter "Y" or "N", however it calls the function if I enter any other character such as "Z".
Below is my code. Thank you!
import random
import time
def Intro():
print("some text here")
print("select a cavern (1 รณ 2)")
def juego():
dragon = random.randint(1,2)
cueva = int(input())
print("bla bla")
time.sleep(2)
print("bla bla bla")
time.sleep(2)
print("bla")
time.sleep(2)
if cueva == dragon:
print("you win")
print("start again? (Y/N)")
print()
else:
print("you lose")
print("start again? (Y/N)")
print()
Intro()
juego()
seguir = input()
print()
while seguir == "Y" or "y":
Intro()
juego()
seguir = input()
print()
if seguir == "N" or "n":
print("Thanks for playing")
break
if seguir != "S" and seguir != "s" and seguir != "N" and seguir != "n":
print("I can't understand you, bye!")
break

Your while loop is only working when the user initially inputs a Y. If the user does not input the Y before the while loop, the check evalueates to false so the while loop never gets run. Dont get input before the while loop, set seguir to 'Y' at the begining so you can actually enter it.

You should try like:
if seguir in ["N", "n"]:
print("Thanks for playing")
break
if seguir.lower() == "n":
print("Thanks for playing")
break
want to help~
ref: How to test multiple variables for equality against a single value?

Related

How to display an input only if certain conditions are met in Python

I'm trying to make my code display an extra input if a certain condition is met (in this case, selecting "Y")
This is what I've tried:
if RandomNum != UserGuess:
print("Sorry, you guessed wrong. The number was: ", RandomNum)
KeepGuess = input("Would you like to continue guessing? (Y/N): ").upper()
elif KeepGuess == "Y":
continue
else:
break
When I do this, I get the following error:
elif KeepGuess == "Y":
UnboundLocalError: local variable 'KeepGuess' referenced before assignment
as the error says, you are trying to use a variable that is not existed yet, you can move the elif-else part in the block that KeepGuess is defined:
if RandomNum != UserGuess:
print("Sorry, you guessed wrong. The number was: ", RandomNum)
KeepGuess = input("Would you like to continue guessing? (Y/N): ").upper()
if KeepGuess == "Y":
continue
else:
break
Your current code only creates and assigns the KeepGuess variable when the if statement returns true. You want to move the first elif statement into the first if statement and change it to an if. So it will look like the code below. You will also want to change continue to call what ever function is making the loop. I hope this helps
def Check():
UserGuess = input('Guess Here:')
if RandomNum != UserGuess:
print("Sorry, you guessed wrong. The number was: ", RandomNum)
KeepGuess = input("Would you like to continue guessing? (Y/N):
").upper()
if KeepGuess == "Y":
Check()
else:
print(rest of your code here)

Flowchart getting complicated with while loops in Python

I would appreciate some help with this:
I try to make a form-program of the "Then why worry" philosophy:
I wrote this code, but I can't understand how do I make the while loop repeat itself every time the user doesn't enter "yes" or "no" in both questions.
problem = str(input("Do you have a problem in life? "))
problem = problem.replace(" ", "").lower() #nevermind caps or spaces
while problem:
if problem not in ("yes","no"):
print("Please enter YES or NO")
if problem == "no":
break
if problem == "yes":
something = str(input("Do you have something to do about it? "))
something = something.replace(" ","").lower()
while something:
if something not in ("yes","no"):
print("Please enter YES or NO")
elif:
break
print("Then why worry?")
Your algorithm is linear, there is no loops in there. So, the only place you need a loop is when you try to get correct response from the user. So, I'd propose you to move that into a function and then your example turns into this:
def get_user_input(prompt):
while True:
reply = input(prompt).replace(" ", "").lower()
if reply in ['yes', 'no']:
return reply
print("Please enter YES or NO")
problem_exists = get_user_input("Do you have a problem in life? ")
if problem_exists == 'yes':
action_possible = get_user_input("Do you have something to do about it? ")
print("Then why worry?")
I'd suggest to use while True loops, so you can put the input code once, then with the correct condition and break you're ok
while True:
problem = input("Do you have a problem in life? ").lower().strip()
if problem not in ("yes", "no"):
print("Please enter YES or NO")
continue
if problem == "no":
break
while True:
something = input("Do you have something to do about it? ").lower().strip()
if something not in ("yes", "no"):
print("Please enter YES or NO")
continue
break
break
print("Then why worry?")
Using walrus operator (py>=3.8) that could be done easier
while (problem := input("Do you have a problem in life? ").lower().strip()) not in ("yes", "no"):
pass
if problem == "yes":
while (something := input("Do you have something to do about it? ").lower().strip()) not in ("yes", "no"):
pass
print("Then why worry?")

Control flow - Jump to another loop?

I did not find any duplicates of this question, i understand that Python has no "goto" functionality in itself and how i can make use of "continue" in a loop to get the same effect, but i'm not really sure if it's any recommended method of "jumping back" to another loop for eg? Let me show you an example below
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
pass
# Here i would want to be able to send the user back to the 1st loop if user gives any other input than "yes" or "no"
The only thing i can think of right now that makes any sense (to not have to simply rewrite the whole thing again) is to simply set the first loop to a function and call that from the second loop to get the result i want, this works as i intend it to:
def firstloop():
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
firstloop()
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
firstloop()
But somehow it feels like i'm over complicating something, or is this the "best" way i can go by with something like this? Thanks
You should put the second loop inside the first one (or inside an enclosing while for both). GOTOs are never needed, See here: https://en.wikipedia.org/wiki/Structured_programming

Python: Depending on IF statement output, execute different code outside of itself

If my_input == "n" I want to my program to loop again, which works fine.
But if my else statement is True I dont want it to run the whole program again and just "start" at the my_input variable.
How can I achieve this?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
I misunderstood your question, I would probably restructure your code a bit, so you get rid of your while loops and use recursive function calling to go back when you need to,
something like the below
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
Add another loop that doesn't terminate until user enters acceptable input.
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
while True:
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
break
else:
print("Invalid input, try again.")
if my_input == 'y':
break
name_user_validation()
Edit: The program terminates only when my_input = y.

Python string input loop

I'm looking to create a python function which would iterate through a string one element at a time based on whatever the user inputs.
So let's say the list is [hello, jello, mello]. The program will print out the string then ask the user "Do you want me to read?", then "y" it'll print the first element then loop through the string until the user inputs "n", then the loop will stop.
Thanks!
This should work:
l = ["Hello", "Jello", "Mello"]
for element in l:
while True:
answer = input("Do you want to read (y/n)")
if answer.lower() == "y" or answer.lower() == "n":
break
else:
print("Invalid input")
if answer.lower() == "y":
print(element)
elif answer.lower() == "n":
break
Hope this helps!
from collections import cycle
def print_entries_forever(list_str):
for entry in cycle(list_str):
answer = input('Do you want me to read [y/n]? ').lower()
if answer.startswith('y'):
print(entry)
elif answer.startswith('n'):
return
print_entries_forever(['Hello', 'Jello', 'Mello'])
EDIT: Loop now cycles forever until user enters 'n'.

Categories