Elif syntax error python

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 sy...

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

Brad Koch's user avatar

Brad Koch

18.7k18 gold badges108 silver badges136 bronze badges

asked Aug 11, 2011 at 11:59

jayantr7's user avatar

4

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

answered Aug 11, 2011 at 12:08

cdhowie's user avatar

cdhowiecdhowie

152k24 gold badges283 silver badges295 bronze badges

4

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.

answered Aug 11, 2011 at 12:08

Ned Batchelder's user avatar

Ned BatchelderNed Batchelder

358k72 gold badges559 silver badges655 bronze badges

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.

answered Aug 11, 2011 at 12:04

Katriel's user avatar

KatrielKatriel

118k19 gold badges134 silver badges167 bronze badges

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.

answered Aug 11, 2011 at 14:08

Meng's user avatar

MengMeng

532 silver badges5 bronze badges

 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right. The syntax is ok.

paxdiablo's user avatar

paxdiablo

838k230 gold badges1561 silver badges1929 bronze badges

answered Aug 11, 2011 at 12:04

Bogdan's user avatar

BogdanBogdan

7,9116 gold badges46 silver badges64 bronze badges

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')

answered Feb 15, 2017 at 2:42

Nello's user avatar

NelloNello

1414 silver badges15 bronze badges

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.

answered Apr 12, 2013 at 21:39

NOE2270667's user avatar

NOE2270667NOE2270667

551 gold badge4 silver badges12 bronze badges

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).

answered May 14, 2017 at 3:29

Alfishe's user avatar

AlfisheAlfishe

3,2501 gold badge24 silver badges19 bronze badges

indentation is important in Python. Your if else statement should be within triple arrow (>>>), In Mac python IDLE version 3.7.4 elif statement doesn’t comes with correct indentation when you go on next line you have to shift left to avoid syntax error.

enter image description here

answered Jul 29, 2019 at 2:07

bikram sapkota's user avatar

bikram sapkotabikram sapkota

1,0641 gold badge13 silver badges18 bronze badges

Error: else & elif Statements Not Working in Python

You can combine the else statement with the elif and if statements in Python. But when running if...elif...else statements in your code, you might get an error named SyntaxError: invalid syntax in Python.

It mainly occurs when there is a wrong indentation in the code. This tutorial will teach you to fix SyntaxError: invalid syntax in Python.

Fix the else & elif Statements SyntaxError in Python

Indentation is the leading whitespace (spaces and tabs) in a code line in Python. Unlike other programming languages, indentation is very important in Python.

Python uses indentation to represent a block of code. When the indentation is not done properly, it will give you an error.

Let us see an example of else and elif statements.

Code Example:

num=25
guess=int(input("Guess the number:"))
if guess == num:
    print("correct")
    elif guess < num:
        print("The number is greater.")
else:
    print("The number is smaller.")

Error Output:

  File "c:Usersrhntmmyscript.py", line 5
    elif guess < num:
    ^^^^
SyntaxError: invalid syntax

The above example raises an exception, SyntaxError, because the indentation is not followed correctly in line 5. You must use the else code block after the if code block.

The elif statement needs to be in line with the if statement, as shown below.

Code Example:

num=25
guess=int(input("Guess the number:"))
if guess == num:
    print("correct")
elif guess < num:
    print("The number is greater.")
else:
    print("The number is smaller.")

Output:

Guess the number:20
The number is greater.

Now, the code runs successfully.

The indentation is essential in Python for structuring the code block of a statement. The number of spaces in a group of statements must be equal to indicate a block of code.

The default indentation is 4 spaces in Python. It is up to you, but at least one space has to be used.

If there is a wrong indentation in the code, you will get an IndentationError in Python. You can fix it by correcting the indent in your code.

Маниго

0 / 0 / 0

Регистрация: 22.08.2015

Сообщений: 4

1

22.08.2015, 16:11. Показов 13705. Ответов 9

Метки нет (Все метки)


Приветствую всех, возникла вот такая проблемка, взялся поучить Python, поставил версию 3.4.3, из литературы выбрал Саммерфилд — Программирование на Python 3.2009. Все было прекрасно и понятно пока не столкнулся вот с такой проблемой:

Python
1
2
3
4
5
>>> if x:
    print("x is non zero")
    if lines < 1000:
        print("small")
        elif lines < 10000:

SyntaxError: invalid syntax

Реально не понимаю в чем проблема, все по книге, отступы автоматом ставит. Помогите советом.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

22.08.2015, 16:11

Ответы с готовыми решениями:

В чем ошибка? Ругается на elif
import math
tip=input(&quot;Введите название фигуры =&quot;)
if tip==&quot;круг&quot;:
r=float(input(&quot;Введите…

Не срабатывает elif
Здравствуйте. Такая проблема- if срабатывает не зависимо от истинности (либо выдает ошибку) и elif…

Elif в Python 3.5.2
простенькая задачка:

if pH==7.0:
print (pH,&quot;Water&quot;)
elif 7.36&lt;pH&lt;7.44:

#ifdef, #elif defined и #else
Если нужно определить ОС, на которой запускается программа, можно воспользоваться такой системой:…

9

2739 / 2342 / 620

Регистрация: 19.03.2012

Сообщений: 8,832

22.08.2015, 16:35

2

Цитата
Сообщение от Маниго
Посмотреть сообщение

отступы автоматом ставит

это это автоматом ставит отступы?

Цитата
Сообщение от Маниго
Посмотреть сообщение

все по книге

Если бы все по книге было, то все работало бы.



0



Marinero

Модератор

Эксперт NIX

2792 / 2035 / 682

Регистрация: 02.03.2015

Сообщений: 6,509

22.08.2015, 16:37

3

Ну вот если бы Вы и сами код нормально отформатировали(поместив его в теги [PYTHОN][/PYTHОN]), то и мы бы посмотрели

Python
1
2
3
4
5
if x:
    print("x is non zero")
if lines < 1000:
    print("small")
elif lines < 10000:



0



alex925

2739 / 2342 / 620

Регистрация: 19.03.2012

Сообщений: 8,832

22.08.2015, 16:38

4

Python
1
2
3
4
5
6
7
8
x = 178
lines = 1001
if x:
    print("x is non zero")
if lines < 1000:
    print("small")
elif lines < 10000:
    print('больше 1000, но меньше 10000')



0



Маниго

0 / 0 / 0

Регистрация: 22.08.2015

Сообщений: 4

22.08.2015, 16:43

 [ТС]

5

у меня он выглядит так

Python
1
2
3
4
5
if x:
    print("x is non zero")
    if lines < 1000:
        print("small")
        elif lines < 10000:



0



alex925

2739 / 2342 / 620

Регистрация: 19.03.2012

Сообщений: 8,832

22.08.2015, 16:46

6

Цитата
Сообщение от alex925
Посмотреть сообщение

это это автоматом ставит отступы?

«кто это» имелось ввиду, опписался

Цитата
Сообщение от Маниго
Посмотреть сообщение

у меня он выглядит так

Вот из-за того, что он у тебя так выглядит, ничего и не работает

Цитата
Сообщение от Маниго
Посмотреть сообщение

у меня он выглядит так

А должен так

Python
1
2
3
4
5
6
7
8
9
x = 178
lines = 1001
 
if x:
    print("x is non zero")
    if lines < 1000:
        print("small")
    elif lines < 10000:
        print('больше 1000, но меньше 10000')



0



0 / 0 / 0

Регистрация: 22.08.2015

Сообщений: 4

22.08.2015, 16:48

 [ТС]

7

Python 3.4.3 Shell
В этом редакторе



0



2739 / 2342 / 620

Регистрация: 19.03.2012

Сообщений: 8,832

22.08.2015, 16:51

8

Цитата
Сообщение от Маниго
Посмотреть сообщение

В этом редакторе

Это не редактор, а интерпретатор запущенный в интерактивном режиме

Ну, а вообще, то что ты вбиваешь код в интерактивном режиме мало, что меняет, отступы все равно тебе нужно точно также ставить. Так что смотри на то, что я тебе кинул и построчно вбивай также и все будет работать.



0



0 / 0 / 0

Регистрация: 22.08.2015

Сообщений: 4

22.08.2015, 16:54

 [ТС]

9

Сделал, через backspace, по другому не получается, все работает, Благодарю!



0



71 / 67 / 6

Регистрация: 08.08.2013

Сообщений: 286

Записей в блоге: 8

22.08.2015, 20:05

10

Скачай pycharm и радуйся жизни.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

22.08.2015, 20:05

Помогаю со студенческими работами здесь

Python 3.2 оператор if else elif
Ввожу пример из книги саммерфилда :
x=int(input())
if x&lt;100:
print(&quot;medium&quot;)
else:…

Директивы #if, #elif, #else и #endif в C#
Добрый день, программисты.

Покажите на примерах, разъясните, как работают с директивами #if,…

Не работает оператор if/elif
Задание: написать программу для решения нелинейного уравнения методом бисекции.
Код:
a = -100.0…

Как сделать if … elif … else … ?
Хочу, чтобы по кругу выполнялся блок if else, пока не станет истинным определенное выражение, но он…

Словарь с функциями вместо elif
Всем привет!
Вообщем продолжаю изучать python, и решил для одной из практик написать бота вк (но…

elif, invalid syntax, math
import math
x = int(input(‘х = ‘))
y = int(input(‘y = ‘))
if x &gt; y:
f=((x**y)+(y**x)
elif…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

10

Уведомления

  • Начало
  • » Python для новичков
  • » Чайник и оператор elif

#1 Апрель 19, 2009 20:37:28

Чайник и оператор elif

учу пайтон по пособию на одном образовательном сайте.
так вот только начал но уже ничего не ясно.

1. в примерах на сайте print печатается через кавычки, а в 3м пайтоне print работает через скобки. это что, из-за разных версий так? пособие для более старой версии пайтона?
2. есть пример:
if a < 0:
s = -1
elif a == 0:
s = 0
else:
s = 1

так вот elif у меня не работает, нет такой функции. SyntaxError: invalid syntax и elif подсвечивает красным цветом.

буду благодарен если направите в нужное русло!

Офлайн

  • Пожаловаться

#2 Апрель 19, 2009 21:20:00

Чайник и оператор elif

Да, в версии 3 print — функция. Используй 2ю ветку. Что за версия Python? В 2.5 точно есть :)

Офлайн

  • Пожаловаться

#3 Апрель 20, 2009 00:36:18

Чайник и оператор elif

версия 3

во второй работает с кавычками.

а что с elif делать не подскажете?

Офлайн

  • Пожаловаться

#4 Апрель 20, 2009 01:16:58

Чайник и оператор elif

На отступы посмотреть, например. Тут что-то совсем глупое. Все должно работать.

Офлайн

  • Пожаловаться

#5 Апрель 20, 2009 10:15:59

Чайник и оператор elif

ладно, начну с самого простого.

IDLE 2.6.2
>>> a=1
>>> b=2
>>> c=b+a
>>> print c
3

>>> if a>b:
c=a
else:

SyntaxError: invalid syntax
>>> else
SyntaxError: invalid syntax
>>> else c=b
SyntaxError: invalid syntax
>>> else: c=b
SyntaxError: invalid syntax
>>> else c = b
SyntaxError: invalid syntax
>>>

что я делаю не так?! 0_о

Офлайн

  • Пожаловаться

#6 Апрель 20, 2009 10:34:34

Чайник и оператор elif

delias
Вы что-нибудь про отступы слышали? В питоне без них никак. Блоки кода (begin-end, фигурные скобки) в питоне обозначаются отступами
т.е.

if a>b:
c = a
else:
# anything

Офлайн

  • Пожаловаться

#7 Апрель 20, 2009 11:02:50

Чайник и оператор elif

delias
ладно, начну с самого простого.

IDLE 2.6.2
>>> a=1
>>> b=2
>>> c=b+a
>>> print c
3

>>> if a>b:
c=a
else:

SyntaxError: invalid syntax
>>> else
SyntaxError: invalid syntax
>>> else c=b
SyntaxError: invalid syntax
>>> else: c=b
SyntaxError: invalid syntax
>>> else c = b
SyntaxError: invalid syntax
>>>

что я делаю не так?! 0_о

перед else отступ не нужен, после else: надо написать оператор

>>>if a > b:
c = a
else:
a = 9

Офлайн

  • Пожаловаться

#8 Апрель 20, 2009 12:06:06

Чайник и оператор elif

спасибо большое, про отступы действительно упустил

Офлайн

  • Пожаловаться

#9 Март 10, 2014 12:09:53

Чайник и оператор elif

Столкнулся с той же проблемой что и топикстартер и с отступами все в порядке было. Потом углядел что после выражения символ двоеточия забыл поставить)

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Чайник и оператор elif

На чтение 6 мин. Просмотров 36.2k. Опубликовано 03.12.2016

Набрел на занятную статью о частых ошибках на Python у начинающих программистов. Мне кажется, она полезна будет для тех, кто перешел с другого языка или только планирует переход. Далее идет перевод.

Поиск решения проблем с сообщениями об ошибках, выдаваемых при запуске программ в Python, может доставлять трудности, если вы изучаете этот язык программирования впервые. Далее будут описаны наиболее частые ошибки, встречающиеся при запуске программ и вызывающие сбой при выполнении.

1) Пропущено двоеточие в конце строки после управляющих конструкций типа if, elif, else, for, while, class, or def, что приведет к ошибке типа SyntaxError: invalid syntax

Пример кода:

if spam == 42

    print(‘Hello!’)

2) Использование = вместо == приводит к ошибке типа SyntaxError: invalid syntax

Символ = является оператором присваивания, а символ == — оператором сравнения.

Эта ошибка возникает в следующем коде:

if spam = 42:

    print(‘Hello!’)

3) Использование неправильного количества отступов.

Возникнет ошибка типа IndentationError: unexpected indent, IndentationError: unindent does not match any outer indentation level и IndentationError: expected an indented block

Нужно помнить, что отступ необходимо делать только после :, а по завершению блока обязательно вернуться к прежнему количеству отступов.

Пример ошибки:

print(‘Hello!’)

    print(‘Howdy!’)

и тут

if spam == 42:

    print(‘Hello!’)

  print(‘Howdy!’)

и тут

if spam == 42:

print(‘Hello!’)

4) Неиспользование функции len() в объявлении цикла for для списков list

Возникнет ошибка типа TypeError: ‘list’ object cannot be interpreted as an integer

Часто возникает желание пройти в цикле по индексам элементов списка или строки, при этом требуется использовать функцию range(). Нужно помнить, что необходимо получить значение len(someList) вместо самого значения someList

Ошибка возникнет в следующем коде:

spam = [‘cat’, ‘dog’, ‘mouse’]

for i in range(spam):

    print(spam[i])

Некоторые читатели (оригинальной статьи) заметили, что лучше использовать конструкцию типа for i in spam:, чем написанный код выше. Но, когда нужно получить номер итерации в цикле, использование вышенаписанного кода намного полезнее, чем получение значения списка.

От переводчика: Иногда можно ошибочно перепутать метод shape с len() для определения размера списка. При этом возникает ошибка типа ‘list’ object has no attribute ‘shape’

5) Попытка изменить часть строки. (Ошибка типа TypeError: ‘str’ object does not support item assignment)

Строки имеют неизменяемый тип. Эта ошибка произойдет в следующем коде:

spam = ‘I have a pet cat.’

spam[13] = ‘r’

print(spam)

А ожидается такое результат:

spam = ‘I have a pet cat.’

spam = spam[:13] + ‘r’ + spam[14:]

print(spam)

От переводчика: Подробней про неизменяемость строк можно прочитать тут

6) Попытка соединить нестроковую переменную со строкой приведет к ошибке TypeError: Can’t convert ‘int’ object to str implicitly

Такая ошибка произойдет тут:

numEggs = 12

print(‘I have ‘ + numEggs + ‘ eggs.’)

А нужно так:

numEggs = 12

print(‘I have ‘ + str(numEggs) + ‘ eggs.’)

или так:

numEggs = 12

print(‘I have %s eggs.’ % (numEggs))

От переводчика: еще удобно так

print(‘This {1} xorosho{0}’.format(‘!’,‘is’))

# This is xorosho!

7) Пропущена одинарная кавычка в начале или конце строковой переменной (Ошибка SyntaxError: EOL while scanning string literal)

Такая ошибка произойдет в следующем коде:

или в этом:

или в этом:

myName = ‘Al’

print(‘My name is ‘ + myName + . How are you?)

8) Опечатка в названии переменной или функции (Ошибка типа NameError: name ‘fooba’ is not defined)

Такая ошибка может встретиться в таком коде:

foobar = ‘Al’

print(‘My name is ‘ + fooba)

или в этом:

или в этом:

От переводчика: очень часто при написании возникают ошибки типа NameError: name ‘true’ is not defined и NameError: name ‘false’ is not defined, связанные с тем, что нужно писать булевные значения с большой буквы True и False

9) Ошибка при обращении к методу объекта. (Ошибка типа AttributeError: ‘str’ object has no attribute ‘lowerr’)

Такая ошибка произойдет в следующем коде:

spam = ‘THIS IS IN LOWERCASE.’

spam = spam.lowerr()

10) Попытка использовать индекс вне границ списка. (Ошибка типа IndexError: list index out of range)

Ошибка возникает в следующем коде:

spam = [‘cat’, ‘dog’, ‘mouse’]

print(spam[6])

11) Использование несуществующих ключей для словаря. (Ошибка типа KeyError: ‘spam’)

Ошибка произойдет в следующем коде:

spam = {‘cat’: ‘Zophie’, ‘dog’: ‘Basil’, ‘mouse’: ‘Whiskers’}

print(‘The name of my pet zebra is ‘ + spam[‘zebra’])

12) Использование зарезервированных в питоне ключевых слов в качестве имени для переменной. (Ошибка типа SyntaxError: invalid syntax)

Ключевые слова (зарезервированные) в питоне невозможно использовать как переменные. Пример в следующем коде:

Python 3 имеет следующие ключевые слова: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13) Использование операторов присваивания для новой неинициализированной переменной. (Ошибка типа NameError: name ‘foobar’ is not defined)

Не стоит надеяться, что переменные инициализируются при старте каким-нибудь значением типа 0 или пустой строкой.

Эта ошибка встречается в следующем коде:

spam = 0

spam += 42

eggs += 42

Операторы присваивания типа spam += 1 эквивалентны spam = spam + 1. Это означает, что переменная spam уже должна иметь какое-то значение до.

14) Использование локальных переменных, совпадающих по названию с глобальными переменными, в функции до инициализации локальной переменной. (Ошибка типа UnboundLocalError: local variable ‘foobar’ referenced before assignment)

Использование локальной переменной в функции с именем, совпадающим с глобальной переменной, опасно. Правило: если переменная в функции использовалась с оператором присвоения, это всегда локальная переменная для этой функции. В противном случае, это глобальная переменная внутри функции.

Это означает, что нельзя использовать глобальную переменную (с одинаковым именем как у локальной переменной) в функции до ее определения.

Код с появлением этой ошибки такой:

someVar = 42

def myFunction():

    print(someVar)

    someVar = 100

myFunction()

15) Попытка использовать range() для создания списка целых чисел. (Ошибка типа TypeError: ‘range’ object does not support item assignment)

Иногда хочется получить список целых чисел по порядку, поэтому range() кажется подходящей функцией для генерации такого списка. Тем не менее нужно помнить, что range() возвращает range object, а не список целых чисел.

Пример ошибки в следующем коде:

spam = range(10)

spam[4] = 1

Кстати, это работает в Python 2, так как range() возвращает список. Однако попытка выполнить код в Python 3 приведет к описанной ошибке.

Нужно сделать так:

spam = list(range(10))

spam[4] = 1

16) Отсутствие операторов инкремента ++ или декремента . (Ошибка типа SyntaxError: invalid syntax)

Если вы пришли из другого языка типа C++, Java или PHP, вы можете попробовать использовать операторы ++ или для переменных. В Питоне таких операторов нет.

Ошибка возникает в следующем коде:

Нужно написать так:

17) Как заметил читатель Luciano в комментариях к статье (оригинальной), также часто забывают добавлять self как первый параметр для метода. (Ошибка типа TypeError: myMethod() takes no arguments (1 given)

Эта ошибка возникает в следующем коде:

class Foo():

    def myMethod():

        print(‘Hello!’)

a = Foo()

a.myMethod()

Краткое объяснение различных сообщений об ошибках представлено в Appendix D of the «Invent with Python» book.

Полезные материалы

Оригинал статьи

Наиболее частые проблемы Python и решения (перевод)

Вещи, о которых следует помнить, программируя на Python

Python 3 для начинающих: Часто задаваемые вопросы

  1. Home
  2. Python Tutorial
  3. If-else statements in Python

Last updated on September 21, 2020


The programs we have written so far executes in a very orderly fashion. This is not how programs in the real world operate. Sometimes we want to execute a set of statements only when certain conditions are met. To handle these kinds of situations programming languages provide some special statements called Control Statements. In addition to controlling the flow of programs, we also use control statements to loop or skip over statements when some condition is true.

The Control Statements are of following types:

  1. if statement
  2. if-else statement
  3. if-elif-else statement
  4. while loop
  5. for loop
  6. break statement
  7. continue statement

In this lesson we are discussing the first three control statements.

if statement #

The syntax of if statement is as follows:

Syntax:

if condition:
    <indented statement 1>
    <indented statement 2>

<non-indented statement>

The first line of the statement i.e if condition: is known as if clause and the condition is a boolean expression, that is evaluated to either True or False. In the next line, we have have block of statements. A block is simply a set of one or more statements. When a block of statements is followed by if clause, it is known as if block. Notice that each statement inside the if block is indented by the same amount to the right of the if keyword. Many languages like C, C++, Java, PHP, uses curly braces ({}) to determine the start and end of the block but Python uses indentation. Each statement inside the if block must be indented by the same number of spaces. Otherwise, you will get syntax error. Python documentation recommends to indent each statement in the block by 4 spaces. We use this recommendation in all our programs throughout this course.

How it works:

When if statement executes, the condition is tested. If condition is true then all the statements inside the if block is executed. On the other hand, if the condition is false then all the statements in the if block is skipped.

The statements followed by the if clause which are not indented doesn’t belong to the if block. For example, <non-indented statement> is not the part of the if block, as a result, it will always execute no matter whether the condition in the if clause is true or false.

Here is an example:

python101/Chapter-09/if_statement.py

number = int(input("Enter a number: "))

if number > 10:
    print("Number is greater than 10")

Try it now

First Run Output:

Enter a number: 100
Number is greater than 10

Second Run Output:

Notice that in the second run when condition failed, statement inside the if block is skipped. In this example the if block consist of only one statement, but you can have any number of statements, just remember to properly indent them.

Now consider the following code:

python101/Chapter-09/if_statement_block.py

number = int(input("Enter a number: "))
if number > 10:
    print("statement 1")
    print("statement 2")
    print("statement 3")
print("Executes every time you run the program")
print("Program ends here")

Try it now

First Run Output:

Enter a number: 45
statement 1
statement 2
statement 3
Executes every time you run the program
Program ends here

Second Run Output:

Enter a number: 4
Executes every time you run the program
Program ends here

The important thing to note in this program is that only statements in line 3,4 and 5 belongs to the if block. Consequently, statements in line 3,4 and 5 will execute only when the if condition is true, on the other hand statements in line 6 and 7 will always execute no matter what.

Python shell responds somewhat differently when you type control statements inside it. Recall that, to split a statement into multiple lines we use line continuation operator (). This is not the case with control statements, Python interpreter will automatically put you in multi-line mode as soon as you hit enter followed by an if clause. Consider the following example:

>>>
>>> n = 100
>>> if n > 10:
...

Notice that after hitting Enter key followed by if clause the shell prompt changes from >>> to .... Python shell shows ... for multi-line statements, it simply means the statement you started is not yet complete.

To complete the if statement, add a statement to the if block as follows:

>>>
>>> n = 100
>>> if n > 10:
...     print("n is greater than 10")
...

Python shell will not automatically indent your code, you have to do that yourself. When you are done typing statements in the block hit enter twice to execute the statement and you will be taken back to the normal prompt string.

>>>
>>> n = 100
>>> if n > 10:
...     print("n is greater than 10")
...
n is greater than 10
>>>

The programs we have written so far ends abruptly without showing any response to the user if the condition is false. Most of the time we want to show the user a response even if the condition is false. We can easily do that using if-else statement

if-else statement #

An if-else statement executes one set of statements when the condition is true and a different set of statements when the condition is false. In this way, a if-else statement allows us to follow two courses of action. The syntax of if-else statement is as follows:

Syntax:

if condition:
    # if block
    statement 1
    statement 2
    and so on
else:
    # else block
    statement 3 
    statement 4
    and so on:

How it works:

When if-else statement executes, condition is tested if it is evaluated to True then statements inside the if block are executed. However, if the condition is False then the statements in the else block are executed.

Here is an example:

Example 1: Program to calculate area and circumference of the circle

python101/Chapter-09/calculate_circles_area_circumference.py

radius = int(input("Enter radius: "))
if radius >= 0:
    print("Circumference = ", 2 * 3.14 * radius)
    print("Area = ", 3.14 * radius ** 2 )
else:
    print("Please enter a positive number")

Try it now

First Run Output:

Enter radius: 4
Circumference =  25.12
Area =  50.24

Second Run Output:

Enter radius: -12
Please enter a positive number

Now our program shows a proper response to the user even if the condition is false which is what is wanted.

In an if-else statement always make sure that if and else clause are properly aligned. Failing to do will raise a syntax error. For example:

python101/Chapter-09/if_and_else_not_aligned.py

radius = int(input("Enter radius: "))
if radius >= 0:
    print("Circumference = ", 2 * 3.14 * radius)
    print("Area = ", 3.14 * radius ** 2 )

    else:
        print("Please enter a positive number")

Try it now

Try running the above program and you will get a syntax error like this:

q@vm:~/python101/Chapter-09$ python3 if_and_else_not_aligned.py 
  File "if_and_else_not_aligned.py", line 6
    else:
       ^
SyntaxError: invalid syntax
q@vm:~/python101/Chapter-06$

To the fix the problem, align the if and else clause vertically as follows:

radius = int(input("Enter radius: "))
if radius >= 0:
    print("Circumference = ", 2 * 3.14 * radius)
    print("Area = ", 3.14 * radius ** 2 )

else:
    print("Please enter a positive number")

Try it now

Here is another example:

Example 2: A program to check the password entered by the user

python101/Chapter-09/secret_world.py

password = input("Enter a password: ")
if password == "sshh":
    print("Welcome to the Secret World")
else:
    print("You are not allowed here")

Try it now

First Run Output:

Enter a password: sshh
Welcome to the Secret World

Second Run Output:

Enter a password: ww
You are not allowed here

Nested if and if-else statement #

We can also write if or if-else statement inside another if or if-else statement. This can be better explained through some examples:

if statement inside another if statement. #

Example 1: A program to check whether a student is eligible for loan or not

python101/Chapter-09/nested_if_statement.py

gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))

if per_grad > 70:
    # outer if block
    if gre_score > 150:
        # inner if block
        print("Congratulations you are eligible for loan")
else:
    print("Sorry, you are not eligible for loan")

Try it now

Here we have written a if statement inside the another if statement. The inner if statement is known as nested if statement. In this case the inner if statement belong to the outer if block and the inner if block has only one statement which prints "Congratulations you are eligible for loan".

How it works:

First the outer if condition is evaluated i.e per_grad > 70, if it is True then the control of the program comes inside the outer if block. In the outer if block gre_score > 150 condition is tested. If it is True then "Congratulations you are eligible for loan" is printed to the console. If it is False then the control comes out of the if-else statement to execute statements following it and nothing is printed.

On the other hand, if outer if condition is evaluated to False, then execution of statements inside the outer if block is skipped and control jumps to the else (line 9) block to execute the statements inside it.

First Run Output:

Enter your GRE score: 160
Enter percent secured in graduation: 75
Congratulations you are eligible for loan

Second Run Output:

Enter your GRE score: 160
Enter percent secured in graduation: 60
Sorry, you are not eligible for loan

This program has one small problem. Run the program again and enter gre_score less than 150 and per_grad greater than 70 like this:

Output:

Enter your GRE score: 140
Enter percent secured in graduation: 80

As you can see program doesn’t output anything. This is because our nested if statement doesn’t have an else clause. We are adding an else clause to the nested if statement in the next example.

Example 2: if-else statement inside another if statement.

python101/Chapter-09/nested_if_else_statement.py

gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))

if per_grad > 70:
    if gre_score > 150:
        print("Congratulations you are eligible for loan.")
    else:
        print("Your GRE score is no good enough. You should retake the exam.")
else:
    print("Sorry, you are not eligible for loan.")

Try it now

Output:

Enter your GRE score: 140
Enter percent secured in graduation: 80
Your GRE score is no good enough. You should retake the exam.

How it works:

This program works exactly like the above, the only difference is that here we have added an else clause corresponding to the nested if statement. As a result, if you enter a GRE score smaller than 150 the program would print «Your GRE score is no good enough. You should retake the exam.» instead of printing nothing.

When writing nested if or if-else statements always remember to properly indent all the statements. Otherwise you will get a syntax error.

if-else statement inside else clause. #

Example 3: A program to determine student grade based upon marks entered.

python101/Chapter-09/testing_multiple_conditions.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
score = int(input("Enter your marks: "))

if score >= 90:
    print("Excellent ! Your grade is A")
else:
    if score >= 80:
        print("Great ! Your grade is B")
    else:
        if score >= 70:
            print("Good ! Your grade is C")
        else:
            if score >= 60:
                print("Your grade is D. You should work hard on you subjects.")
            else:
                print("You failed in the exam")

Try it now

First Run Output:

Enter your marks: 92
Excellent ! Your grade is A

Second Run Output:

Enter your marks: 75
Good ! Your grade is C

Third Run Output:

Enter your marks: 56
You failed in the exam

How it works:

When program control comes to the if-else statement, the condition (score >= 90) in line 3 is tested. If the condition is True, "Excellent ! Your grade is A" is printed to the console. If the condition is false, the control jumps to the else clause in line 5, then the condition score >= 80 (line 6) is tested. If it is true then "Great ! Your grade is B" is printed to the console. Otherwise, the program control jumps to the else clause in the line 8. Again we have an else block with nested if-else statement. The condition (score >= 70) is tested. If it is True then "Good ! Your grade is C" is printed to the console. Otherwise control jumps again to the else block in line 11. At last, the condition (score >= 60) is tested, If is True then "Your grade is D. You should work hard on you subjects." is printed to the console. On the other hand, if it is False, "You failed the exam" is printed to the console. At this point, the control comes out of the outer if-else statement to execute statements following it.

Although nested if-else statement allows us to test multiple conditions but they are fairly complex to read and write. We can make the above program much more readable and simple using if-elif-else statement.

if-elif-else statement #

If-elif-else statement is another variation of if-else statement which allows us to test multiple conditions easily instead of writing nested if-else statements. The syntax of if-elif-else statement is as follows:

Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
if condition_1: 
    # if block
    statement
    statement   
    more statement
elif condition_2:
    # 1st elif block
    statement
    statement
    more statement
elif condition_3:   
    # 2nd elif block
    statement
    statement
    more statement

...

else    
    statement
    statement
    more statement

... means you means you can write as many elif clauses as necessary.

How it works:

When if-elif-else statement executes, the condition_1 is tested first. If the condition found to be true, then the statements in the if block is executed. The conditions and statements in the rest of the structure is skipped and control comes out of the if-elif-else statement to execute statements following it.

If condition_1 is false the program control jumps to the next elif clause and condition_2 is tested. If condition_2 is true the statements in the 1st elif block is executed. The conditions and statements in the rest of the if-elif-else structure is skipped and control comes out of the if-elif-statement to execute statements following it.

This process keeps repeating until an elif clause is found to be true. In case no elif clause found to be true then at last the block of statements in the else block is executed.

Let’s rewrite the above program using if-elif-statement.

python101/Chapter-09/if_elif_else_statement.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
score = int(input("Enter your marks: "))

if score >= 90:
    print("Excellent! Your grade is A")
elif score >= 80:
    print("Great! Your grade is B")
elif score >= 70:
    print("Good! Your grade is C")
elif score >= 60:
    print("Your grade is D. You should work hard on you studies.")
else:
    print("You failed in the exam")

Try it now

First run output:

Enter your marks: 78
Good ! Your grade is C

Second run output:

Enter your marks: 91
Excellent! Your grade is A

Third run output:

Enter your marks: 55
You failed in the exam

As you can see the above program is quite easy to read and understand unlike it’s nested equivalent.



Ezoic

Программирование, Python, Учебный процесс в IT, Блог компании SkillFactory


Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

image

Выяснить, что означают сообщения об ошибках Python, может быть довольно сложно, когда вы впервые изучаете язык. Вот список распространенных ошибок, которые приводят к сообщениям об ошибках во время выполнения, которые могут привести к сбою вашей программы.

1) Пропуск “:” после оператора if, elif, else, for, while, class или def. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Пример кода с ошибкой:

if spam == 42

    print('Hello!')

2) Использование = вместо ==. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

= является оператором присваивания, а == является оператором сравнения «равно». Пример кода с ошибкой:

if spam = 42:

    print('Hello!')

3) Использование неправильного количества отступов. (Сообщение об ошибке: «IndentationError: unexpected indent» и «IndentationError: unindent does not match any outer indentation level» и «IndentationError: expected an indented block»)

Помните, что отступ увеличивается только после оператора, оканчивающегося на “:” двоеточие, и впоследствии должен вернуться к предыдущему отступу.
Пример кода с ошибкой:

print('Hello!')

    print('Howdy!')

… еще:

if spam == 42:

    print('Hello!')

  print('Howdy!')

… еще:

if spam == 42:

print('Hello!')

4) Забыть вызвать len() в операторе цикла for. (Сообщение об ошибке: “TypeError: 'list' object cannot be interpreted as an integer”)

Обычно вы хотите перебирать индексы элементов в списке или строке, что требует вызова функции range(). Просто не забудьте передать возвращаемое значение len(someList) вместо передачи только someList.

Пример кода с ошикой:

spam = ['cat', 'dog', 'mouse']

for i in range(spam):

    print(spam[i])

(UPD: как некоторые указали, вам может понадобиться только for i in spam: вместо приведенного выше кода. Но вышесказанное относится к очень законному случаю, когда вам нужен индекс в теле цикла, а не только само значение.)

5) Попытка изменить строковое значение. (Сообщение об ошибке: “TypeError: 'str' object does not support item assignment”)

Строки являются неизменным типом данных. Пример кода с ошибкой:

spam = 'I have a pet cat.'

spam[13] = 'r'

print(spam)

Пример правильного варианта:

spam = 'I have a pet cat.'

spam = spam[:13] + 'r' + spam[14:]

print(spam)

6) Попытка объединить не строковое значение в строковое значение. (Сообщение об ошибке: “TypeError: Can't convert 'int' object to str implicitly”)

Пример кода с ошибкой:

numEggs = 12
print('I have ' + numEggs + ' eggs.')
Правильный вариант:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

… или:

numEggs = 12
print('I have %s eggs.' % (numEggs))

7) Пропуск кавычки, в начале или конце строкового значения. (Сообщение об ошибке: “SyntaxError: EOL while scanning string literal”)

Пример кода с ошикой:

print(Hello!')

… еще:

print('Hello!)
...еще:
myName = 'Al'
print('My name is ' + myName + . How are you?')

8) Опечатка в переменной или имени функции. (Сообщение об ошибке: “NameError: name 'fooba' is not defined”)

Пример кода с ошибкой:

foobar = 'Al'
print('My name is ' + fooba)
...еще:
spam = ruond(4.2)
...еще:
spam = Round(4.2)

9) Опечатка в названии метода. (Сообщение об ошибке: “AttributeError: 'str' object has no attribute 'lowerr'”)

Пример кода с ошибкой:

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()

10) Выход за пределы массива. (Сообщение об ошибке: “IndexError: list index out of range”)

Пример кода с ошибкой:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11) Использование несуществующего ключа словаря. (Сообщение об ошибке: “KeyError: 'spam'”)

Пример кода с ошибкой:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12) Попытка использовать ключевые слова Python в качестве переменной (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Ключевые слова Python (также называются зарезервированные слова) не могут быть использованы для названия переменных. Ошибка будет со следующим кодом:

class = 'algebra'

Ключевые слова Python 3: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13) Использование расширенного оператора присваивания для новой переменной. (Сообщение об ошибке: “NameError: name 'foobar' is not defined”)

Не думайте, что переменные начинаются со значения, такого как 0 или пустая строка. Выражение с расширенным оператором как spam += 1 эквивалентно spam = spam + 1. Это означает, что для начала в spam должно быть какое-то значение.

Пример кода с ошибкой:

spam = 0
spam += 42
eggs += 42

14) Использование локальных переменных (с таким же именем как и у глобальной переменной) в функции до назначения локальной переменной. (Сообщение об ошибке: “UnboundLocalError: local variable 'foobar' referenced before assignment”)

Использовать локальную переменную в функции, имя которой совпадает с именем глобальной переменной, довольно сложно. Правило таково: если переменной в функции когда-либо назначается что-то, она всегда является локальной переменной, когда используется внутри этой функции. В противном случае, это глобальная переменная внутри этой функции.
Это означает, что вы не можете использовать ее как глобальную переменную в функции до ее назначения.

Пример кода с ошибкой:

someVar = 42
def myFunction():
    print(someVar)
    someVar = 100
myFunction()

15) Попытка использовать range() для создания списка целых чисел. (Сообщение об ошибке: “TypeError: 'range' object does not support item assignment”)

Иногда вам нужен список целочисленных значений по порядку, поэтому range() кажется хорошим способом создать этот список. Однако вы должны помнить, что range() возвращает «объект диапазона», а не фактическое значение списка.

Пример кода с ошибкой:

spam = range(10)
spam[4] = -1
То что вы хотите сделать, выглядит так:
spam = list(range(10))
spam[4] = -1

(UPD: Это работает в Python 2, потому что Python 2’s range() возвращает список значений. Но, попробовав сделать это в Python 3, вы увидите ошибку.)

16) Нет оператора ++ инкремента или -- декремента. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Если вы пришли из другого языка программирования, такого как C++, Java или PHP, вы можете попытаться увеличить или уменьшить переменную с помощью ++ или --. В Python таких операторов нет.

Пример кода с ошибкой:

spam = 0
spam++
То что вы хотите сделать, выглядит так:
spam = 0
spam += 1

17) UPD: как указывает Luchano в комментариях, также часто забывают добавить self в качестве первого параметра для метода. (Сообщение об ошибке: «TypeError: TypeError: myMethod() takes no arguments (1 given)»)

Пример кода с ошибкой:

class Foo():
    def myMethod():
        print('Hello!')
a = Foo()
a.myMethod()

Краткое объяснение различных сообщений об ошибках приведено в Приложении D книги «Invent with Python».


image
Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:

  • Курс «Профессия Data Scientist» (24 месяца)
  • Курс «Профессия Data Analyst» (18 месяцев)
  • Курс «Python для веб-разработки» (9 месяцев)

Читать еще

  • 450 бесплатных курсов от Лиги Плюща
  • Бесплатные курсы по Data Science от Harvard University
  • 30 лайфхаков чтобы пройти онлайн-курс до конца
  • Самый успешный и самый скандальный Data Science проект: Cambridge Analytica

Понравилась статья? Поделить с друзьями:
  • Elicenser pos error message logic
  • Elicenser control error что делать
  • Elicenser control center error
  • Elf interpreter libexec ld elf so 1 not found error 8
  • Elex как изменить язык