Lesson 3 условия: if-then-else
Содержание:
- When «else condition» does not work
- How to use «elif» condition
- How to execute conditional statement with minimal code
- Python Nested if Statement
- Switch Case Statement in Python
- Одиночные проверки
- Nested if and if-else statement #
- Способы реализации тернарного оператора Python
- Python Compound If Statement Example
- Оператор if Python — пример
- Сравнение строк
- Python Nested if Statement
- Switch Case Statement in Python
- Примеры решения задач
- Python if else in one line
- Сложные логические выражения
- Оператор Python if … else
- Python nested if..else in one line
- 4.4. break and continue Statements, and else Clauses on Loops¶
- Python if else Command Example
When «else condition» does not work
There might be many instances when your «else condition» won’t give you the desired result. It will print out the wrong result as there is a mistake in program logic. In most cases, this happens when you have to justify more than two statement or condition in a program.
An example will better help you to understand this concept.
Here both the variables are same (8,8) and the program output is «x is greater than y», which is WRONG. This is because it checks the first condition (if condition in Python), and if it fails, then it prints out the second condition (else condition) as default. In next step, we will see how we can correct this error.
# #Example file for working with conditional statement # def main(): x,y =8,8 if(x
How to use «elif» condition
To correct the previous error made by «else condition», we can use «elif» statement. By using «elif» condition, you are telling the program to print out the third condition or possibility when the other condition goes wrong or incorrect.
Example
# #Example file for working with conditional statement # def main(): x,y =8,8 if(x
- Code Line 5: We define two variables x, y = 8, 8
- Code Line 7: The if Statement checks for condition x<y which is False in this case
- Code Line 10: The flow of program control goes to the elseif condition. It checks whether x==y which is true
- Code Line 11: The variable st is set to «x is same as y.»
- Code Line 15: The flow of program control exits the if Statement (it will not get to the else Statement). And print the variable st. The output is «x is same as y» which is correct
How to execute conditional statement with minimal code
In this step, we will see how we can condense out the conditional statement. Instead of executing code for each condition separately, we can use them with a single code.
Syntax
A If B else C
Example:
def main(): x,y = 10,8 st = "x is less than y" if (x
- Code Line 2: We define two variables x, y = 10, 8
- Code Line 3: Variable st is set to «x is less than y «if x<y or else it is set to «x is greater than or equal to y». In this x>y variable st is set to «x is greater than or equal to y.»
- Code Line 4: Prints the value of st and gives the correct output
Instead of writing long code for conditional statements, Python gives you the freedom to write code in a short and concise way.
Python Nested if Statement
Following example demonstrates nested if Statement Python
total = 100
#country = "US"
country = "AU"
if country == "US":
if total
Uncomment Line 2 in above code and comment Line 3 and run the code again
Switch Case Statement in Python
What is Switch statement?
A switch statement is a multiway branch statement that compares the value of a variable to the values specified in case statements.
Python language doesn’t have a switch statement.
Python uses dictionary mapping to implement Switch Case in Python
Example
function(argument){
switch(argument) {
case 0:
return "This is Case Zero";
case 1:
return " This is Case One";
case 2:
return " This is Case Two ";
default:
return "nothing";
};
};
For the above Switch case in Python
def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")
if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))
Python 2 Example
Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.
# If Statement #Example file for working with conditional statement # def main(): x,y =2,8 if(x
Summary:
A conditional statement in Python is handled by if statements and we saw various other ways we can use conditional statements like Python if else over here.
- «if condition» – It is used when you need to print out the result when one of the conditions is true or false.
- «else condition»- it is used when you want to print out the statement when your one condition fails to meet the requirement
- «elif condition» – It is used when you have third possibility as the outcome. You can use multiple elif conditions to check for 4th,5th,6th possibilities in your code
- We can use minimal code to execute conditional statements by declaring all condition in single statement to run the code
- Python If Statement can be nested
Одиночные проверки
Внутри условия
можно прописывать и такие одиночные выражения:
x = 4; y = True; z = False
if(x): print("x = ", x, " дает true")
if(not ): print("0 дает false")
if("0"): print("строка 0 дает true")
if(not ""): print("пустая строка дает false")
if(y): print("y = true дает true")
if(not z): print("z = false дает false")
Вот этот оператор
not – это отрицание
– НЕ, то есть, чтобы проверить, что 0 – это false мы
преобразовываем его в противоположное состояние с помощью оператора отрицания
НЕ в true и условие
срабатывает. Аналогично и с переменной z, которая равна false.
Из этих примеров
можно сделать такие выводы:
-
Любое число,
отличное от нуля, дает True. Число 0 преобразуется в False. -
Пустая строка –
это False, любая другая
строка с символами – это True. - С помощью
оператора not можно менять
условие на противоположное (в частности, False превращать в True).
Итак, в условиях
мы можем использовать три оператора: and, or и not. Самый высокий
приоритет у операции not, следующий приоритет имеет операция and и самый
маленький приоритет у операции or. Вот так работает оператор if в Python.
Видео по теме
Python 3 #1: установка и запуск интерпретатора языка
Python 3 #2: переменные, оператор присваивания, типы данных
Python 3 #3: функции input и print ввода/вывода
Python 3 #4: арифметические операторы: сложение, вычитание, умножение, деление, степень
Python 3 #5: условный оператор if, составные условия с and, or, not
Python 3 #6: операторы циклов while и for, операторы break и continue
Python 3 #7: строки — сравнения, срезы строк, базовые функции str, len, ord, in
Python 3 #8: методы строк — upper, split, join, find, strip, isalpha, isdigit и другие
Python 3 #9: списки list и функции len, min, max, sum, sorted
Python 3 #10: списки — срезы и методы: append, insert, pop, sort, index, count, reverse, clear
Python 3 #11: списки — инструмент list comprehensions, сортировка методом выбора
Python 3 #12: словарь, методы словарей: len, clear, get, setdefault, pop
Python 3 #13: кортежи (tuple) и операции с ними: len, del, count, index
Python 3 #14: функции (def) — объявление и вызов
Python 3 #15: делаем «Сапер», проектирование программ «сверху-вниз»
Python 3 #16: рекурсивные и лямбда-функции, функции с произвольным числом аргументов
Python 3 #17: алгоритм Евклида, принцип тестирования программ
Python 3 #18: области видимости переменных — global, nonlocal
Python 3 #19: множества (set) и операции над ними: вычитание, пересечение, объединение, сравнение
Python 3 #20: итераторы, выражения-генераторы, функции-генераторы, оператор yield
Python 3 #21: функции map, filter, zip
Python 3 #22: сортировка sort() и sorted(), сортировка по ключам
Python 3 #23: обработка исключений: try, except, finally, else
Python 3 #24: файлы — чтение и запись: open, read, write, seek, readline, dump, load, pickle
Python 3 #25: форматирование строк: метод format и F-строки
Python 3 #26: создание и импорт модулей — import, from, as, dir, reload
Python 3 #27: пакеты (package) — создание, импорт, установка (менеджер pip)
Python 3 #28: декораторы функций и замыкания
Python 3 #29: установка и порядок работы в PyCharm
Python 3 #30: функция enumerate, примеры использования
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
1 2 3 4 5 6 7 8 9 10 |
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")
|
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 .
How it works:
First the outer if condition is evaluated i.e , if it is then the control of the program comes inside the outer if block. In the outer if block condition is tested. If it is then is printed to the console. If it is 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 , 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:
1 2 3 |
Enter your GRE score: 160 Enter percent secured in graduation: 75 Congratulations you are eligible for loan |
Second Run Output:
1 2 3 |
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 less than and greater than like this:
Output:
1 2 |
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
1 2 3 4 5 6 7 8 9 10 |
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.")
|
Output:
1 2 3 |
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")
|
First Run Output:
1 2 |
Enter your marks: 92 Excellent ! Your grade is A |
Second Run Output:
1 2 |
Enter your marks: 75 Good ! Your grade is C |
Third Run Output:
1 2 |
Enter your marks: 56 You failed in the exam |
How it works:
When program control comes to the if-else statement, the condition in line 3 is tested. If the condition is , is printed to the console. If the condition is false, the control jumps to the else clause in line 5, then the condition (line 6) is tested. If it is true then 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 is tested. If it is True then is printed to the console. Otherwise control jumps again to the else block in line 11. At last, the condition is tested, If is then is printed to the console. On the other hand, if it is False, 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.
Способы реализации тернарного оператора Python
Есть разные способы реализации тернарного оператора Python. Мы можем реализовать тернарный оператор Python, используя кортежи, словари и лямбда-функции. Давайте реализуем тернарный оператор с помощью кортежа. Мы создали две числовые переменные num1 и num2 и сохранили случайные числа в этих переменных. Случайные числа в Python создаются с помощью функции random(). Функция random() присутствует в модуле random.
import random num1=random.random() num2=random.random() #реализация тернарного оператора print((num1, num2) )
По выходным данным мы не можем определить, что это значение num1 или num2. Давайте реализуем приведенный выше код следующим образом:
import random
num1=random.random()
num2=random.random()
print((f"num1:{num1}", f"num2:{num2}") )
Хорошо! Теперь давайте реализуем тернарный оператор, используя словарь Python и лямбда-функцию.
import random
num1=random.random()
num2=random.random()
#использование словаря Python
print("Использование словаря Python:")
print(({True:f"num1:{num1}",False:f"num2:{num2}"}))
#использование лямбда-функции
print("Использование лямбда-функции:")
print((lambda: f"num1:{num1}", lambda: f"num2:{num2}")())
Python Compound If Statement Example
The following example shows how you can use compound conditional commands in the if statement.
# cat if7.py
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a < b < c:
print("Success. a < b < c")
In the above:
The print block will get executed only when the if condition is true. Here, we are using a compound expression for the if statement where it will be true only when a is less than b and b is less than c.
The following is the output when if condition becomes true.
# python if7.py Enter a: 10 Enter b: 20 Enter c: 30 Success. a < b < c
The following is the output when if condition becomes false.
# python if7.py Enter a: 10 Enter b: 10 Enter c: 20
Оператор if Python — пример
# Если число положительное, мы выводим соответствующее сообщение
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is alwaysprinted.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is alsoalwaysprinted.")
Результат работы кода:
3 is a positive number This is alwaysprinted This is alsoalwaysprinted.
В приведенном выше примере num > 0— это тестовое выражение. Тело if выполняется только в том случае, если оно равно True.
Когда переменная num равна 3, тестовое выражение истинно, и операторы внутри тела if выполняются. Если переменная num равна -1, тестовое выражение не истинно, а операторы внутри тела if пропускаются.
Оператор print() расположен за пределами блока if (не определен). Следовательно, он выполняется независимо от тестового выражения.
Сравнение строк
Как вы видите,
сравнение двух числовых значений выполняется вполне очевидным образом. Но можно
ли, например, сравнивать строки между собой? Оказывается да, можно. Чтобы
определить, что одна строка больше другой, Python использует
«алфавитный» или «лексикографический» порядок. Другими словами, строки сравниваются
посимвольно. Например:
print('Я' > 'А' )
print( 'Кот' > 'Код' )
print( 'Сонный' > 'Сон' )
Алгоритм
сравнения двух строк довольно прост:
-
Сначала
сравниваются первые символы строк. -
Если первый
символ первой строки больше (меньше), чем первый символ второй, то первая
строка больше (меньше) второй. - Если первые
символы равны, то таким же образом сравниваются уже вторые символы строк.
Сравнение
продолжается, пока не закончится одна из строк. Если обе строки заканчиваются
одновременно, и все их соответствующие символы равны между собой, то строки считаются
равными. Иначе, большей считается более длинная строка.
В примерах выше
сравнение ‘Я’ > ‘А’ завершится на первом шаге, тогда как строки
«Кот» и «Код» будут сравниваться посимвольно:
- К равна К.
- о равна о.
- т больше чем д.
Python Nested if Statement
Following example demonstrates nested if Statement Python
total = 100
#country = "US"
country = "AU"
if country == "US":
if total
Uncomment Line 2 in above code and comment Line 3 and run the code again
Switch Case Statement in Python
What is Switch statement?
A switch statement is a multiway branch statement that compares the value of a variable to the values specified in case statements.
Python language doesn’t have a switch statement.
Python uses dictionary mapping to implement Switch Case in Python
Example
function(argument){
switch(argument) {
case 0:
return "This is Case Zero";
case 1:
return " This is Case One";
case 2:
return " This is Case Two ";
default:
return "nothing";
};
};
For the above Switch case in Python
def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")
if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))
Python 2 Example
Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.
# If Statement #Example file for working with conditional statement # def main(): x,y =2,8 if(x
Summary:
A conditional statement in Python is handled by if statements and we saw various other ways we can use conditional statements like Python if else over here.
- «if condition» – It is used when you need to print out the result when one of the conditions is true or false.
- «else condition»- it is used when you want to print out the statement when your one condition fails to meet the requirement
- «elif condition» – It is used when you have third possibility as the outcome. You can use multiple elif conditions to check for 4th,5th,6th possibilities in your code
- We can use minimal code to execute conditional statements by declaring all condition in single statement to run the code
- Python If Statement can be nested
Примеры решения задач
Проверить является ли клетка шахматной доски белой
# Два числа выбираются случайным образом (координаты клетки шахматного поля, от 1 до 8)
# Вывести YES, если клетка белая, и NO, если клетка черная
from random import randint
x = randint(1,8)
y = randint(1,8)
print(x, y)
if (x + y) % 2 == 1:
print(‘YES’)
else:
print(‘NO’)
Во втором случаем числа вводятся с клавиатуры
x = int(input(‘Введите координату x: ‘))
y = int(input(‘Введите координату y: ‘))
if (x + y) % 2 == 1:
print(‘YES’)
else:
print(‘NO’)
Проверить может ли слон ходить с первой шахматной на вторую
# Четыре числа выбираются случайным образом (координаты клетки шахматного поля, от 1 до 8)
# Вывести YES, если ладья может сходить с первой клетки на вторую, и NO, если не может
# Напомню, что ладья ходит так:
# Л ——X
# |
# |
# |
# X
from random import randint
x1 = randint(1, 8)
x2 = randint(1, 8)
y1 = randint(1, 8)
y2 = randint(1, 8)
print(x1, y1)
print(x2, y2)
if x1 == x2 and y1 != y2 or x1 != x2 and y1 == y2:
print(‘YES’)
else:
print(‘NO’)
То же самое, но с помощью ввода с клавиатуры
x1 = int(input(‘Введите координату x1: ‘))
x2 = int(input(‘Введите координату y1: ‘))
y1 = int(input(‘Введите координату x2: ‘))
y2 = int(input(‘Введите координату y2: ‘))
if x1 == x2 and y1 != y2 or x1 != x2 and y1 == y2:
print(‘YES’)
else:
print(‘NO’)
Python if else in one line
Syntax
The general syntax of single if and else statement in Python is:
if condition: value_when_true else: value_when_false
Now if we wish to write this in one line using ternary operator, the syntax would be:
value_when_true if condition else value_when_false
In this syntax, first of all the is evaluated.
- If condition returns then is returned
- If condition returns then is returned
Similarly if you had a variable assigned in the general based on the condition
Advertisement
if condition:
value = true-expr
else:
value = false-expr
The same can be written in single line:
value = true-expr if condition else false-expr
Here as well, first of all the condition is evaluated.
- if condition returns then is assigned to value object
- if condition returns then is assigned to value object
For simple cases like this, I find it very nice to be able to express that logic in one line instead of four. Remember, as a coder, you spend much more time reading code than writing it, so Python’s conciseness is invaluable.
Some important points to remember:
- You can use a ternary expression in Python, but only for expressions, not for statements
- You cannot use Python block in one line.
- The name “ternary” means there are just 3 parts to the operator: , , and .
- Although there are hacks to modify into and then use it in single line but that can be complex depending upon conditions and should be avoided
- With , only one of the expressions will be executed.
- While it may be tempting to always use ternary expressions to condense your code, realise that you may sacrifice readability if the condition as well as the true and false expressions are very complex.
Python Script Example
This is a simple script where we use comparison operator in our if condition
- First collect user input in the form of integer and store this value into
- If is greater than or equal to then return “” which will be condition
- If returns i.e. above condition was not success then return ““
- The final returned value i.e. either “” or “” is stored in object
- Lastly print the value of value
#!/usr/bin/env python3
b = int(input("Enter value for b: "))
a = "positive" if b >= else "negative"
print(a)
The multi-line form of this code would be:
#!/usr/bin/env python3
b = int(input("Enter value for b: "))
if b >= :
a = "positive"
else:
a = "negative"
print(a)
Output:
# python3 /tmp/if_else_one_line.py Enter value for b: 10 positive # python3 /tmp/if_else_one_line.py Enter value for b: -10 negative
Сложные логические выражения
Логические выражения типа являются простыми, так как в них выполняется только одна логическая операция. Однако, на практике нередко возникает необходимость в более сложных выражениях. Может понадобиться получить ответа «Да» или «Нет» в зависимости от результата выполнения двух простых выражений. Например, «на улице идет снег или дождь», «переменная news больше 12 и меньше 20″.
В таких случаях используются специальные операторы, объединяющие два и более простых логических выражения. Широко используются два оператора – так называемые логические И (and) и ИЛИ (or).
Чтобы получить при использовании оператора , необходимо, чтобы результаты обоих простых выражений, которые связывает данный оператор, были истинными. Если хотя бы в одном случае результатом будет , то и все сложное выражение будет ложным.
Чтобы получить при использовании оператора , необходимо, чтобы результат хотя бы одного простого выражения, входящего в состав сложного, был истинным. В случае оператора сложное выражение становится ложным лишь тогда, когда ложны оба составляющие его простые выражения.
Допустим, переменной x было присвоено значение 8 (), переменной y присвоили 13 (). Логическое выражение будет выполняться следующим образом. Сначала выполнится выражение . Его результатом будет . Затем выполнится выражение . Его результатом будет . Далее выражение сведется к , что вернет .
>>> x = 8 >>> y = 13 >>> y < 15 and x > 8 False
Если бы мы записали выражение так: , то оно также вернуло бы . Однако сравнение не выполнялось бы интерпретатором, так как его незачем выполнять. Ведь первое простое логическое выражение () уже вернуло ложь, которая, в случае оператора , превращает все выражение в ложь.
В случае с оператором второе простое выражение проверяется, если первое вернуло ложь, и не проверяется, если уже первое вернуло истину
Так как для истинности всего выражения достаточно единственного , неважно по какую сторону от оно стоит
>>> y < 15 or x > 8 True
В языке Python есть еще унарный логический оператор , то есть отрицание. Он превращает правду в ложь, а ложь в правду. Унарный он потому, что применяется к одному выражению, стоящему после него, а не справа и слева от него как в случае бинарных и .
>>> not y < 15 False
Здесь возвращает . Отрицая это, мы получаем .
>>> a = 5 >>> b = 0 >>> not a False >>> not b True
Число 5 трактуется как истина, отрицание истины дает ложь. Ноль приравнивается к . Отрицание дает .
Оператор Python if … else
Синтаксис if … else
if тестовое выражение:
тело if
else:
тело else
Оператор if..else оценивает тестовое выражение и выполняет тело if, только если условие равно True. Если условие равно False, выполняется тело else. Для разделения блоков используются отступы.
Python if else — примеры
# Программа проверяет, является ли число положительным или отрицательным
# и отображает соответствующее выражение
num = 3
# Также попробуйте следующие два варианта.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
В приведенном выше примере, когда num равно 3, тестовое выражение истинно и выполняется тело if, а тело else пропускается.
Если num равно -5, тестовое выражение является ложным и выполняется блок else, а тело if пропускается.
Если num равно 0, тестовое выражение истинно и выполняется блок if, а тело else пропускается.
Python nested if..else in one line
We can also use ternary expression to define on one line with Python.
Syntax
If you have a multi-line code using , something like this:
if condition1:
expr1
elif condition-m:
expr-m
else:
if condition3:
expr3
elif condition-n:
expr-n
else:
expr5
The one line syntax to use this in Python would be:
expr1 if condition1 else expr2 if condition 2 else (expr3 if condition3 else expr4 if condition 4 else expr5)
Here, we have added nested inside the using ternary expression. The sequence of the check in the following order
- If returns then is returned, if it returns then next condition is checked
- If returns then is returned, if it returns then with is checked
- If returns then is returned, if it returns then next condition inside the is returned
- If returns then is returned, if it returns then is returned from the condition
Python Script Example
In this example I am using inside the of our one liner. The order of execution will be in the provided sequence:
- First of all collect integer value of from the end user
- If the value of is equal to 100 then the condition returns and “” is returned
- If the value of is equal to 50 then the condition returns and “” is returned
- If both and condition returns then the is executed where we have condition
- Inside the , if is greater than 100 then it returns “” and if it returns then “” is returned
#!/usr/bin/env python3
b = int(input("Enter value for b: "))
a = "equal to 100" if b == 100 else "equal to 50" if b == 50 else ("greater than 100" if b > 100 else "less than 100")
print(a)
The multi-line form of this code would be:
#!/usr/bin/env python3
b = int(input("Enter value for b: "))
if b == 100:
a = "equal to 100"
elif b == 50:
a = "equal to 50"
else:
if b > 100:
a = "greater than 100"
else:
a = "less than 100"
print(a)
Output:
# python3 /tmp/if_else_one_line.py Enter value for b: 10 less than 100 # python3 /tmp/if_else_one_line.py Enter value for b: 100 equal to 100 # python3 /tmp/if_else_one_line.py Enter value for b: 50 equal to 50 # python3 /tmp/if_else_one_line.py Enter value for b: 110 greater than 100
4.4. break and continue Statements, and else Clauses on Loops¶
The statement, like in C, breaks out of the innermost enclosing
or loop.
Loop statements may have an clause; it is executed when the loop
terminates through exhaustion of the iterable (with ) or when the
condition becomes false (with ), but not when the loop is
terminated by a statement. This is exemplified by the
following loop, which searches for prime numbers:
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == ... print(n, 'equals', x, '*', n//x) ... break ... else ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
(Yes, this is the correct code. Look closely: the clause belongs to
the loop, not the statement.)
When used with a loop, the clause has more in common with the
clause of a statement than it does with that of
statements: a statement’s clause runs
when no exception occurs, and a loop’s clause runs when no
occurs. For more on the statement and exceptions, see
.
The statement, also borrowed from C, continues with the next
iteration of the loop:
Python if else Command Example
The following example shows how to use if..else command in Python.
# cat if4.py
days = int(input("How many days are in March?: "))
if days == 31:
print("You passed the test.")
else:
print("You failed the test.")
print("Thank You!")
In the above example:
- 1st line: Here, we are asking for user input. The input will be an integer, which will be stored in the variable days.
- 2nd line: This is the if command, where we are comparing whether the value of the variable days is equal to the numerical value 31. The colon at the end is part of the if command syntax, which should be given.
- 3rd line: This line starts with two space indent at the beginning. Any line (one or more) that follows the if statement, which has similar indentation at the beginning is considered part of the if statement block true condition.
- 4th line: This has the else keyword for this if block. The colon at the end is part of the if..else command syntax, which should be given.
- 5th line: This line starts with two space indent at the beginning. Any line (one or more) that follows the else statement, which has similar indentation at the beginning is considered part of the if statement block false condition.
- 6th line: This line is outside the if statement block. So, this will get executed whether the if statement is true or false.
The following example is also similar to above example, but this if..else uses string variable for comparision.
# cat if5.py
code = raw_input("What is the 2-letter state code for California?: ")
if code == 'CA':
print("You passed the test.")
else:
print("You failed the test.")
print("Thank You!")
The following is the output of the above examples, when the if statement condition is false. i.e The else block will get executed here.
# python if4.py How many days are in March?: 30 You failed the test. Thank You! # python if5.py What is the 2-letter state code for California?: NV You failed the test. Thank You!


