Is there a way to use raw input inside an if-statement? I would like to ask the user a question and if they type "yes" I want to code to continue working after the if-statement. If they type "no" I want the code to say "Thank you for your time" and then stop all actions after that particular if-statement. Is this possible?
Code (I have never done this before so this is a wild guess):
tri=raw_input("Do the points that you entered form a triangle? (yes or no)")
tri=str(tri)
if tri == "yes" or "Yes" or "YES":
print "Your triangle is an:"
elif tri == "no" or "NO" or "No":
print "Thank you for your time."
else:
print "Not a valid answer, please try again later."
Give this a shot:
tri = None
while tri not in ['yes', 'no']:
tri=raw_input("Do the points that you entered form a triangle? (yes or no): ").lower()
if tri == 'yes':
print "Your triangle is an:"
else:
print "Thank you for your time."
Related
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 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()
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
from sys import exit
def answer():
answer = raw_input("> ")
if answer == "Yes" or answer == "yes":
#going to next
joint()
elif answer == "No" or answer == "no":
print "You still have something, I know..."
again()
else:
fubar()
def again():
again = raw_input("> ")
if again == "Yes" or again == "yes":
#going to next
joint()
elif again == "No" or again == "no":
print "You still have something, I know..."
else:
fubar()
def fuck():
print "Fubar'd!"
def joint():
print "To be continue..."
def question():
print "Hi duuuude..."
raw_input("To say 'Hi' press Enter")
print "Can you help me?"
answer()
question()
Hi, can you help me with this? I`m trying to repeat the function "answer", when I get answer "NO". Im want to escape function "again"... And also is there a way to escape "answer == "Yes" or answer == "yes": " so no matter I write capital or small letter to accept the answer and not to write like a noob "Yes" or "yes"?
This is usually achieved with a while loop.
Edit: As pointed out, while loops are nice and clear, and avoid recursion limits.
Never thought a simple answer would generate so many votes....
Lets give you an example
while True:
ans = raw_input("Enter only y or n to continue").strip().lower()
if ans == "y":
print "Done!"
break
elif ans == "n":
print "No?"
else:
print "Not valid input."
The simplest solution to your problem is remove your again function, and recurse:
def answer():
ans = raw_input("> ")
if ans == "Yes" or ans == "yes":
#going to next
joint()
elif ans == "No" or ans == "no":
print "You still have something, I know..."
answer() # again()
else:
fubar()
I had to rename your answer variable to ans so that it didn't clash with the function name.
For the second question, you want either:
if answer.lower() == "yes":
or
if answer in ("Yes", "yes"):