Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

else & elif statements not working in Python

Tags:

I'm a newbie to Python and currently learning Control Flow commands like if, else, etc.

The if statement is working all fine, but when I write else or elif commands, the interpreter gives me a syntax error. I'm using Python 3.2.1 and the problem is arising in both its native interpreter and IDLE.

I'm following as it is given in the book 'A Byte Of Python' . As you can see, elif and else are giving Invalid Syntax.

>> number=23 >> guess = input('Enter a number : ') >> if guess == number: >>    print('Congratulations! You guessed it.') >> elif guess < number:    **( It is giving me 'Invalid Syntax')** >> else:    **( It is also giving me 'Invalid syntax')** 

Why is this happening? I'm getting the problem in both IDLE and the interactive python. I hope the syntax is right.

enter image description here

like image 624
jayantr7 Avatar asked Aug 11 '11 11:08

jayantr7


People also ask

What is a else meaning?

1a : in a different manner or place or at a different time how else could he have acted here and nowhere else. b : in an additional manner or place or at an additional time where else is gold found. 2 : if not : otherwise leave or else you'll be sorry —used absolutely to express a threat do what I tell you or else. ...

Where do we use else?

We use else after words beginning with any-, every-, no- and some-, to mean 'other', 'another', 'different' or 'additional'. A: Will there be anything else, sir? (Do you want any additional thing(s)?)

What is the example of Else?

Else is defined as in a different way, place or time. An example of else is blowing up a balloon with a different gas; what else can I use? The definition of else is a different person or thing, or something more. An example of else is running into someone other than who you were expecting to see; someone else.

What is else synonym?

Synonyms for else. differently, other (than), otherwise.


2 Answers

It looks like you are entering a blank line after the body of the if statement. This is a cue to the interactive compiler that you are done with the block entirely, so it is not expecting any elif/else blocks. Try entering the code exactly like this, and only hit enter once after each line:

if guess == number:     print('Congratulations! You guessed it.') elif guess < number:     pass # Your code here else:     pass # Your code here 
like image 51
cdhowie Avatar answered Oct 01 '22 20:10

cdhowie


The problem is the blank line you are typing before the else or elif. Pay attention to the prompt you're given. If it is >>>, then Python is expecting the start of a new statement. If it is ..., then it's expecting you to continue a previous statement.

like image 39
Ned Batchelder Avatar answered Oct 01 '22 18:10

Ned Batchelder