Python | Is it possible to have multiple outcomes of one IF statement? - python

Making an IT quiz for school and I don't want it to be case sensitive, so I'd have 2 if statements if I want there to be 2 possible answers. My problem is that only one answer works.. May sound confusing.
a = input("And the answer is...")
if a == "answer1":
print("Correct!")
if a == "answer2":
print("Correct!")
else:
print("Incorrect!")
The outcome if you enter "answer1" is:
Correct!
Incorrect!
However, "answer2" will give you:
Correct!
Basically, I want both "answer1" and "answer2" to have the outcome of "Correct!"

A couple of different ways:
if a == "answer1" or a == "answer2":
print("Correct!")
else:
print("Incorrect!")
or
if a in ["answer1", "answer2"]:
print("Correct!")
else:
print("Incorrect!")
or
if a == "answer1":
print("Correct!")
elif a == "answer2":
print("Correct!")
else:
print("Incorrect!")
You can read more about in the "Flow Control" section of the Python tutorial.

While isowen's answer is correct, and is a better way of writing the function, it doesn't explain why the first one is wrong.
The actual problem is that the else only applies to the second if statement, not the first one. If you wanted to have different behavior for each case, you could do:
a = input("And the answer is...")
if a == "answer1":
print("Correct!")
elif a == "answer2":
print("Also Correct!")
else:
print("Incorrect!")
edit: isowen wasn't done yet when I wrote this.

Related

Is there an if function in python for ASCII art? [duplicate]

I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()

Why can I not guess the correct number in this random number guesser in python 3.8.2?

import random
num=int(input("What is the highest number you want? "))
r=random.randint(0,num)
answer=int(input("Guess the number! "))
if answer!= r:
if answer < r:
print("More!")
if answer > r:
print("Less!")
if answer==r:
print("Correct!")
quit()
if answer !=r:
answer = int(input('Second guess out of 3! '))
if answer != r:
if answer < r:
print('Lower!')
if answer > r:
print('Higher!')
if answer == r:
print('Correct!')
quit()
answer = int(input('Final guess! '))
if answer == r:
print('Finally!')
quit()
else:
print('Damn... you lost.')
quit()
My limit was 5, and it said it was between 3 and 4.
I guessed 3 and it said it was too low.
I guessed 4 and it said it was too high.
Please help!
It may be the variables or possibly my limited understanding of the random module.
Am relatively new to programming so much explanation would be much appreciated.
You can never reach your "Correct" condition:
if answer!= r:
# etc
if answer==r:
print("Correct!")
quit()
It's not possible for answer == r to be true inside a block that's already conditional on answer != r.
What you probably want to do is check for answer == r immediately so you can quit() on a correct answer and otherwise continue. That way you don't even need to explicitly check for answer != r, which makes the code simpler by removing a lot of extra indentation:
import random
num = int(input("What is the highest number you want? "))
r = random.randint(0,num)
answer = int(input("Guess the number! "))
if answer == r:
print("Correct!")
quit()
if answer < r:
print("More!")
if answer > r:
print("Less!")
answer = int(input('Second guess out of 3! '))
if answer == r:
print('Correct!')
quit()
if answer < r:
print('Lower!')
if answer > r:
print('Higher!')
answer = int(input('Final guess! '))
if answer == r:
print('Finally!')
quit()
print('Damn... you lost.')
The problem you might be running into when you actually play your game is that you're using different words to indicate a wrong guess:
if answer < r:
print("More!")
if answer > r:
print("Less!")
# etc
if answer < r:
print('Lower!')
if answer > r:
print('Higher!')
In one case you're saying that the answer is more than the guess, and in the other you're saying that the guess is lower than the answer, and in both case you're meaning the same thing but saying something entirely different. (This is also made more confusing when reading the code because the answer is r and the guess is answer -- I had to reread it a few times when writing the above sentence to make sure I had it straight in my own head.) Maybe that's intentionally confusing to make the game harder, but if not you probably want to clarify the wording of your clues, or use the same wording both times.

How to repeat code from a certian point when user input is incorrect

I'm new to Python so I'm not really sure on the basics so I understand this is probably a stupid question.
I'm making code where the user inputs a number, and if they get it wrong, I want the code to restart and ask them to guess again till it's right. How do I do this?
print("Let's play a game! Type in a number and see if you guess mine correctly!")
num = input("Type in a number: ")
for x in range (0,1):
if num == "7":
print("Correct!")
else:
print("Nope, try again!")
(Also I know that a lot of this code is probably wrong.)
You can put it in a while loop:
verified = None
while verified is None:
num = input("Type in a number: ")
if num == "7":
print("Correct!")
# if answer is good
verified = True
else:
print("Nope, try again!")

if/elif questions not working?

I am very new to Python and preparing to start it as a GCSE. I have been trying to do a capital of France question set in school with different responses for some answers, but it has not been working. The syntax error 'unindent does not match any outer indentation level' comes up after the response for when answers are incorrect (e.g. after print('Right Country, Wrong City. Try again.'). Can anyone help? Thanks.
print('What is the capital of France?')
answer==input('Enter your answer:')
if answer == 'Paris':
print('Well Done! That\'s Correct.')
elif answer == 'Lyon':
print('Right country, Wrong city. Try again.')
input('Enter your answer:')
elif answer == 'F':
print('Terrible joke and the wrong answer. Try again.')
input('Enter your answer:')
else:
print('Sorry, that\'s incorrect. Try again.')
input('Enter your answer:')
Your indentation was off in the if/elif/else block
If you're assigning a variable, it should be one = not ==
If you want to prompt for the correct answer again, you have to reassign the variable answer (answer = input(....))
Also you may want to run a while answer == 'Paris' or something similar so that way it prompts continuously until the answer is the value you want it to be
print('What is the capital of France?')
answer = input('Enter your answer:')
if answer == 'Paris':
print('Well Done! That\'s Correct.')
elif answer == 'Lyon':
print('Right country, Wrong city. Try again.')
input('Enter your answer:')
elif answer == 'F':
print('Terrible joke and the wrong answer. Try again.')
input('Enter your answer:')
else:
print('Sorry, that\'s incorrect. Try again.')
input('Enter your answer:')
In addition to the previous answers, I just wanted to point out that it is better to use a while loop and assign the value to 'answer' within the while loop. This way, you can also insert a 'break' statement, that will terminate the program once you digit the word 'exit' or provide the right answer. Here is the code:
print('What is the capital of France?')
while True:
answer=input('Enter your answer, or type "exit" to close the program: ')
if answer=='exit':
print('Program terminated')
break
elif answer == 'Paris':
print('Well Done! That\'s Correct.')
break
elif answer == 'Lyon':
print('Right country, Wrong city. Try again.')
elif answer == 'F':
print('Terrible joke and the wrong answer. Try again.')
else:
print('Sorry, that\'s incorrect. Try again.')
At first when you want to save something in variable, you just use one = not == of them
At second you need to have all elif and if on same place dont use tabulators python is very sensitive on this
And for the answer you need to do loop maybe while to repeat until they write the right question
You should not use input(), but instead use raw_input().

python - checking string for certain words

What I'm trying to do is that, if I ask a question only answerable by Yes and
No, I want to make sure that yes or no is the answer. Otherwise, it will stop.
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
First:
answer = input(">").lower
should be
answer = input(">").lower()
Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
Something like:
if word.lower() in ('yes', 'no'):
would be the simplest approach (assuming case doesn't matter).
Side-note:
answer = input(">").lower
Is assigning a reference to the lower method to answer, not calling it. You need to add parens, answer = input(">").lower(). Also, if this is Python 2, you need to use raw_input, not input (In Python 3, input is correct).

Categories