This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Python newbie here so sorry for what I'm sure is a stupid question, but I can't seem to solve the following challenge in a tutorial that is asking me to use a while loop to check for valid user input.
(using Python2.7)
Here's my code, but it's not working properly:
choice = raw_input('Enjoying the course? (y/n)')
student_surveyPromptOn = True
while student_surveyPromptOn:
if choice != raw_input('Enjoying the course? (y/n)'):
print("Sorry, I didn't catch that. Enter again: ")
else:
student_surveyPromptOn = False
The above prints out to the console:
Enjoying the course? (y/n) y
Enjoying the course? (y/n) n
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) x
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n)
Which obviously isn't correct — the loop should end when the user enters either 'y' or 'n' but I'm not sure how to do this. What am I doing wrong here?
Note: the challenge requires me to use both the != operator and the loop_condition
You can use the condition
while choice not in ('y', 'n'):
choice = raw_input('Enjoying the course? (y/n)')
if not choice:
print("Sorry, I didn't catch that. Enter again: ")
A shorter solution
while raw_input("Enjoying the course? (y/n) ") not in ('y', 'n'):
print("Sorry, I didn't catch that. Enter again:")
What your code is doing wrong
With regard to your code, you can add some print as follow:
choice = raw_input("Enjoying the course? (y/n) ")
print("choice = " + choice)
student_surveyPromptOn = True
while student_surveyPromptOn:
input = raw_input("Enjoying the course? (y/n) ")
print("input = " + input)
if choice != input:
print("Sorry, I didn't catch that. Enter again:")
else:
student_surveyPromptOn = False
The above prints out:
Enjoying the course? (y/n) y
choice = y
Enjoying the course? (y/n) n
choice = y
input = n
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) x
choice = y
input = x
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n)
As you can see, there is a first step in your code where the question appears and your answer initializes the value of choice. This is what you are doing wrong.
A solution with != and loop_condition
If you have to use both the != operator and the loop_condition then you should code:
student_surveyPromptOn = True
while student_surveyPromptOn:
choice = raw_input("Enjoying the course? (y/n) ")
if choice != 'y' and choice != 'n':
print("Sorry, I didn't catch that. Enter again:")
else:
student_surveyPromptOn = False
However, it seems to me that both Cyber's solution and my shorter solution are more elegant (i.e. more pythonic).
The very simple solution for this is to initialize some variable at the before the loop kicks in:
choice=''
#This means that choice is False now
while not choice:
choice=input("Enjoying the course? (y/n)")
if choice in ("yn")
#any set of instructions
else:
print("Sorry, I didn't catch that. Enter again: ")
choice=""
What this while conditional statement means is that as long as choice variable is false--doesn't have any value means choice=''-- ,then proceeds #with the loop
If the choice have any value then proceed with enters the loop body and check
the value for specific input, if the input doesn't fulfill the required value
then reset the choice variable to False value again to continue prompts user
until a correct input is supplied
Related
i am preparing a function to user to guess a random number generated by computer.
The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number.
In the end the, the user should be asked if he wants to play again or not.
Everything is working excepts this last part, because i can't break the loop to stop the game.
Here's my code:
#random number guessing game
import random
def generate_random (min,max):
return random.randint (min,max)
#generate_random (1,100)
star_range=1
end_range=100
#targetnumber=generate_random(start_range,end_range)
#print (targetnumber)
def main():
targetnumber=generate_random(star_range,end_range)
number_of_guesses =0 #guarda o numero de tentativas do jogador
print ("Guess a number between 0 e 100.\n")
while True:
number_of_guesses +=1
guess = int(input("Guess #" + str(number_of_guesses) + ": "))
if guess > targetnumber:
print("\t Too High, try again.")
elif guess < targetnumber:
print ("\t Too low, try aain")
else:
print ("\t Correct")
print ("\t Congratulations. you got it in",number_of_guesses,"guesses.")
break
playagain=input("\n whould you like to play again? (y/n): ").lower()
while playagain != "y" or playagain != "n":
print ("Please print y to continue or n to exit")
playagain=input("\n whould you like to play again? (y/n): ").lower()
if playagain == "y":
continue
else:
break
My final output is always this one:
whould you like to play again? (y/n): n
Please print y to continue or n to exit
whould you like to play again? (y/n):
Can you please help me, letting me know what i am doing wrong?
Thank you very much
The condition evaluation is always True, hence you get into the loop again.
while playagain not in ['y', 'n']:
...
would satisfy your input check
Also, your continue/break condition is only evaluated if the while loop condition is met (i.e., the input was not correct)
It looks like you are continuing the second "while" loop and not moving back to your "game" code when you check the equality of the string "y" as the input, thus the question gets asked again. Instead, you should try refactoring the loops so that your game loop is nested inside the retry loop.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
"""
GuessNumber.py - This program allows a user to guess a number
between 1 and 10.
Input: User guesses numbers until they get it right.
Output: Tells users if they are right or wrong.
"""
import random
number = random.randint(1, 10)
# Prime the loop.
keepGoing = input("Do you want to guess a number? Enter Y or N ")
# Validate input.
# Enter loop if they want to play.
while keepGoing == "Y":
# Get user's guess.
stringNumber = input("I'm thinking of a number. .\n Try to guess by entering a number between 1 and 10 ")
userNumber = int(stringNumber)
# Validate input.
# Test to see if the user guessed correctly.
if userNumber == number:
keepGoing = "N"
print("You are a genius. That's correct!")
else:
keepGoing = input("That's not correct. Do you want to guess again? Enter Y or N ")
# Validate input.
If the user guesses correctly, the program congratulates the user, and then the loop that controls guessing numbers exits; otherwise the program asks the user if he or she wants to guess again. If the user enters "Y", he or she can guess again. If the user enters "N", the loop exits. You can see that the "Y" or "N" is the sentinel value that controls the loop. I need to ass a code that validates "y" and "n"
keepGoing.upper() == "Y" would check lower and upper case inputs.
You shouldn't need to validate N/n
import random
number=random.randint(1,10)
keepGoing=raw_input("DO you want to guess a number:\n ")
keepGoing=keepGoing[0].upper()
while keepGoing=='Y':
stringNumber=int(raw_input("I'm thinking of a number. .\n Try to guess by entering a number between 1 and 10:\n "))
if (stringNumber==number):
print("You are a genius. That's correct!")
break
else:
keepGoing=raw_input("DO you want to guess a number")
keepGoing=keepGoing[0].upper()
I'm new to coding (Python) and am trying to learn loops. I have had some difficulty with a little complex while and for loops. Here I'm trying to create a function and use the while loop. Could I get some ideas on how to fix this code and get some explaintion on what i did wrong?
What I'm trying to achieve with this code is that I have some numbers stored in a list which are secret. And until the user doesn't type in one of these numbers the loop will continue asking. As soon as the user types in one of the numbers, the loop will exit preferibly without using exit() from sys.
def hell_hole():
print("You have just fallen through the hell hole.")
print("You must guess the right number to stop falling otherwise this program will keep repeating.")
print("The right numbers are between 1 - 10 ")
password = [4,9,8]
while True:
typed_in = input("What is the passing code?\n> ")
if typed_in != password:
print("Wrong, try again!")
elif typed_in == password:
print("Well done! You have stopped falling.")
else:
print("Say what?")
I know that this problem can be solved if i changed the if-statment to this:
while True:
typed_in = input("\nWhat is the passing code?\n> ")
if "4" in typed_in or "8" in typed_in or "9" in typed_in:
print("Well done! You have stopped falling.")
exit()
else:
print("Wrong, try again!")
But I want to try to fix the inital code if possible.
You will find below a working version of your code!
As it war already posted, if you want to check if the number entered by the user is IN the list of passwords, you can use the keyword in to do that. Furthermore, as the passwords are integer, you need to convert the input to this type.
In order to exit the while loop, you can use break, which allows you to exit the more nested loop!
Hope it helps!
def hell_hole():
print("You have just fallen through the hell hole.")
print("You must guess the right number to stop falling otherwise this program will keep repeating.")
print("The right numbers are between 1 - 10 ")
password = [4,9,8]
while True:
typed_in = int(input("What is the passing code?\n> "))
if typed_in in password:
print("Well done! You have stopped falling.")
break
else:
print("Wrong, try again!")
You can use in statement:
password = ['4','9','8']
while True:
typed_in = input("\nWhat is the passing code?\n> ")
if typed_in in password:
print("Well done! You have stopped falling.")
break
else:
print("Wrong, try again!")
Instead of sys.exit() you can use either break that will break your loop (here the while loop) or return that will return from your function.
Note that you can return a value from your function to use it out of it by using return yourValue but in your case it's not useful.
Also, an other useful control flow keyword is continue which allow you to skip an iteration of your loop. All those keywords work for both while and for loops.
To make your if statement better, i think you should either check if the password is one of the values you want it to be :
if typed_in in ["4","8","9"]:
or check if one of those values are in the inputted string, just as you seem to do :
if any(x in typed_in for x in ["4", "8", "9"]):
Cast the user input to an int, since you're comparing it to an array of int
Use in and not in to check whether the entered number is in password
Use break instead of exit(). break will simply exit the while loop.
Working implementation:
while True:
typed_in = int(input("What is the passing code?\n> "))
if typed_in not in password:
print("Wrong, try again!")
elif typed_in in password:
print("Well done! You have stopped falling.")
break
else:
print("Say what?")
Demo: https://repl.it/#glhr/55450907
note: you are trying to compare input (string) with whole list:
if typed_in != password
instead of that, check if input is in the list
Fastest way to check if a value exist in a list:
if typed_in in password:
Also in your list (password = [4,9,8] )you have integers, input() is returning string
because of that you need to convert input into integer:
int(input("What is the passing code?\n> "))
The return statement can be used as a kind of control flow. By putting one (or more) return statements in a function the return statement allows you to terminate the execution of a function
password = [4,9,8] # List of numbers
while True:
typed_in = int(input("What is the passing code?\n> "))
if typed_in not in password: # Check if input is IN the list
print("Wrong, try again!")
elif typed_in in password: # Check if input is NOT in the list
print("Well done! You have stopped falling.")
return # Exit function
else:
print("Say what?")
This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 4 years ago.
Could someone please help on how to prompt users to exit, and if they say no, to go back and rerun the program? I'm having an absolute head ache with it and the internet hasn't helped.
This is my code:
print("Hello, this program will ask for two numbers, then show the product
of those numbers that many times")
value = input("Please enter number")
value = int(value)
value2 = input("Please enter a second number")
value2 = int(value2)
for i in range(value*value2):
print(value*value2)
while True:
answer = input("Do you wih to exit? Enter Yes or No:")
if answer in ('No', 'Yes'):
break
print ("Invalid input.")
if answer == 'No':
continue
else:
print ("Goodbye")
break
It's just multiplication then displaying the sum as many times as itself, but I can't figure out how to prompt users to exit, then run through the program again if they say no. I've heard of putting the entire code in a loop, and I've tried, to no avail. Could I please get some help?
Based on the answer as written, but without writing a function:
The key here is that you need to loop until the user inputs 'yes'. Your while loop will never be false, so you'll prompt forever. Here's another solution (though #Ricky Kim has a much more pythonic answer)
answer=""
while answer!= "yes":
print("Hello, this program will ask for two numbers, then show the product \
of those numbers that many times")
value = input("Please enter number")
value = int(value)
value2 = input("Please enter a second number")
value2 = int(value2)
for i in range(value*value2):
print(value*value2)
#use lower so that the user can enter "Yes" or "yes"
answer = str.lower(input("Do you wih to exit? Enter Yes or No:"))
print ("Goodbye")
You can make it as a recursive function and do a loop when the user answers No.
For example:
def ask():
print("Hello, this program will ask for two numbers, then show the product of those numbers that many times")
value = input("Please enter number")
value = int(value)
value2 = input("Please enter a second number")
value2 = int(value2)
for i in range(value * value2):
print(value * value2)
answer = input("Do you wih to exit? Enter Yes or No:")
if answer not in ('No', 'Yes'):
print("Invalid input.")
if answer == 'No':
ask()
else:
print("Goodbye")
ask()
After 4th line, even if u type something else other than yes, it still prints okay?
x = input("Enter any number of your choice: ")
print("the number you picked is", x)
yes = x
input(" right? : ")
if yes:
print("ok")
else:
print("you liar")
Unless you don't enter anything when you prompt for this:
x = input("Enter any number of your choice: ")
if yes: # it's always going to be true
Also this is not doing anything:
input(" right? : ")
you need to assign it to a variable
I think what you want is this:
sure = input(" right? : ")
if sure == 'yes':
You may want to use isnumeric() in case you want to check for a number.
Some documentation on isnumeric() is located at http://www.tutorialspoint.com/python/string_isnumeric.htm
At the moment, you are basically just checking the existence of the variable yes.
BTW: The output for checking up on the number can be rewritten to a formatted statement as follows:
print("The number you picked is {:d} right?".format(x))
Checking, if the user answers with a "yes", can be done easily as well:
yes = input("The number you picked is {:d} right?".format(x))
if (yes == "yes"):
print("ok")
else:
print("you liar")
In case of python2.x you should use raw_input() instead of input(), which is fine for python3.
You want to check what the user is saying for the "Right?" prompt:
x = input("Enter any number of your choice: ")
print("the number you picked is", x)
yes = input(" right? : ") # capture the user input
if yes == "yes": # check if the user said yes
print("ok")
else:
print("you liar")