User Input Not Responding With If/Else Statements Correctly - python

I'm working through Learning Python the Hard Way and I'm currently creating a game. For some reason my if/else statements are not properly working. Here is the related part in my current script:
if door_choice == '1':
room_one()
else:
print "I don't recognize that choice, try again!"
if door_choice == '2':
room_two()
else:
print "I don't recognize that choice, try again!"
if door_choice == '3':
room_three()
else:
print "I don't recognize that choice, try again!"
Whatever number I use to type in my input, I still receive the other answers' else statement, for example:
You see 3 doors.
You must choose either 1, 2 or 3.
> 2
I don't recognize that choice, try again!
The second room is dark and smelly but you see a gold chest!
Do you open the chest or just give up?
I don't recognize that choice, try again!
The print statement for "I don't recognize that choice, try again!" should not show up if I input the designated number. I tried adding integer to my input and having my door choice variable not as a string and still no luck.

You should chain those separate if-else blocks into one if-elif-else block:
if door_choice == '1':
room_one()
elif door_choice == '2':
room_two()
elif door_choice == '3':
room_three()
else:
print "I don't recognize that choice, try again!"

The problem is in your if statements. Your program encounters if door_choice == '1' which is false, so it jumps to the next else statement and prints "I don't recognize that choice, try again!"
Instead if first is not true, then check second, if not true check third, if not true, invalid choice.
if door_choice == '1':
room_one()
elif door_choice == '2':
room_two()
elif door_choice == '3':
room_three()
else:
print "I don't recognize that choice, try again!"

Besides the obvious "pass in else everytime" effect, you can use a table and function pointers to save the if/elif constructions if you have a lot of cases.
room_funcs = [room_one,room_two,room_three]
idx = int(door_choice)-1
if 0 <= idx < len(room_funcs):
room_funcs[idx]()
else:
print("I don't recognize that choice, try again!")

EDIT: As for maximums there is one if statement, chained by any amount of elif statements. However, there can only be 1 else statements per if.
TutorialsPoint has a great page regarding if/elif/else: http://www.tutorialspoint.com/python/python_if_else.htm
"The else statement is an optional statement and there could be at most only one else statement following if ."
I don't think your indentation is right. Indent all of the else statements by 4 spaces additionally after the if statements, and change them to if. Also take away the last else statement.
I'll show you what I mean.
if door_choice == '1':
room_one()
if door_choice != 1 or 2 or 3:
print "I don't recognize that choice, try again!"
if door_choice == '2':
room_two()
if door_choice != 1 or 2 or 3:
print "I don't recognize that choice, try again!"
if door_choice == '3':
room_three()
if door_choice != 1 or 2 or 3:
print "I don't recognize that choice, try again!"
Also, your not giving the user input after you say "I don't recognize that choice, try again!"

If door_choice == '1'
Room_one()
elif door_choice == '2'
Room_two()
elif door_choice == '3'
Room_three()
else
Print "please input a value between 1 and 3
You had some bad logics.
If you input 1, then that's correct otherwise error appears, however you check again for input 2 and get the wished result and then check again for input 3 but error appears again.
Using else if or elif in python is one of the way to get to the result.
There are also switches if you need to do more cases

Related

Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?

I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,
if guess.isdigit():
guess = int(guess)
Please help
import random
a = random.randint(1,10)
print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")
if question_one == "Yes":
print("Let's go!")
else:
print("That sucks!")
exit()
guess = None
while guess != a:
guess = (input("Alright, guess a number from 1-10"))
if guess.isdigit():
guess = int(guess)
if guess > a:
guess = int(input("Guess lower!"))
elif guess < a:
guess = int(input("Guess higher!"))
else guess == a:
print("you got it!")
else doesn't let you define a condition. else will execute if all other conditionals return false. You should change that last else to elif. Or you can simply leave out the conditional guess == a all together. If it is not greater than or less than, the only other thing it can be is equal to.
If you have the last else, the code inside the else will be executed if any other condition goes false. So I think if you change the last else with an elif we work properly.
An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:
elif guess == a:
print("you got it!")

if statement inside an if statement

this is kinda my homework and I'm stuck on making the code becoming a follow up question, like this code here, I've tried inserting an if statement after that but it gave me an unexpected incent error.
Here are my codes so far:
Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
You have an extra indent. Just remove the extra level of indentation:
Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
Indentation is the way to create code blocks in Python. Your error says exactly what you did wrong.
if condition:
# executes if condition is met
if internalCondition:
# executes if both condition and internalCondition is met
elif otherCondition:
# executes if first statement didn't and otherCondition is met
else:
# executes if nothing else executed
You indented if internalCondition: with excess whitespaces.

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

Elif giving invalid syntax python?

This is the code i have been using but it is not working as it says that the elif statement is invalid syntax. Can anyone help me because i am a beginner in python.
age = int(input('How old are you?: '))
if age <= 16:
print ('You are too young to enter this section of the program!')
else:
age >= 16
print ('Welcome to the advanced section of the program!')
elif: password = int(input('please enter the password to enter the elite members section: ')):
if password == ('muffin'):
print ('Well done for unlocking the secret part of the program')
else:
print ('You shall not pass!')
elif needs a condition (ie elif 7 > 5: ....) also an elif cannot follow an else and must follow an if or elif condition
in your case your elif has no condition ,so python does not know what to do
your elif also follows your else Im not sure what you actually expect it to do ...
Your elif has no conditional. Else if...what?
else:
age >= 16
This looks like an attempt at an elif. Should this really be
elif age >= 16:
That'd make sense based on your if.
Additionally, elif goes before else. If you are using elif, it needs to occur after the if but before the else:
if ...
elif ...
else ...
As stated above, be sure to have a condition for your elif statement as well as place it between your if and else. You may also run into an issue with your statements when a user's age is 16 as both your if and else technically qualify at this point.

If and elif in Python for good programming practices

Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. However I'm getting weird results such as this
input = raw_input('Please enter the required digit: ')
intput = int(input)
if intput == 0:
print 'if1'
if intput == 1:
print 'if2'
elif intput == 0:
print 'elif1'
elif intput == 1:
print 'elif2'
else:
print 'else'
if I in put 1 it will print "if2", I thought that it will also print "elif2" and other shenanigans when I try to change the "intput == n" code. So my question is do I have to stick to the if,elif, elif, .... n * elifs, else method which seems to me working alright than working with the wacky if,if.... n * ifs, elif, elif, ...n* elifs, else.
Thanks
The elif tree is designed such that at anywhere along if one of the statement turns out to be True, the rest of the elifs will not be evaluated.
Here's a tutorial that might help you understand if else better.
this may be more clear to understand:
if input == 0:
print "if1"
switch(input):
case 1:
print "if2"
break
case 0:
print "elif1"
break
case 1:
print "elif2"
break
default:
print "else"
break
of course, the code does not work.

Categories