I'm currently working on a python project and I need it to accept random input from users at some point.
So, if I have, for example:
def question_one () :
answer_one = raw_input ('How many days are there in a week? ').lower()
try:
if answer_one == 'seven' or answer_one == '7' :
question_2()
Everything works wonders. But how can I make python accept random input, as in
def question_two () :
answer_two = raw_input ('What´s your mother´s name? ').lower()
try:
if answer_two == ***I have no idea how to code this part*** :
question_3()
In this case, I would need python to accept any input and still take the user to the next question. How could I do it?
Just remove the if clause then.
If the input doesn't have to be of a specific form, or have some particular property, then there's no need for the if statement, or even the try.
def question_two():
answer_two = raw_input("What's your mother's name?").lower()
question_3()
If you want to be able to re-ask the question, if they don't get it right then you can loop back to it like so. The only acceptable answer for this question is "yes", or "YES", etc..
If they don't answer correctly it will ask them again,till they get it right.
def question1():
answer1 = raw_input("Do you like chickens?")
answer1 = answer1.lower()
if answer1 == 'yes':
print "That is Correct!"
question2()
else:
question1()
If you want them to be able to go on to the next question even if they get it wrong, you can do like so:
def question1():
answer1 = raw_input("Do you like chickens?")
answer1 = answer1.lower()
if answer1 == 'yes':
print "That is Correct!"
else:
print "Next question coming!"
question2()
def question2():
answer2 = raw_input("How many days in a week?")
answer2 = answer2.lower()
if answer2 == '7' or answer2 == "seven":
print "That is Correct!"
else:
print "Sorry,that was wrong"
question3()
Related
What is wrong with my coding. It is a simple conditional statement where you say yes or no to taking the quiz. If you type yes, you begin answering questions and if you type no, it just exits out of the function.
play=input("\v Do you want to take the quiz or not? Yes or No? ").lower
if play == "no":
print("That's too bad")
quit(main())
question_num=0
green_point=0
mean_point=0
if play=="yes":
print("Great! Let us Begin!")
for questions,answers in QUESTIONS:
playeranswer=input("{} " .format(questions))
But the program just ends once you type in an answer for play. I thought it was pretty clear what is supposed to happen. Why is it not doing anything?
1- the indention is wrong with your coding
2- you forgot the () after .lower
your code should be like this :
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower()
if play == "no":
print("That's too bad")
quit(main())
question_num = 0
green_point = 0
mean_point = 0
elif play == "yes":
print("Great! Let us Begin!")
for questions, answers in QUESTIONS:
playeranswer = input("{} " .format(questions))
Actually it's not just the indentation. When you do this:
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower
It actually sets play to be the function lower, not the lowercase string that results from calling lower(). You need to add parentheses:
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower()
if play == "no":
print("That's too bad")
quit(main())
question_num = 0
green_point = 0
mean_point = 0
elif play == "yes":
print("Great! Let us Begin!")
for questions, answers in QUESTIONS:
playeranswer = input("{} " .format(questions))
I'm using Python 2.7.13 and Windows Powershell. When I run the program, the first raw_input() isn't recognized, regardless of whether, "yes", "y", or "Yes", are entered.
Ideally, I'm wanting the program to register whether any of these options are initially used. If one of these options isn't used, the while loop continues to display the "Type 'yes' when you are ready to begin" message, until the appropriate input is received from the user. Any help would be greatly appreciated!
# This is a questionnaire form for a python programming exercise.
print "Hello, Sir or Madame.",
print "My name is Oswald, and I will be asking you a few questions, today."
print "Are you ready to begin?"
answer_1 = raw_input()
while answer_1 != "yes" or answer_1 != "y" or answer_1 != "Yes":
print "Type 'yes' when you are ready to begin."
answer_1 = raw_input()
if (answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"):
print "What is your name"
name = raw_input()
print "What is your favorite color?"
color = raw_input()
print "Where do you live?"
home = raw_input()
print "So, you're %r. You're favorite color is %r, and you live in %r" % (name, color, home)
You have your condition backwards.
In Python (and programming in general), the or statement is true if ANY of the items mentioned is true.
So when you say answer != A or answer != B then, because answer can only have one value, the result will always be true. This is because, if answer is C, then it will be doubly-true, while if answer is A the "or answer !=B" part will be true, while if answer is B the "answer != A" part will be true.
If you are testing for a list of possible acceptable responses, you need to either make it an inclusive test using or:
if answer = A or answer = B or answer = C ...
or make it an exclusive test using and:
if answer != A and answer != B and answer != C ...
This is true for if statements and while statements.
Try changing your while statement to be like this:
print "Are you ready to begin?"
answer_1 = raw_input()
while answer_1 == "yes" or answer_1 == "y" or answer_1 == "Yes":
print "Type 'yes' when you are ready to begin."
answer_1 = raw_input()
if (answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"):
print "What is your name"
name = raw_input()
Alright, I believe I've gotten it to work how you want it to.
First things first:
I made your condition evaluate to a single True or False by having it do this.
condition = ((answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"))
Then to start your while loop you just need to do this:
while not condition:
print "Type 'yes' when you are ready to begin."
answer_1 = raw_input()
condition = ((answer_1 == "yes") or (answer_1 == "y") or (answer_1 == "Yes"))
Then and this is the important part.
You need to move the questions out side of the while loop.
Because if the while evaluates to true, it will ask you repetitively if your ready.
But say you answer yes at the beginning the while loop evaluates to False and the code for the questions is skipped.
If you want it to ask the questions repetitively just put them in a
while True:
#ask the questions
Oh also, you won't need the if statement if you do it this way.
That is because if you answer no at the beginning, you'll enter the while loop until you enter yes. After which the loop closes, and the questions are asked.
I hope that answers your question.
Keep up the good work!
You can actually simplify what you're trying to do:
answer_1 = ''
while answer_1.lower() not in ('y', 'yes', 'si', 'da', 'yes, please'):
answer_1 = raw_input('Are you ready to begin? (type "yes" to begin): ')
And this will continue to ask for them to type... well, any of the possible inputs :)
Your problem is that you're getting the input twice:
print "Are you ready to begin?"
answer_1 = raw_input() # <==== Once here
while answer_1 != "yes" or answer_1 != "y" or answer_1 != "Yes":
print "Type 'yes' when you are ready to begin."
answer_1 = raw_input() # <==== again here
And then your if comes inside the while loop. But you don't need to do that.
It helps if you think about your program and write it out first without writing code:
while the user doesn't provide correct input, ask the user for input
then, ask them for their choices
What that means in the code is that you're going to have two separate blocks:
# Block 1
# while not_correct_input:
# get input
# Block 2
# ask for choices
Now you can replace these with code that you need:
from __future__ import print_function
# Block 1
# while not correct input
# get input
# Block 2
name = raw_input("What is your name? ")
color = raw_input("What is your favorite color? ")
home = raw_input("Where do you live? ")
print("So, you're %r. You're favorite color is %r, and you live in %r" % (name, color, home))
Once you try this out and it works, then you can go ahead and add your check for correct input:
# Block 1
answer_1 = ''
while answer_1.lower() not in ('y', 'yes', 'si', 'da', 'yes, please'):
answer_1 = raw_input('Are you ready to begin? (type "yes" to begin): ')
# Block 2
name = raw_input("What is your name? ")
color = raw_input("What is your favorite color? ")
home = raw_input("Where do you live? ")
print("So, you're %r. You're favorite color is %r, and you live in %r" % (name, color, home))
Now when all of this works, go ahead and add the other parts of your program that you want:
from __future__ import print_function
print('''
Hello, Sir or Madame. My name is Oswald, and I will be asking you a few questions, today.
'''.strip())
# Block 1
answer_1 = ''
while answer_1.lower() not in ('y', 'yes', 'si', 'da', 'yes, please'):
answer_1 = raw_input('Are you ready to begin? (type "yes" to begin): ')
# Block 2
name = raw_input("What is your name? ")
color = raw_input("What is your favorite color? ")
home = raw_input("Where do you live? ")
print("So, you're %r. You're favorite color is %r, and you live in %r" % (name, color, home))
Here's an example of what this code looks like in action:
Hello, Sir or Madame. My name is Oswald, and I will be asking you a few questions, today.
Are you ready to begin?
Are you ready to begin? (type "yes" to begin): no
Are you ready to begin? (type "yes" to begin): maybe
Are you ready to begin? (type "yes" to begin): probably
Are you ready to begin? (type "yes" to begin): okay
Are you ready to begin? (type "yes" to begin): yes
What is your name? Wayne
What is your favorite color? Blue... no yellow!
Where do you live? Camelot
So, you're 'Wayne'. You're favorite color is 'Blue... no yellow!', and you live in 'Camelot'
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 7 years ago.
I'm writing a simple 8ball response program and have an issue. When I run this program but give any option other than "y" or "yes" in response to the variable 'rd', the program thinks I have actually inputted "yes" and goes ahead with the code indented in the 'if' statement with a yes response. Why is this? I can't work out why.
import time
import random
import sys
resp = ["Yes!", "No!", "Maybe!", "Don't be so silly!",
"In your dreams!", "Without a doubt!", "Most likely!",
"Very doubtful!", "I'm going to have to say no this time!",
"What kind of a question is that? Of course not!", "I reckon there's a 20% chance!",
"Better not tell you now", "I've been told by to tell you no...",
"I've been told to tell you yes...", "It's possible!", "More likely to see pigs fly!",
"You wish!", "All signs point to no!", "All signs point to yes!",
"If you truly believe it!"
]
def intro():
print "Hello! Welcome to 8 Ball!\n"
time.sleep(2)
def main():
quit = 0
while quit != "n":
rd = raw_input("Are you ready to play? Enter y/n: ")
if rd.lower() == "y" or "yes":
question = raw_input("\nType your question and please press enter: ")
print "\n"
print random.choice(resp)
print "\n"
quit = raw_input("Do you want to roll again? Enter y/n: ")
elif rd.lower() == "n" or "no":
print "Looks like you need some more time to think. Have a few seconds to think about it.."
time.sleep(3)
quit = raw_input("Are you ready to play now? Enter y/n: ")
else:
print "That wasn't an option. Try again."
rd = raw_input("Are you ready to play? Enter y/n: ")
print "Okay! Thanks for playing."
intro()
main()
>>> bool("yes")
True
"yes" evaluates to true
if rd.lower() in ("y", "yes"):
could be used check to see if the value is 'y' or 'yes'
You can't do if x == a or b in python you have to do x == a or x == b or x in (a, b)
import time
import random
import sys
resp = ["Yes!", "No!", "Maybe!", "Don't be so silly!",
"In your dreams!", "Without a doubt!", "Most likely!",
"Very doubtful!", "I'm going to have to say no this time!",
"What kind of a question is that? Of course not!", "I reckon there's a 20% chance!",
"Better not tell you now", "I've been told by to tell you no...",
"I've been told to tell you yes...", "It's possible!", "More likely to see pigs fly!",
"You wish!", "All signs point to no!", "All signs point to yes!",
"If you truly believe it!"
]
def intro():
print "Hello! Welcome to 8 Ball!\n"
time.sleep(2)
def main():
quit = 0
while quit != "n":
rd = raw_input("Are you ready to play? Enter y/n: ")
if rd.lower() in ("y", "yes"):
question = raw_input("\nType your question and please press enter: ")
print "\n"
print random.choice(resp)
print "\n"
quit = raw_input("Do you want to roll again? Enter y/n: ")
elif rd.lower() in ("n", "no"):
print "Looks like you need some more time to think. Have a few seconds to think about it.."
time.sleep(3)
quit = raw_input("Are you ready to play now? Enter y/n: ")
else:
print "That wasn't an option. Try again."
rd = raw_input("Are you ready to play? Enter y/n: ")
print "Okay! Thanks for playing."
intro()
main()
You can't do this:
if rd.lower() == "y" or "yes":
because it's evaluating "yes" by itself. Instead try:
if rd.lower() == "y" or rd.lower() == "yes":
also consider:
if rd.lower() in ["y", "yes"]:
I'm a beginner to Python, and am having problems with a function. I am making a program in which I have many parameters for the user to choose from and I need to allow them to confirm or deny their choices. Here is a simplified code section that represents my issue.
my code:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
print 'Congratulations! You have a name!'
break
your_name()
When running this program, it will print the congratulatory string the same amount of times that answer received an input.
my output:
What is your name? Bastion
Are you sure? no
What is your name? Artex
Are you sure? no
What is your name? Falcor
Are you sure? yes
Congratulations! You have a name!
Congratulations! You have a name!
Congratulations! You have a name!
My intention is for the congratulatory message to be printed just one time. How can I edit my function(s) in order to achieve this?
What I've tried:
I have attempted all of these, using the exact same input values I used in my output block above.
Within the section of confirm(function) that says:
if answer == 'no':
return function()
I've tried changing it to:
if answer == 'no':
function()
In the output, this will ask for the answer raw_input 3 times, posting the congratulatory message after each input. If I write the code in this way:
if answer == 'no':
print function()
It will print the congratulatory response 3 times and print None on a separate line below for each time. I am looking for an elegant, clean format so this will not do.
So your problem is you are creating a kind of recursive function without meaning to, you don't need to pass the function to be called again as you are already inside the function. I would suggest the following:
def confirm():
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
if answer == 'no':
return False
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
elif confirm():
print 'Congratulations! You have a name!'
break
your_name()
I think the cleanest way is to change your_name to:
def your_name(toplevel=False):
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
if toplevel: print 'Congratulations! You have a name!'
break
and the very first call from the top level to your_name(True).
There are other ways, but they require global variables (ecch:-) or even dirtier tricks to find out if the function has been called from the top level; telling it explicitly is way cleaner...
Because of the style recursion you're doing (kudos on that) you end up invoking the your_name() function once each time they fill an answer.
I'd try something more like this:
def confirm():
answer = ''
while answer == '':
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
answer = ''
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
if confirm():
print 'Congratulations! You have a name!'
else:
your_name()
your_name()
I think you don't have to use all those "recursive" calls, try this:
def your_name():
flag = True
while flag:
name = raw_input("What is your name? ")
if name:
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
flag = False
break
elif answer == 'no':
break
print 'Congratulations! You have a name!'
your_name()
Using an inner loop for asking if the user is sure. With the use of a flag to determine whenever or not the main "What is your name? " question cycle is over.
You can just put the print 'Congratulations! You have a name!' inside your confirmation() function instead of your_name() so it will be something like this:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
print 'Congratulations! You have a name!'
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue
else:
confirm(your_name)
break
your_name()
BTW, I also modify your conditional syntax in the first function so that the program won't go through two if statements.
This solution is relatively succinct. It loops requesting your name while 'name' is an empty string. When requesting confirmation, it resets name to an empty string and thus continues the loop unless the user confirms 'yes'. It then prints the user's name to confirm its assignment.
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
answer = raw_input('Are you sure (yes or no)? ') if name != '' else 'no'
name = '' if answer != 'yes' else name
print 'Congratulations {0}! You have a name!'.format(name)
I'm new to Python and I am currently doing some work with IF statements.
This is what I have so far...
print("Hello")
myName = input("What is your name?")
print("Hello " +myName)
myAge = int(input("How old are you?"))
if myAge <=18:
myResponse = input("You must still be at school?")
if myResponse == "Yes" or "yes" or "YES" or "Y" or "yEs" or "y":
mySchool = input("What school do you go to?")
print (mySchool, "that is a good school I hear")
if myResponse == "No" or "n" or "N" or "NO":
print("Lucky you, you have lots of free time!")
if myAge >=19:
myResponse = input("You must have a job?")
if myResponse == "Yes" or "yes" or "YES" or "Y" or "yEs" or "y":
myWork = input("What do you do?")
print (myWork, "Thats a tough job")
if myResponse == "No" or "n" or "N" or "NO":
print("Lucky you, you have lots of free time!")
I want the user to be able to answer a question with a one word answer however have various options that would be recognized by the program for example "No", "NO" and "no" or "yes", "YES" and "Yes".
I have just figured out this way of doing it seen above but is there a better way it should be done?
Bare in mind I am new to this so it is probably a silly question.
Any help would be greatly appreciated.
Si
This condition checks that myRespone is either yes or "y" and is case insensitive (meaning that yes, YeS, and others are all valid)
myResponse.lower() in ["yes","y"]
The question asks specifically for answers in the form "yes" or "no" with different capitalizations ("y" or "n" are not mentioned). With that in mind, we can do as follows, being careful to remove any extra spaces:
if myresponse.strip().lower() == "yes":
# if yes, do something
And similarly:
if myresponse.strip().lower() == "no":
# if no, do something else
Try this:
if myResonse.lower() == "yes":
etc
With string functions:
if myResponse.upper() == 'NO':
# do something
Or:
if myResponse.lower() == 'no':
#do something