Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
When I press "y" in the first question the loop just keeps going instead of stopping.
Done = True
while Done:
quit = str(raw_input ("Do you want to quit? "))
if quit == 'y' :
Done=False;
attack = str(raw_input("Does your elf attack the dragon? "))
if attack=='y':
print ("Bad choice, you died.")
done=False;
print "Loop stopped"
I am using Python 2.7.
You may want to use a break, this is used to stop a loop:
while True:
quit = str(raw_input ("Do you want to quit? "))
if quit == 'y' :
break # Add this
...
Quoting Python docs:
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
Edit:
You could try using an infinite loop (while True) and when you want to exit it, just check for a condition and use a break statement.
Python is case-sensitive. You need to make sure Done is always capitalized or not:
>>> Done = True
>>> while Done:
quit = str(raw_input ("Do you want to quit? "))
if quit == 'y' :
Done = False
attack = str(raw_input("Does your elf attack the dragon? "))
if attack=='y':
print("Bad choice, you died.")
Done = False
print("Loop stopped")
As Makoto has pointed out, in Python 2.x, the parentheses in the print statements above are a grouping mechanism. But in Python 3.x, print constitutes a function and requires parentheses. The above code will work in both versions of Python.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
When I run this easy program and want to exit it, I need to type exit 2 times (at line 7).
def registration():
def username_registration():
entering_username = True
while entering_username:
print("Type exit to leave the registration.")
usernam_from_registration = input("Enter username: ")
if usernam_from_registration == "exit":
break
lenght_usernam_from_registration = len(usernam_from_registration)
if lenght_usernam_from_registration > 15:
print("too long")
else:
return usernam_from_registration
username_registration()
print(username_registration())
registration()
Why is this and how can I make it so I only need to write it one time?
This is because you are calling the username_registration() function twice.
username_registration()
print(username_registration())
The first time you call it, nothing happens because you are not doing anything with the result.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I am making a text based game. I am moving along, but I am stumped on how to make specific choices bring you back to where you need to make the choice. Currently, the current plan I am doing is to make the right answers bring you to the rest of the game, while the incorrect questions bring you nowhere, and you have to restart the program entirely, but it isn't very fun to have to slog through the parts I have already done every single time I get a wrong choice.
ruintalk = input ()
if ruintalk == '1':
print ('"Rude!" the old man shouts, "I knew you were just like the rest of them." The old man storms out as fast as his frail legs can take him. You never hear from him again and later die of lumbago and are buried in a paupers grave. Dont insult the old man or ask stupid questions. Hes kind of a dick so just roll with it and restart the game.')
What command should I put to bring me back to input()?
Loops are what can you help you with that. "while" loops particularly in this case. "while" loops keep iterating through a block of code till the condition is true.
Here is an example demonstrating their use -
while True:
ruintalk = input()
if ruintalk == correct_answer:
break # This will break the iteration
This block of code will keep iterating until break statement is called. Alternatively, what you can do is have a variable set as True and set it to false once the correct answer is entered. Here is an example showing this -
run = True
while run:
ruintalk = input()
if ruintalk == correct_answer:
run = False
If I understand what you're trying to build, you might want to make your input a function to be called. You can then build loops for different scenarios and your input will happen in a statement:
def userInput():
r = input()
r = r.lower() #I like doing this to simplify how I handle user input in the code
return(r)
while sceneComplete is False:
print("Something to setup the scene. What do you want to do, user??? (X/Y/Z)?")
action = userInput()
if action == "x":
do the x thing
elif action == "y":
do the y thing
elif action == "z":
sceneComplete = True
else:
print("You broke the rules and an ogre kills you ....")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am a beginner learning Python and wrote the following codes. To control the loop flow I tried using a variable "test", but the loop never stopped. Appreciate if any thoughts.
test=False
while test==False:
a=input("Please enter an even number to make test True: ")
if int(a)%2==0:
test==True
print("test is now True")
else:
print("Please try again!")
test=False
while test is False:
a=input("Please enter an even number to make test True: ")
if int(a) %2 == 0:
test = True
print("test is now True")
else:
print("Please try again!")
Fixed the test == true, should've been test = true :) have fun learning
heres the right code:
test=False
while test==False:
a=input("Please enter an even number to make test True: ")
if int(a)%2==0:
test=True
print("test is now True")
else:
print("Please try again!")
here's what you did wrong:
in the 5th line test==True the == checks if that's what the variable true stores, it doesn't set it; so this can be simply fixed by test=True
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have created a function named user_choice() using Jupyter Notebook. This function is expecting an valid integer input from the user and prints the same. If a user any input other than integer then it should display an error message like " Sorry that is not a digit!" and it will again ask the user to enter valid input.
Below is my code for the function user_choice()
def user_choice():
choice = "WRONG"
while choice.isdigit() == False:
choice = input("Enter a digit(0-10): ")
if choice.isdigit == False:
print("Sorry that is not a digit!")
return(int(choice))
On calling the above function and entering non integer value, It is not displaying the message "Sorry that is not a digit!"
Enter a digit(0-10): ten
Enter a digit(0-10):
Looks like you just forget brackets after .isdigit method in if statement.
You need to use recursive call
def user_choice(choice="WRONG"):
if choice.isdigit() == False:
choice = raw_input("Enter a digit(0-10): ") #use input for higher python version, mine is 2.7 hence used raw_input
if choice.isdigit() == False:
print("Sorry that is not a digit!")
user_choice(choice)
else:
print("Captured:"+choice)
return(int(choice))
A shorter version:
def user_choice(choice="WRONG"):
if choice.isdigit() == False:
choice = raw_input("Input must be a digit(0-10): ") #use input for higher python version, mine is 2.7 hence used raw_input
user_choice(choice)
else:
print("Captured:"+choice)
return(int(choice))
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Python Question: i need to run a program that asks for a password but if the wrong answer is input three times the user is thrown out of the program i can run it in a while loop but cant get it to quit if the wrong password is entered.
Thanks for your help
Adding an approximation of how I'd do it, in the absence of an example containing the problem. else on a for loop will only execute if you did not break out of the loop. Since you know the max number of times to run the loop is 3 you can just use a for loop instead of a while loop. break will still break you out early.
for _ in range(3):
if raw_input("Password:") == valid_passwd: # really should compare hashed values (as I shouldnt have passwords stored in the clear
print "you guessed correctly"
break
print "you guessed poorly"
else:
print "you have failed too many times, goodbye"
sys.exit(1)
# continue on your merry (they got the right password)
How about sys.exit()
>>> import sys
>>> guess = False
>>> if guess:
... pass
... else:
... sys.exit()
http://docs.python.org/3/library/sys.html