- Python Control Flow Statements and Loops
- Table of contents
- Control Flow Statements
- Conditional statements
- Iterative statements
- Transfer statements
- If statement in Python
- If – else statement
- Chain multiple if statement in Python
- Nested if-else statement
- Single statement suites
- for loop in Python
- While loop in Python
- Continue statement in python
- Pass statement in Python
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Python. Урок 5. Условные операторы и циклы
- Условный оператор ветвления if
- 1. Конструкция if
- 2. Конструкция if – else
- 3. Конструкция if – elif – else
- Оператор цикла while
- Операторы break и continue
- Оператор цикла for
- P.S.
- Python. Урок 5. Условные операторы и циклы : 41 комментарий
Python Control Flow Statements and Loops
In Python programming, flow control is the order in which statements or blocks of code are executed at runtime based on a condition.
Table of contents
Control Flow Statements
The flow control statements are divided into three categories
Conditional statements
In Python, condition statements act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition. Condition statements always evaluate to either True or False.
There are three types of conditional statements.
Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the condition is True. We also call it a loop statements.
Python provides us the following two loop statement to perform some actions repeatedly
Let’s learn each one of them with the examples
Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain manner. For this purpose, we use three types of transfer statements.
If statement in Python
In control statements, The if statement is the simplest form. It takes a condition and evaluates to either True or False .
If the condition is True , then the True block of code will be executed, and if the condition is False, then the block of code is skipped, and The controller moves to the next line
Syntax of the if statement
if condition: statement 1 statement 2 statement n
Let’s see the example of the if statement. In this example, we will calculate the square of a number if it greater than 5
number = 6 if number > 5: # Calculate square print(number * number) print('Next lines of code')
If – else statement
The if-else statement checks the condition and executes the if block of code when the condition is True, and if the condition is False, it will execute the else block of code.
Syntax of the if-else statement
if condition: statement 1 else: statement 2
If the condition is True , then statement 1 will be executed If the condition is False , statement 2 will be executed. See the following flowchart for more detail.
password = input('Enter password ') if password == "PYnative@#29": print("Correct password") else: print("Incorrect Password")
Enter password PYnative@#29 Correct password
Enter password PYnative Incorrect Password
Chain multiple if statement in Python
In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one after another. This is useful when you need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple conditions one by one and if the condition fulfills, then executes that code.
Syntax of the if-elif-else statement:
if condition-1: statement 1 elif condition-2: stetement 2 elif condition-3: stetement 3 . else: statement
def user_check(choice): if choice == 1: print("Admin") elif choice == 2: print("Editor") elif choice == 3: print("Guest") else: print("Wrong entry") user_check(1) user_check(2) user_check(3) user_check(4)
Admin Editor Guest Wrong entry
Nested if-else statement
In Python, the nested if-else statement is an if statement inside another if-else statement. It is allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is useful when we want to make a series of decisions.
Syntax of the nested- if-else :
if conditon_outer: if condition_inner: statement of inner if else: statement of inner else: statement ot outer if else: Outer else statement outside if block
Example: Find a greater number between two numbers
num1 = int(input('Enter first number ')) num2 = int(input('Enter second number ')) if num1 >= num2: if num1 == num2: print(num1, 'and', num2, 'are equal') else: print(num1, 'is greater than', num2) else: print(num1, 'is smaller than', num2)
Enter first number 56 Enter second number 15 56 is greater than 15
Enter first number 29 Enter second number 78 29 is smaller than 78
Single statement suites
Whenever we write a block of code with multiple if statements, indentation plays an important role. But sometimes, there is a situation where the block contains only a single line statement.
Instead of writing a block after the colon, we can write a statement immediately after the colon.
number = 56 if number > 0: print("positive") else: print("negative")
Similar to the if statement, while loop also consists of a single statement, we can place that statement on the same line.
for loop in Python
Using for loop, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple.
Read the Complete guide on Python for loop.
Syntax of for loop:
for element in sequence: body of for loop
Example to display first ten numbers using for loop
for i in range(1, 11): print(i)
While loop in Python
In Python, The while loop statement repeatedly executes a code block while a particular condition is true.
In a while-loop, every time the condition is checked at the beginning of the loop, and if it is true, then the loop’s body gets executed. When the condition became False, the controller comes out of the block.
Read the Complete guide on Python while loop.
Syntax of while-loop
while condition : body of while loop
Example to calculate the sum of first ten numbers
num = 10 sum = 0 i = 1 while i
Sum of first 10 number is: 55
Break Statement in Python
Read: Complete guide on Python Break, Continue, and Pass.
The break statement is used inside the loop to exit out of the loop. It is useful when we want to terminate the loop as soon as the condition is fulfilled instead of doing the remaining iterations. It reduces execution time. Whenever the controller encountered a break statement, it comes out of that loop immediately
Let’s see how to break a for a loop when we found a number greater than 5.
Example of using a break statement
for num in range(10): if num > 5: print("stop processing.") break print(num)
0 1 2 3 4 5 stop processing.
Continue statement in python
The continue statement is used to skip the current iteration and continue with the next iteration.
Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body of the loop for other numbers.
Example of a continue statement
for num in range(3, 8): if num == 5: continue else: print(num)
Pass statement in Python
The pass is the keyword In Python, which won’t do anything. Sometimes there is a situation in programming where we need to define a syntactically empty block. We can define that block with the pass keyword.
A pass statement is a Python null statement. When the interpreter finds a pass statement in the program, it returns no operation. Nothing happens when the pass statement is executed.
It is useful in a situation where we are implementing new methods or also in exception handling. It plays a role like a placeholder.
months = ['January', 'June', 'March', 'April'] for mon in months: pass print(months)
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Python. Урок 5. Условные операторы и циклы
В этом уроке рассмотрим оператор ветвления if и операторы цикла while и for. Основная цель – это дать общее представление об этих операторах и на простых примерах показать базовые принципы работы с ними.
Условный оператор ветвления if
Оператор ветвления if позволяет выполнить определенный набор инструкций в зависимости от некоторого условия. Возможны следующие варианты использования.
1. Конструкция if
Синтаксис оператора if выглядит так.
if выражение: инструкция_1 инструкция_2 . инструкция_n
После оператора if записывается выражение. Если это выражение истинно, то выполняются инструкции, определяемые данным оператором. Выражение является истинным, если его результатом является число не равное нулю, непустой объект, либо логическое True. После выражения нужно поставить двоеточие “:”.
ВАЖНО: блок кода, который необходимо выполнить, в случае истинности выражения, отделяется четырьмя пробелами слева!
a = 3 if a == 3: print("hello 2")
a = 3 if a > 1: print("hello 3")
lst = [1, 2, 3] if lst : print("hello 4")
2. Конструкция if – else
Бывают случаи, когда необходимо предусмотреть альтернативный вариант выполнения программы. Т.е. при истинном условии нужно выполнить один набор инструкций, при ложном – другой. Для этого используется конструкция if – else.
if выражение: инструкция_1 инструкция_2 . инструкция_n else: инструкция_a инструкция_b . инструкция_x
a = 3 if a > 2: print("H") else: print("L")
a = 1 if a > 2: print("H") else: print("L")
Условие такого вида можно записать в строчку, в таком случае оно будет представлять собой тернарное выражение.
a = 17 b = True if a > 10 else False print(b)
В результате выполнения такого кода будет напечатано: True
3. Конструкция if – elif – else
Для реализации выбора из нескольких альтернатив можно использовать конструкцию if – elif – else.
if выражение_1: инструкции_(блок_1) elif выражение_2: инструкции_(блок_2) elif выражение_3: инструкции_(блок_3) else: инструкции_(блок_4)
a = int(input("введите число:")) if a 0: print("Neg") elif a == 0: print("Zero") else: print("Pos")
Если пользователь введет число меньше нуля, то будет напечатано “Neg“, равное нулю – “Zero“, большее нуля – “Pos“.
Оператор цикла while
Оператор цикла while выполняет указанный набор инструкций до тех пор, пока условие цикла истинно. Истинность условия определяется также как и в операторе if. Синтаксис оператора while выглядит так.
while выражение: инструкция_1 инструкция_2 . инструкция_n
Выполняемый набор инструкций называется телом цикла.
a = 0 while a 7: print("A") a += 1
Буква “А” будет выведена семь раз в столбик.
Пример бесконечного цикла.
Операторы break и continue
При работе с циклами используются операторы break и continue.
Оператор break предназначен для досрочного прерывания работы цикла while.
a = 0 while a >= 0: if a == 7: break a += 1 print("A")
В приведенном выше коде, выход из цикла произойдет при достижении переменной a значения 7. Если бы не было этого условия, то цикл выполнялся бы бесконечно.
Оператор continue запускает цикл заново, при этом код, расположенный после данного оператора, не выполняется.
a = -1 while a 10: a += 1 if a >= 7: continue print("A")
При запуске данного кода символ “А” будет напечатан 7 раз, несмотря на то, что всего будет выполнено 11 проходов цикла.
Оператор цикла for
Оператор for выполняет указанный набор инструкций заданное количество раз, которое определяется количеством элементов в наборе.
for i in range(5): print("Hello")
В результате “Hello” будет выведено пять раз.
Внутри тела цикла можно использовать операторы break и continue, принцип работы их точно такой же как и в операторе while.
Если у вас есть заданный список, и вы хотите выполнить над каждым элементом определенную операцию (возвести в квадрат и напечатать получившееся число), то с помощью for такая задача решается так.
lst = [1, 3, 5, 7, 9] for i in lst: print(i ** 2)
Также можно пройти по всем буквам в строке.
word_str = "Hello, world!" for l in word_str: print(l)
Строка “Hello, world!” будет напечатана в столбик.
На этом закончим краткий обзор операторов ветвления и цикла.
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
Python. Урок 5. Условные операторы и циклы : 41 комментарий
- Ирина 23.09.2017 Подскажите, пожалуйста, что делать, если знаки” == “и “!=” не выделяются отдельным цветом и, соответственно, не дают никакого результата?
- Максим 06.08.2018 Если верно понимаю, Вы не правильно записываете команду
Получается так, что Вы говорите программе, чтобы она описала строчное значение, указанное в “”
В данным случае, Вам нужно применить оператор if и написать:
if name == “0”:
print (“False”) Таким образом вы даете программе условие, что: если переменная равна значению “0” (строчному значению)
то выводи False
- Илья 25.05.2020 def find_NOK(number1, number2):
if number1 < number2:
number1, number2 = number2, number1
for x in range(number2):
if number1*(x+1)%number2 == 0:
return number1*(x+1)
return number1*number2 a, b = map (int, input().split(', '))
print(find_NOK(a, b))
- Jam 13.07.2020 Функция range генерирует все числа указанные в диапазоне не включая последнее.
Поэтому:
range(1, max(a) + 1)