I\'m a newbie to Python and currently learning Control Flow commands like if
, else
, etc.
The if
statement is working all fine
Python can generate same 'invalid syntax' error even if ident for 'elif' block not matching to 'if' block ident (tabs for the first, spaces for second or vice versa).
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.
elif
and else
must immediately follow the end of the if
block, or Python will assume that the block has closed without them.
if 1:
pass
<--- this line must be indented at the same level as the `pass`
else:
pass
In your code, the interpreter finishes the if
block when the indentation, so the elif
and the else
aren't associated with it. They are thus being understood as standalone statements, which doesn't make sense.
In general, try to follow the style guidelines, which include removing excessive whitespace.
In IDLE and the interactive python, you entered two consecutive CRLF which brings you out of the if statement. It's the problem of IDLE or interactive python. It will be ok when you using any kind of editor, just make sure your indentation is right.
Remember that by default the return value from the input will be a string and not an integer. You cannot compare strings with booleans like <, >, =>, <= (unless you are comparing the length). Therefore your code should look like this:
number = 23
guess = int(input('Enter a number: ')) # The var guess will be an integer
if guess == number:
print('Congratulations! You guessed it.')
elif guess != number:
print('Wrong Number')
Besides that your indention is wrong. The code wont work. I know you are using python 3. something. I am using python 2.7.3 the code that will actually work for what you trying accomplish is this.
number = str(23)
guess = input('Enter a number: ')
if guess == number:
print('Congratulations! You guessed it.')
elif guess < number:
print('Wrong Number')
elif guess < number:
print("Wrong Number')
The only difference I would tell python that number is a string of character for the code to work. If not is going to think is a Integer. When somebody runs the code they are inputing a string not an integer. There are many ways of changing this code but this is the easy solution I wanted to provide there is another way that I cant think of without making the 23 into a string. Or you could of "23" put quotations or you could of use int() function in the input. that would transform anything they input into and integer a number.