# Loops In Python (for, while  loop)

Example 1:

```python
# For loop statement
# It has the ability to iterate over the items of any sequence, such as a list or a string.
# Syntax
# for iterating_var in sequence:
#   statements(s)
# If a sequence contains an expression list, it is evaluated first. 
# Then, the first item in the sequence is assigned to the iterating variable iterating_var. 
# Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
#Examples
s = 'PYTHON'
for x in s : 
    print(x)
    
```

P

Y&#x20;

T

&#x20;H

&#x20;O

&#x20;N

Example 2:

```python
# It can be used to iterate over iterators and a range.
# Iterating over a list 
print("List Iteration") 
l = ["books", "bags", "pens"] 
for i in l: 
    print(i) 
```

List Iteration

books

bags

pens

Example 3:

```python
# Iterating over a String 
print("\nString Iteration")     
s = "Python_is_awesome"
for i in s : 
    print(i)
#String Iteration
```

String Iteration

&#x20;P

&#x20;y

&#x20;t

&#x20;h

&#x20;o

&#x20;n

\_

&#x20;i

s

*\_*&#x20;

a

&#x20;w

&#x20;e

&#x20;s

&#x20;o

&#x20;m

&#x20;e

Example 4:

```python
# Iterating over dictionary 
print("\nDictionary Iteration")    
d = dict()  
d['xyz'] = 123
d['abc'] = 345
for i in d : 
    print("%s  %d" %(i, d[i]))
```

Dictionary Iteration

&#x20;xyz 123&#x20;

abc 345

Example 5:

```python
# One parameter
for i in range(5):
    print(i)
```

0&#x20;

1

2

3

4

## Practice problems:

Example 6:

```python
# Two parameters
for i in range(3, 6):
    print(i)
```

3

4

5

Example 7:

```python
# Three parameters
for i in range(4, 10, 2):
    print(i)
```

4&#x20;

6&#x20;

8

Example 8:

```python
# Going backwards
for i in range(0, -10, -2):
    print(i)
```

0&#x20;

-2&#x20;

-4&#x20;

-6&#x20;

-8

Example 9:

```python
i = 0
while i < 3: 
    print(i) 
    i += 1
else: 
    print(0) 
```

0

1

2

0

Example 10:

```python
my_string = "Python"
i = "i"
while i in my_string:    #No output why?
    print(i, end =" ")
```

No Output

Example 11:

```python
my_string = 'Python is Awesome'
for i in range(my_string): 
    print(i) 
```

TypeError Traceback (most recent call last)

&#x20;in () 1 my\_string = 'Python is Awesome' ----> 2 for i in range(my\_string): 3 print(i)

TypeError: 'str' object cannot be interpreted as an integer

Example 12:

```python
my_string = 'We love Python'
for i in range(len(my_string)): 
    print(my_string[i].upper())
```

W&#x20;

E

L&#x20;

O

V

E

P

Y

T

H

O

N

Example 13:

```python
my_list = ['one', 'two', 'three', 'four', 'five']
my_list_len = len(my_list)
for i in range(0, my_list_len):
    print(my_list[i])
```

one

two

three

four

five

Example 14:

```python
for i in range(5, 0, -1):
        if i == 1:
                print('1 bottle of beer on the wall, 1 bottle of beer!')
                print('So take it down, pass it around, no more bottles of beer on the wall!')
        elif i == 2:
                print('2 more bottles of beer on the wall, 2 more bottles of beer!')
                print('So take one down, pass it around, 1 more bottle of beer on the wall!')
        else:
                print('{0} bottles of beer on the wall, {0} bottles of beer!'.format(i))
                print('So take it down, pass it around, {0} more bottles of beer on the wall!'.format(i - 1))
```

5 bottles of beer on the wall, 5 bottles of beer!

So take it down, pass it around, 4 more bottles of beer on the wall!

4 bottles of beer on the wall, 4 bottles of beer!&#x20;

So take it down, pass it around, 3 more bottles of beer on the wall!&#x20;

3 bottles of beer on the wall, 3 bottles of beer!&#x20;

So take it down, pass it around, 2 more bottles of beer on the wall!&#x20;

2 more bottles of beer on the wall, 2 more bottles of beer!&#x20;

So take one down, pass it around, 1 more bottle of beer on the wall!

1 bottle of beer on the wall, 1 bottle of beer!&#x20;

So take it down, pass it around, no more bottles of beer on the wall!

Example 15:

```python
# Nested Loops
# Python programming language allows to use one loop inside another loop.
# Syntax:
# for iterator_var in sequence:
#    for iterator_var in sequence:
#        statements(s)
#        statements(s)
# Example:-
for i in range(1, 5): 
    for j in range(i): 
         print(i, end=' ') 
    print() 
```

1&#x20;

2 2

3 3 3

4 4 4 4

Example 16:

```python
l = [ 'hello','hi',1,2,3,4,3.6j,['hi','bye','bye bye'],123,23,3,2]

for var in l :
     print(var)
```

hello&#x20;

hi&#x20;

1&#x20;

2&#x20;

3&#x20;

4

3.6j

&#x20;\['hi', 'bye', 'bye bye']&#x20;

123&#x20;

23&#x20;

3&#x20;

2

Example 17:

```python
for var in range(1,20,2):
    if var % 2 == 0 : 
        break
    elif var % 3 == 0 :
        continue
    print("Hello World")
else : 
    print("Good to Go ")
```

Output

Hello World&#x20;

Hello World&#x20;

Hello World&#x20;

Hello World&#x20;

Hello World&#x20;

Hello World

&#x20;Hello World

&#x20;Good to Go

Example 18:

```python
l = [ 1,2,3,4,5,6,7,8,9,10 ] 
n = int(input("Enter a number : "))
for var in l : 
    print(var*n)
```

Output

Enter a number : 5&#x20;

5&#x20;

10&#x20;

15&#x20;

20&#x20;

25&#x20;

30&#x20;

35&#x20;

40&#x20;

45&#x20;

50

Example 19:

```python
for letter in 'Python': 
   print('Current Letter :', letter)

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:    
   print('Current fruit :', fruit)

print("Good bye!")
```

Output

Current Letter : P&#x20;

Current Letter : y&#x20;

Current Letter : t

Current Letter : h

&#x20;Current Letter : o

Current Letter : n&#x20;

Current fruit : banana&#x20;

Current fruit : apple&#x20;

Current fruit : mango&#x20;

Good bye!

Example 20:

```python
# Iterating by Sequence Index
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
    print('Current fruit :', fruits[index])

print("Good bye!")
```

Current fruit : banana&#x20;

Current fruit : apple&#x20;

Current fruit : mango&#x20;

Good bye!

Dictionary doesn't remember order (sequence), that's why we use another data type in python orderedDict

Example 21:

```python
d = { 
        'name' : 'python',
        'version': 3.6,
        'father' : 'Guido Van Rossum',
        'named on ' : 'Monty Python',
        'method' : 'OOPS',
        'type' :'interpreted',
        'year' : 1991,
        }

for var in d:
    print(var,'=',d[var])

s = { 'hello', 'hi',1,2,3,4,5,6,'good to go','bye bye' }
for var in s : 
    print(var)
```

Output

name = python&#x20;

version = 3.6

&#x20;father = Guido Van Rossum&#x20;

named on = Monty Python&#x20;

method = OOPS&#x20;

type = interpreted&#x20;

year = 1991&#x20;

1

2&#x20;

3&#x20;

hello

4&#x20;

5&#x20;

6&#x20;

hi

bye bye

good to go

Example 22:

```python
l = [ (1,2,3),('hello','hi','how are you'),('good','bye','bye',),('hello','world','!!',),('python','java','c'),'c++',['oh','my','god' ] ]
c = 1
for val1,val2,val3 in l :
    print("Iteration ",c)
    print("Value 1 = ",val1)
    print("Value 2 = ",val2)
    print("Value 3 = ",val3)
    c = c + 1
    print("\n")
```

Output

Iteration 1&#x20;

Value 1 = 1&#x20;

Value 2 = 2&#x20;

Value 3 = 3

Iteration 2&#x20;

Value 1 = hello&#x20;

Value 2 = hi

&#x20;Value 3 = how are you

Iteration 3 Value 1 = good&#x20;

Value 2 = bye&#x20;

Value 3 = bye

Iteration 4&#x20;

Value 1 = hello&#x20;

Value 2 = world&#x20;

Value 3 = !!

Iteration 5&#x20;

Value 1 = python&#x20;

Value 2 = java&#x20;

Value 3 = c

Iteration 6&#x20;

Value 1 = c&#x20;

Value 2 = +

&#x20;Value 3 = +

Iteration 7&#x20;

Value 1 = oh&#x20;

Value 2 = my&#x20;

Value 3 = god

Example 23:

```python
l1 = [ 1,34,56,34,2,364,57,42,13,4,65,63,3,12,2,3456,]
l2 = [ 1,3,4,42,67,346,57,5434,2,34,657,434,2,346,34,34]

for val1,val2 in zip(l1,l2) :
    print("val1 = ",val1)
    print("val2 = ",val2)
    print()
```

Output

val1 = 1&#x20;

val2 = 1

val1 = 34&#x20;

val2 = 3

val1 = 56

&#x20;val2 = 4

val1 = 34&#x20;

val2 = 42

val1 = 2&#x20;

val2 = 67

val1 = 364&#x20;

val2 = 346

val1 = 57&#x20;

val2 = 57

val1 = 42&#x20;

val2 = 5434

val1 = 13&#x20;

val2 = 2

val1 = 4&#x20;

val2 = 34

val1 = 65&#x20;

val2 = 657

val1 = 63&#x20;

val2 = 434

val1 = 3&#x20;

val2 = 2

val1 = 12&#x20;

val2 = 346

val1 = 2&#x20;

val2 = 34

val1 = 3456&#x20;

val2 = 34

Example 24:

```python
for var in range(1,20) : 
    print(var,end=",")
```

Output

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,

Example 25:

```python
for var in range(1000,0,-1) : 
    if var % 2 == 0 and var % 3 == 0 and var % 5 == 0 : 
        print(var,end=', ')
```

Output

990, 960, 930, 900, 870, 840, 810, 780, 750, 720, 690, 660, 630, 600, 570, 540, 510, 480, 450, 420, 390, 360, 330, 300, 270, 240, 210, 180, 150, 120, 90, 60, 30,

Example 26:

```python
l = [ 10, 34, 2, 56, 23, 567, 34, 232, 12, 345, 76, 44, 213, 45, 12, 456 ]

for var in range(len(l)-1):
    for var2 in range(var+1,len(l)) :
        if l[var] >= l[var2] :
            l[var],l[var2]=l[var2],l[var]

print(l)
```

Output:

\[2, 10, 12, 12, 23, 34, 34, 44, 45, 56, 76, 213, 232, 345, 456, 567]
