This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
Question1 = input("We will start off simple, what is your name?")
if len(Question1) > 0 and Question1.isalpha(): #checks if the user input contains characters and is in the alphabet, not numbers.
Question2 = input("Ah! Lovely name, %s. Not surprised you get all the women, or is it men?" % Question1)
if Question2.lower() in m: #checks if the user input is in the variable m
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
elif Question2.lower() in w: # checks if the user input is in the variable w
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
else: #if neither of the statements are true (incorrect answer)
print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")
else:
print ("Come on, enter your accurate information before proceeding! Restart me!") #if the first question is entered wrong (not a name)
Question3 = input("Now I know your name and what gender attracts you. One more question and I will know everything about you... Shall we continue?")
In order to get the right answer, I will first tell you what happens when I run it:
There are several scenarios but I will walk you through 2. When I run the program I am first asked what my name is, I can enter anything here that is alphabetic, then it asks me if I like men or woman, weird I know but it's a project I am working on, if I were to say 'men' or 'women' the program runs perfectly, but if I were to enter say... 'dogs' it would follow the else statement print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!") but then it continues the code and goes to the last line shown above "Now I know your name and what gender attract you...... blah blah". What I am trying to do is have it restart the script if you were to enter anything other than 'men' or 'women'.
I was told that a while statement would work, but I would need an explanation as to why and how... I'm new to Python in a sense.
That's what loops are for.
while True:
# your input and all that here
if answer == "man" or answer == "woman":
# do what you want if the answer is correct
break # this is important, as it breaks the infinite `while True` loop
else:
# do whatever you want to do here :)
continue
If you want the script to repeat indefinitely, you can simply wrap everything in a while loop like so:
while True:
# Do yo your logic here.
# Break out when a condition is met.
If you want to be more savvy with it you can use a method and have the method call itself over and over until it's done.
def ask_questions():
# Do your logic here
if INPUT_NOT_VALID:
ask_questions()
else:
# Continue on.
Also, search on this site for you text because I've seen about five or six questions all involving this programming scenario which means it has to be a common problem from a programming class (one I'm assuming you are in). If that's the case discuss with classmates and try to stimulate each other to find the solution instead of just posting online for an answer.
Related
I know that the question is quite ambiguous, so I'll expand on my problem. I have written a short thingy over here as practice since I just started learning python and am sort of a newbie.
In my code, I ask the user how many apples they have and if they would like to eat it. If they keep saying "Y" until the amount of apples is 0 (#mention 1 in the screenshot), I want my code to redirect to the #redirect 1 part, instead of writing the entire code from #redirect 1 again. I know that I could just rewrite it, however, I can't for the next part. If there are no apples, I ask the user if they want to buy them and the amount.
Then I would like to redirect the code back to #redirect 2 so that the code plays out again. I have read previous questions and understand that a 'goto' doesn't exist as it is unstructured, however, I have no idea how else I would write my code. Sorry for the dumb question, but as I said I am new to this.
Sounds like you need function definition. Something like.
def dostuff():
print "doing stuff"
num = 0
num = 0
while true:
num =+ 1
if num == 5:
dostuff()
else:
pass
This should print doing stuff once every 5 loops
I have done little text game and and all info of this try expect thing is some professional language what i do not understand. I am just started to studying Python so this is not easy for me.
I have lot of inputs in my game, example answer yes or no. If player writes something else, game stop working and error comes. I must do something with this. How can i use try except? Can you tell me it simply.
Piece of my game:
print('Hello you! Welcome to the Ghetto! What is first name?')
first_name=input()
print('Hello',first_name+'! Now tell me your last name also!')
last_name=input()
print('You are my bailout',first_name,last_name+'! I really need your help here. I lost my wallet last night when i was drunk.')
print('The problem is i dont wanna go alone there to get it back cause this place is so dangerous. Can you help me? Answer "YES" or "NO"')
lista1 = ['yes','y']
lista2 = ['no','n']
answer1=input().lower()
if answer1 in lista2:
print('If you are not interested to help me with this problem, go away from here and never come back!!')
print('*** Game end ***')
if answer1 in lista1:
print('That is awesome man! You can see that big house huh? There is three apartments and my wallet is in one of them.')
print('But you have to be god damn careful there you know, these areas is not safe to move especially you are alone. So lets go my friend')
Is there any chance to get error name input? Is there some letter or character what Python does not understand?
And if you answer something else than yes or no, how can i tell to python with try except to give question again? I hope you understand. And sorry for so long post.
If something is causing an error, it's after the code you've shown... Using input() alone should have no reason to try-except it because anything typed is always accepted as a string.
If you want to repeat input, you'll need a loop
while True:
answer1=input().lower()
if answer1 in ["yes", "y"]:
print("ok")
break
elif answer1 in ["no", "n"]:
print("end")
break
else:
print("try again")
This question already has answers here:
How to repeat a section of the program until the input is correct?
(3 answers)
Closed 5 years ago.
I am trying to learn Python. I just made a simple rock, paper, scissors game for practice. I am having a small problem.
When each player choose the same item, the game ends in a tie.
When the player makes a mistake and has to choose again, the variable is empty. Notice that Player 1 says "none".
This is the method. The problem occurs in the else branch.
def play1():
player1_choice = input("Player 1 - Go: ")
if (check(player1_choice)):
return player1_choice
else:
print(error_msg)
play1() # Something is wrong here.
What did I do wrong? How can I fix it? Thanks
Don't use recursion if you don't have to. Try this:
def play1():
while True:
player1_choice = input("Player 1 - Go: ")
if (check(player1_choice)):
return player1_choice
else:
print(error_msg)
This is a classic while loop application; you want to loop until you get a reasonable answer (while the known answer is unacceptable), returning that answer to the calling program.
Use a for loop when you know as you enter the loop how many times you have to repeat it.
Recursion is proper when you have a job in which you can:
do something simple;
reduce the remaining task to something smaller, closer to a trivial "completed" state;
pass that smaller task to the same function for further processing.
In this application, getting a wrong answer from the user doesn't put you any closer to a solution (a valid answer) than when you started. The task isn't any simpler now. Further processing is the same, but you get that just as well with an iteration loop.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
My program first asks the user what is wrong with their mobile phone and when the user writes their answer, the program detects keywords and outputs a solution. I used "or" statements but when I input "My phone dropped in water and my speakers don't work" it should output "you need new speakers. if waters been in contact you also may need a new motherboard if it doesn't come on" but instead it outputs "you will need your screen replacing"
Can anybody tell me what I'm doing wrong and tell me how I can overcome this problem in the future.
import time #This adds delays between questions
name = input ("what is your name?")
problem1 = input("hello there,what is wrong with your device?")
if "cracked" or "screen broke" in problem1:
print("you will need your screen replacing")
elif "water" or "speakers" in problem:
print("you need new speakers. if waters been in contact you also may need a new motherboard if it doesnt come on")
I think you mis-understand or. In programming, or is slightly different from in English. x or y in z means "is x True or is y in z?". If the first argument (x) is non-empty, that means that it evaluates to True. No check is made for anything's presence in z. If x is empty, it evaluates to False and there is a check for y's presence in z, but not x's presence. You need to create a new test for each one. Also, you used problem instead of problem1 in your second elif:
if "cracked" in problem1 or "screen broke" in problem1:
...
elif "water" in problem1 or...
...
I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")