Dieter
Dieter

Reputation: 21

My else statement is always an invalid syntax

I follow a course "web programming" and I'm stuck in Python. My "else" statement always gives an error (invalid syntax). No matter which code I try (any random code I use from the web), I always get the same error with my else statement. This is a very simple code which gives the error:

#!/usr/bin/python

test1 = 2
test2 = 1

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else test1 == test2:
    print("is equal")

This is what I get in Terminal:

  File "varvergelijken3.py", line 10
    else test1 == test2:
             ^
SyntaxError: invalid syntax

Upvotes: 0

Views: 258

Answers (3)

Mureinik
Mureinik

Reputation: 311863

The else clause does not take an argument - it's executed if and only if the if condition and all the elif conditions are not met. You could use another elif condition:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
elif test1 == test2:
    print("is equal")

Or, since if neither test1 is smaller than test2, nor test2 smaller than test1, they must be equal, so a simple else condition would suffice:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else:
    print("is equal")

Upvotes: 1

DorElias
DorElias

Reputation: 2313

else doesnt have a condition in python, you can do :

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else:
    print("is equal")

or if you want to specify the condition than do:

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
elif test1 == test2:
    print("is equal")

Upvotes: 1

taesu
taesu

Reputation: 4580

test1 = 2
test2 = 1

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
elif test1 == test2:
    print("is equal")

else doesn't carry conditional

or more desirably

test1 = 2
test2 = 1

if test1 < test2:
    print("Is smaller")
elif test1 > test2:
    print("is bigger")
else:
    print("is equal")

to learn more, refer to the doc

Upvotes: 1

Related Questions