drinks = 5
if drinks <= 2:
print("Keep going buddy")
elif drinks == 3:
print("I believe you've had enough, sir")
else:
print("stop")
This was the code I was trying to run, and it keeps giving me a syntax error with the "else" and I don't know why.
Your syntax is wrong. Remove the space before the else:
The syntax of your code is labeled as incorrect because an else statement and clause cannot exist without an if statement and clause preceding it. Since you have an else statement alone inside an elif clause, an error is thrown.
Likely this is just an issue with your indentation, which you need to be very careful about, since Python emphasizes whitespace. Here is the code I believe you meant to type:
drinks = 5
if drinks <= 2:
print("Keep going buddy")
elif drinks == 3:
print("I believe you've had enough, sir")
else:
print("stop")
Related
I have a main program that uses a function from a class from another file, in the while loop, when the function is called with the correct parameters it just doesn't return anything print anything or do anything it supposed to do, however it doesn't raise any errors and it goes back to the start of the loop.
Here is a snippet of the main loop in question:
....
elif command in ["talk","fight","hug"]:
if inhabitant is not None:
if inhabitant.event_handler(command,current_room,inventory) is False:
break
else:
continue
else:
print("There is nobody in the room")
cl()
....
and the function in question:
def event_handler(self,command,room,inv):
if command is "talk":
self.talk()
input()
print("\n"*25)
elif command is "hug":
print("You probably don't want to do that")
input()
print("\n"*25)
elif command is "fight":
itemSel = input("What item do you want to fight with?\n>")
if itemSel in inv:
if self.fight(itemSel):
room.character = None
if Character.number_of_enemies == 0:
print("Congrats! You defeated all the enemies and won the game!")
input()
return False
input()
print("\n"*25)
else:
print("You died")
input()
return False
else:
print("You don't have this item")
input()
print("\n"*25)
where all of the variables are valid and have already been assigned values at some point in the main loop, and the functions .fight() and .talk() are also in the same class as .event_handler()
.event_handler() is a method of the object stored as inhabitant
What could be the reason behind this not working? I don't really get it so if anyone could help I'd greatly appreciate it.
I think you have multiple problems going on here, I am afraid. First, event_handler has no return statement. Therefore, no matter what, it is returning None, which is not False. Therefore,
if inhabitant.event_handler(command,current_room,inventory) is False:
will always be untrue.
However, as #jordanm mentioned, you are likely not even getting to that call. You can test this with a small function just to see what would have happened:
>>> def testfun():
... print("Did I get here?")
...
>>> if testfun() == False:
... print("Yes, I got in here.")
...
Did I get here?
You'll notice 2 things:
Even though there is no return statement (which means it always returns None), the function is at least called.
The comparison (if statement) is untrue, since False != None, so the second print statement is not run.
Finally, as others have said, using is is risky. Without inundating you with too much information, == compares if the values are the same whereas is compares if it is actually the same object in memory. If that makes no sense to you, don't worry about it and just remember that == is the safer route.
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
I am a Python newb.
I keep getting indent errors around the if statements of my code.
The first chunk of if/else statements are read fine.
The second chunk results in indent errors.
When I remove it for debugging.
The third chunk (at the end) also returns indent errors.
...but I'm not sure where to find them?
Any suggestions on what's going wrong?
# Begin Fight/Conditions for Ending
while Player.hp > 0 and Marco.hp > 0:
while playerchoice not in [1,2,3,4]:
playerchoice = input("\n Which move would you like to use: ")
marcochoice = random.choice([1,2,3,4])
# Making the Moves - Player Always Goes First (For now!)
if playerchoice == 1:
Player.jabs(Marco)
#print("\n Player - jabs - Debug")
elif playerchoice == 2:
...
else:
#print("Player - Non-Choice - Debug")
# Marco's Turn!
if Marco.hp > 0:
if marcochoice == 1:
Marco.jabs(Player)
#print("Marco - Jabs - Debug")
...
else:
#print("Marco - Non-Choice - Debug")
else:
pass
# Ending Conditional
if Marco.hp <= 0 and Player.hp <= 0:
print("It's a draw!")
...
else:
print("Something has gone horribly wrong!")
It's not the quotation marks. I made that error when transferring the code to stackoverflow (modified the code for readability/compactness).
The error is with the comments by some of the else statements.
Python never reads/executes anything, so it just assumes whatever follows is supposed to be indented.
Once I put pass underneath the else statements, everything cleared up.
Assuming you try to run this exact code you posted, the problem is the comment after you first 'else:' statement. The same happens here:
for i in range(10):
if i in [0,1,2,3,4,6,7,8,9]:
print("found")
else:
#print("test")
print("that could be it")
To run without problems just uncomment the second print statement.
Hope that helps.
It looks like your forgot the double quote
playerchoice = input("\n Which move would you like to use: ")
The color of the text could have helped you ;)
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.
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.