How to stop a infinite while loop - python

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.

Related

Function Remain Without Looping (Recursion Error)

This is difficult without just laying the function out first so here we go. FYI, this is essentially a medical diagnostic program I'm making.
def patient_discussion(patient, q_count): #q_count keeps track of the number of questions asked.
response_list = ['n', 'menu']
if q_count == 0:
question = input('''What would you like to ask the patient? You can ask them for/about:
N = Their name.
Or type "main" to go back to the main screen. ''')
else:
question = ('What would you like to ask the patient? ') #This is to avoid spitting out a huge block of text. I think it's important the first time but not the rest.
if question.lower() == "n":
print("My name is "+ patient['Name'] + ". ")
q_count += 1
print()
patient_discussion(patient, q_count) #This is to loop back in case the player wants to ask additional questions.
if question.lower() == "main": #To bring the patient back to the main screen if they want.
menu(patient)
if question.lower() not in response_list: #To prevent an error.
print("What the heck are you even asking me, doc?")
print()
q_count += 1
patient_discussion(patient, q_count)
When I do this, there's a recursively loop error.
RecursionError: maximum recursion depth exceeded while calling a Python object
And I know what's happening. The original function is called as
patient_discussion(patient, 0)
And when I ask a question, the q_count goes up to 1 then 2 and so on and so forth. I just don't know why it's even looping to an incorrect answer since "n" would be in the above list.
I'd appreciate any help.

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.

Input/If statement - correct way of writing

I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.
As I am just starting out, I was wondering which way is more preferable to write the program,
The solution is:
# Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")
# If they want to proceed
if should_proceed.lower() == "y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining -= num_tickets
# Otherwise...
else:
# Thank them by name
print("Thank you anyways, {}!".format(name))
Whereas, I have put:
# Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()
# If they want to proceed
if proceed == "Y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining = tickets_remaining - ticket_request
print(tickets_remaining)
# Otherwise...
elif proceed == "N":
# Thank them by name
print("Thank you for your time, {}".format(customer_name))
Was it incorrect to call upper() on the input?
Is there any other errors I have done?
Many thanks,
Was it incorrect to call upper() on the input?
No, this is a perfectly fine way to allow case-insensitive input. Their solution shows an alternative that works just as well.
Both ways are fine with one caveat. Because you are specifically checking for both Y and N, your way is probably better in that case since you would otherwise have to call upper() twice:
proceed = input("Would you like to proceed? Y/N ")
if proceed.upper() == "Y":
doSomething()
elif proceed.upper() == "N":
doSomethingElse()
On that enhanced checking, your code is slightly different in that it does nothing if the input is neither Y nor N (the other code treats anything that's not y as n). In that case, you're probably wise to ensure it is one of those values, with something like:
proceed = ""
while proceed != "Y" and proceed != "N":
proceed = input("Would you like to proceed (Y/N)? ").upper()

Python While loop keeps repeating

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.

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.")

Categories

Resources