(B17) Python part9 Python Loop - For loop - Break, Continue, Pass
20220521 111112
Python Loops
The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones.
It enables us to alter the flow of the program so that instead of
writing the same code again and again, we can repeat the same code
for a finite number of times. For example, if we need to print the
first 10 natural numbers then, instead of using the print statement
10 times, we can print inside a loop which runs up to 10 iterations
Advantages of loops
It provides code re-usability.
Using loops, we do not need to write the same code again and again.
Using loops, we can traverse over the elements of data structures (array or linked lists).
loop statements in Python.
Loop Statement Description
for loop The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.
do-while loop The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).
--------------------------------------
Python for loop
The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary.
The syntax of for loop in python is given below.
for iterating_var in sequence:
statement(s)
Iterating string using for loop
str = "Python"
for i in str:
print(i)
for i in "Savantis":
print(i)
----------------
a = [12,34,55,66,11,82,96,17]
for x in a:
print("interation of a ", x)
----------------
a = [12,34,55,66,11,82,96,17]
sum =0
for x in a:
sum = sum +x
print("total of values in a is ",sum)
----------------
#0+1+2+3+4
sum=0
for x in range(5):
sum = sum +x
print("total of values in a is ",sum)
------------------
#break - stops iteration if condition met
a = [12,34,55,66,11,82,96,17]
for x in a:
print("interation of a ", x)
if x == 11:
break
-------------------
a = [12,34,55,66,11,82,96,17]
for x in a:
if x == 11:
print(" x is 11 , so break")
break
print("interation of a ", x)
--------------------
#continue --if condition is true , skill it, and continue
a = [12,34,55,66,11,82,96,17]
for x in a:
if x == 11:
print(" x is 11 , so skip step continue")
continue
print("interation of a ", x)
----------------------
#pass - continue, not breaks or skipps
a = [12,34,55,66,11,82,96,17]
for x in a:
if x == 11:
print(" x is 11 , so pass and continue")
pass
print("interation of a ", x)
------------------------
: Program to print numbers in sequence.
for i in range(10):
print(i,end = ' ')
----------
Program to print table of given number.
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
----------------
list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])
---------------------
for x in range(5,11):
if x%2 == 0:
print(x,' is even number')
else:
print(x, ' is odd number')
-----------------------------
for-else
n = int(input("Enter n value="))
for x in range(2,n):
if n%x == 0:
print(n,' is Not a prime number')
break
else:
print(n, ' is a Prime number')
---------------------------------
Nested for loop in python
Example- 1: Nested for loop
# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Output:
Enter the rows:5
*
**
***
****
*****
Example-2: Program to number pyramid.
rows = int(input("Enter the rows"))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()
Output:
1
22
333
4444
55555
Example 1
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
The for loop completely exhausted, since there is no break.
Example 2
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «(B17) Python part9 Python Loop - For loop - Break, Continue, Pass», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.