if/elif questions not working? - python

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().

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()

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!")

I want to setup a would you like to retry

I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.

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).

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

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.

Categories