Invalid syntax on if-else statement - python

Can someone explain why I am getting an invalid syntax error from Python's interpreter while formulating this simple if/else statement? I don't add any tabs myself I simply type the text then press enter after typing. When I type an enter after "else:" I get the error. else is highlighted by the interpreter. What's wrong?
>>> if 3 > 0:
print("3 greater than 0")
else:
SyntaxError: invalid syntax

Python does not allow empty blocks, unlike many other languages (since it doesn't use braces to indicate a block). The pass keyword must be used any time you want to have an empty block (including in if/else statements and methods).
For example,
if 3 > 0:
print('3 greater then 0')
else:
pass
Or an empty method:
def doNothing():
pass

That's because your else part is empty and also not properly indented with the if.
if 3 > 0:
print "voila"
else:
pass
In python pass is equivalent to {} used in other languages like C.

The else block needs to be at the same indent level as the if:
if 3 > 0:
print('3 greater then 0')
else:
print('3 less than or equal to 0')

The keyword else has to be indented with respect to the if statement respectively
e.g.
a = 2
if a == 2:
print "a=%d", % a
else:
print "mismatched"

The problem is indent only.
You are using IDLE. When you press enter after first print statement indent of else is same as print by default, which is not OK. You need to go to start of else sentence and press back once. Check in attached image what I mean.

it is a obvious mistake we do, when we press enter after the if statement it will come into that intendation,try by keeping the else statement as straight with the if statement.it is a common typographical error

Else needs to be vertically aligned. Identation is playing a key role in Python. I was getting the same syntax error while using else. Make sure you indent your code properly

Related

Why do I get an "invalid syntax" error for this simple if-else code?

I have a simple python code as follows:
a = 3
if a == 3:
print("a is 3")
print("yes")
else:
print("a is not 3")
I get an invalid syntax error for the else: part. Can someone please explain why? Is it illegal to have code between an if and else statement?
This is expressly forbidden by the language definition. You cannot have an else without a matching if.
Note the syntax here is that you can have zero or more elif statements and else is entirely optional, if you don't want to include it.
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
Depending on your actual goals here, you could do something where you just keep the print function call inside of the positive if block instead.
a = 3
if a == 3:
print("a is 3")
print("yes")
else:
print("a is not 3")
...but this is obviated by "a is 3" being printed out in advance of this, so having this print("yes") expression doesn't add a whole lot of extra value.
You exited the if block when you printed the word "yes" because that print statement is indented at the same level as the if statement. So, when the parser finds an else statement on the following line, it does not have a corresponding if statement and raises a syntax error. It looks like you intended to indent the second print statement to the same level as the first one. That will certainly resolve the error anyway.

Not able to use an if statement in python shell

i am new to python and i want to write a simple function which will get some input and print it accordingly, something like this
def printer(data):
if data<5:
print('data is less than 5')
else:
print('data is greater than 5')
return;
but when i run this code, i get an
'unexpected indent'
error, what am i doing wrong
As the error points out, you need to indent your code as required by Python language. So after typing if condition1:, hit enter, then hit tab and write your following code.
def printer(data):
if data<5:
print('data is less than 5')
else:
print('data is greater than 5')
return
And don't put a ; at the end of your function, this is not JS.
Welcome to Python! You need to make sure your code is properly indented. Python doesn't use braces to mark sections, instead, it uses indentation. Just like missing a brace in another language, you need to make sure the indentation is right.
def printer(data):
if data<5:
print('data is less than 5')
else:
print('data is greater than 5')
No need for a return if there is no return value, and Python doesn't use semi-colons as end of statement markers.
The unexpected indent in the picture is the initial space before def, as indicated by the red rectangle. (This is an IDLE feature, so I suspect you are using IDLE.)
When you fix that, see AIG's or Rostan's answer.

Unindent error and input number limit

I am making a calculator (using tkinter) and I need to have a limit so if the user enters an input of more than 999, an error message appears and the numbers are not calculated (it is a school project). When I run the script from below, at school it just appears with a blank GUI and on my home computer it says 'unindent does not match any outer indentation level'. How can I solve this?
Thanks
P.S. I am using Python 3.3.2
def calc(self):
try:
self.display.set(self.validate_result(eval(self.display.get())))
self.need_clr = True
except:
showerror('Operation Error', 'Illegal Operation')
self.display.set('')
self.need_clr = False
def validate_result(self, result):
if result >= 1000:
raise ValueError('result too big!')
else:
return result
Python uses indentation to distinguish levels of scope.
Here all your code seems to be entirely indented, so Python thinks all your code is in an inner scope, and tries to find the outer scope that contains it, but there isn't any.
You should try with this indentation :
def calc(self):
try:
...
def calc(self):
try:
...
Edit : also, you seem to have other indentation problems in the second function. You must align except with try, and there is one space missing before if result >= 1000:.

except ValueError not tripping Python 3.4

Alright so I'm trying to basically prevent someone from typing a string value into the field:
#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()
#Security statement followed by case statement
while selection <= 0 or selection >= 10:
try:
print("That is an invalid selection, please input a proper selection.")
print("Which program would you like to run?")
selection = int(input())
print()
except ValueError:
print("Cmon man")
Plain and simple, it's not running. I've tried reorganizing everything and I haven't found a proper solution. Been looking around for almost an hour now. No help to the issue. Any kind souls?
Ignore the case statement portion btw, that's not even written yet.
P.S. Just keep getting usual "String isn't a number durr" response
("ValueError: invalid literal for int() with base 10: 'why'")
P.P.S. Issue is already pointed out. I'm apparently stupidly oblivious lol... Thanks for the help.
Your try...except doesn't cover the initial user input and so the ValueError isn't actually caught.
If you enter an int outside the bounds defined (0 >= x >= 10) as the first input then you can see the try...except blocks working.
You'll need to refactor your code so that the first input request is inside your try block and the loop or wrap the existing input request in another try...except.
Also, as a side note, input() can take a string argument that will be displayed as a prompt to the user.
selection = int(input("Which program would you like to run? "))

Different indentation no error in python

password = raw_input("Enter password: ")
if password == "1234":
print "You logged in correctly!"
else:
print "GTFO"
Though i give different indentations the code is working fine i'm unable to figure it out.
it will not be flagged as as IndentationError, sine any block of statement has to have at lease 1 space of indent
here your if and else are two different blocks, so it was indented anyway so the interpreter throws no error
if True:
print
elif True:
print
elif True:
print
elif True:
print
else:
print
This will work without any problem
But if I try the following I will get IndendationError
if True:
print ""
print "" # has different Indentation
print ""
The Python documentation explains indentation. Here's a relevant excerpt:
At the beginning of each logical line, the line’s indentation level is
compared to the top of the stack. If it is equal, nothing happens. If
it is larger, it is pushed on the stack, and one INDENT token is
generated. If it is smaller, it must be one of the numbers occurring
on the stack
In your code, since the indentation level is larger than the top of the stack (which is 0), it is treated as a single indent. The else: line popped 2 off of the top of the stack, so the interpreter has no memory of your previous indentation level of 2. It only knows that it's higher than the 0.
Problems arise when you start mixing indentation within a block:
def foo():
if True:
return True
return False # Is this part of the if statement or not?
When the parser reaches return False, the stack contains [4, 8]. The next line has an indent of 6, which is not contained in the stack and therefore generates an IndentationError.

Categories