Python While loop keeps repeating - python

I am trying to use this program I created and I want the program not to repeat the option a lot of times here is the program:
# A Program to show how to use a menu
menu=int(input("What would you like? \n\
1. A compliment \n\
2. An insult \n\
3. A proverb \n"))
y=True
while y==True:
if menu==1: #compliment
print ("You look nice today")
elif menu==2: #insult
print("You smell")
elif menu==3: #proverb
print("A bird in the hand is worth two in the bush!")
else:
y==False
print("Invalid option")
break
What happens is that when I type in the option for example 2 the program repeats
You smell
You smell
You smell
You smell
You smell
infinite times.

You have 2 issues. As #Arrjun Ram mentioned you have y==False when you need y=False
The other issue you have is that your call to input is outside the while loop. This means the value of menu will never change. You need to move it to the inside of the while loop.
You might also add an option, say 4, to exit the loop.

Your while loop never ends. You have a break under your final 'else', but you're assuming that your variable menu will actually be modified. You shouldn't be looping on the response, but instead overall as such:
y=True
while y==True:
menu=int(input("What would you like? \n\
1. A compliment \n\
2. An insult \n\
3. A proverb \n"))
if menu==1: #compliment
print ("You look nice today")
elif menu==2: #insult
print("You smell")
elif menu==3: #proverb
print("A bird in the hand is worth two in the bush!")
else:
print("Invalid option ")
y = False
The above will run until an invalid option is entered and then the loop will break. Your original code would never break since y can never be modified. Your y==False is a comparison operation, NOT an assignment operation. However, that STILL would never be hit, because you're not asking for additional input within your loop so it would remain TRUE forever.

Related

Breaking out of a loop or continuing it under certain conditions (Python)

I'm a little new to Python so I apologise in advance if this is a really simple question but I have been trying to wrap my mind around this problem for a while now.
Simply put, my code is to prompt the user if they have written down a couple of values correctly, If they have I want the loop to continue so the values can be saved to a database. If they have not I would like the code to loop back to the top of the while loop so they can re-enter the values.
For some reason when I enter 'no' It goes through the loop regardless, how may I fix this?
Here's the code below:
while True:
clear()
print("\nPlease input the required data.\n")
in_name = input('Name: ')
in_email = input('Email: ')
in_address = input('Address: ')
clear()
print("\nDoes this look correct?\n")
print("#--START--#\n")
print("Name: " + in_name)
print("Email: " + in_email)
print("Address " + in_address)
print("\n#---END---#\n")
validate == input(">>> ")
if validate == "no":
continue
elif validate == "yes":
print("/nAttempting to copy to the database...")
cursor.execute("""
INSERT INTO contacts(name, email, address)
VALUES (?,?,?)
""", (in_name, in_email, in_address))
conn.commit ()
print ( 'Data entered successfully.\n' )
break
(I should note that this write program is part of a larger program, the loop is nested within another loop that acts as the main menu, perhaps that may help.)
the keyword continue will take you back to the next iteration without finishing the current one, example.
for i in range(5):
if i == 2:
continue
print(i * 5)
This means that when i is 2 it wont print(i=2 * 5), instead it will go up to start the next loop where i=3. The output will be
0
5
15
20
If you use break, it will just completely stop and exit out of the iteration once it reaches this keyword.
I think you're looking for the keyword pass.
'while True:' will always be True, meaning the loop will go on forever. I believe that you'll need to break out of the loop for it to stop. Based on Jorge Alvarez's answer, even changing 'continue' to 'pass' will allow the loop to go forever.
If I understand correctly, you'll need to change the initial 'while True:' statement to test whether validate equals 'no' or 'yes'.

Variable not define newbie in Python

I made a menu to play a game in python. (Please See Below). However, I can t use my lists when I call setup_game or init_trigger. I tried to put them into the while and to also add a variable play so I can avoid the user to press 2 if he never played before. my issues are the following:
Why setup_game(possible_answers, female_charactere, male_charactere) or init_trigger(possible_answers, charactere_attributes) does not work if I put the list out of the while?
why is play not defined?
Please also give me feedback on the code itself, I am a newbie and I want to improve. Thank you!
### create the menu
def menu():
print (30 * "-" , "MENU" , 30 * "-")
print ("1. Replay")
print ("2. Back to my first choice")
print ("3. Exit")
print (67 * "-")
## setup number of time player try the game
play=0
## lists needed to run setup_game and init_trigger
possible_answers= ["female","Female","F","girl","answer","Answer","a","yes","y","Yes","Y","kitchen","Kitchen","K","k","1","Leave","leave"]
female_charactere= ["boy","girl","he","his","him","prince"]
male_charactere= ["girl","boy","she","her","her","princess"]
loop=True
while loop: ## While loop which will keep going until loop = False
menu() ## Displays menu
choice = int(input("Enter your choice [1-3]: "))
if choice==1:
print ("Your story is about to start")
play=play+1 ##count number of time user play
setup_game(possible_answers, female_charactere, male_charactere) ## launch game
elif (choice==2 and play>=1):
print ("Your are back to your first choice")
play=play+1 ##count number of time user play
init_trigger(possible_answers, charactere_attributes) ##lauch game at first choice
elif (choice==2 and play==0):
print ("You have not played yet, you are starting a new story")
setup_game()
elif choice==3:
print("Thank you for playing!")
loop=False # This will make the while loop to end as not value of loop is set to False
else:
print("Thank you for playing!")
break
Why setup_game(possible_answers, female_charactere, male_charactere)
or init_trigger(possible_answers, charactere_attributes) does not work
if I put the list out of the while?
Here you're calling 2 functions you've yet to create. Unless you have more code that you did not share. Your app has no idea what to do with start_game() or init_trigger().
why is play not defined?
Python requires proper indentation, when you step into something like a function, loop, if statement, etc, you have to indent the code that belongs to it.
In your case, you've indented play = 0 under the menu() function. Because of this, play only exists in the scope of menu (). If you align play = 0 left, that warning will disappear.

In this very basic code i can't figure out what's the sytax error here in line 6 is (python)

myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")

How to stop a infinite while loop

I am writing this simple game for an assignment in my class. I am trying to make it so that once the user enters “yes”, it stops asking them if they would like to proceed to the Kanto region. But if they enter no, it loops them back to the beginning telling them that they are first proceeding to the Kanto region.
Edit: How would I make it so that if the users enters yes, it stops the loop and if he enters no, it continues the loop?
while gender=='boy' or gender=='Boy':
#REGION KANTO
print("We will first proceed to the Kanto Region.")
print("You are currently facing the Kanto Region Pokemon Master, John!")
#ATTACK
attack=input("Would you like to use cut and hurt his Pokemon?")
if attack=='yes' or attack=='Yes':
print(starterP,"used cut! Foe Pokemon has fainted!")
print("You will advance to the next region!")
print("=====================================================")
if attack=='no' or attack=='No':
print(starterP,"got attacked!",starterP,"has fainted!")
print("Game over!")
print("=====================================================")
Use break to exit from a while loop:
>>> while True:
... x+=1
... if x == 100:
... print x
... break
...
100
>>>
However, your question is kind of unclear. Please leave a comment if my question is unsatisfactory.

(Python) For loop syntax - execute for only one item?

Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.

Categories

Resources