# 3rd Week Python Experience

Now at week 3 , increase in complexity ,, have a great time reading the article ....

## While Loop

A "while loop" is a control flow statement used in programming to repeatedly execute a block of code as long as a specified condition is true. If the condition is true, the code block inside the loop is executed. When the condition becomes false, the loop terminates, and the program continues with the next line of code after the loop.

***Use Cases*** :

* Used when you don't know the number of iterations in advance, but you know the condition under which you want to continue iterating.
    
* Useful when the number of iterations is not predetermined, or you want to repeatedly execute a block of code until a certain condition is met.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706241327397/4545c1f9-105b-497c-8031-417d2d97cab4.jpeg align="center")

example:

Guessing my birthday :

```python
print('year of birth of Anish ?')
year=int(input(  ))

while(year!=2004):  
  print('you are wrong, guess again?')
  year=int(input(  ))

print("hurray! you got it correct")
```

Finding factorial of an integer :

```python
a=1 #answer
i=1  #iterator 
n=int(input("Enter a positive interger for finding factorial : "))
while(i<=n):
  a=a*i
  i=i+1
print(a)

OR

n=int(input())      #input
a=1                 #ans (factorial)

if(n<0):            # if n  is negative
  print("Not defined")
else:
 while(n>0):        #if n is positive
    a=a*n
    n=n-1
 print(a)
```

## For Loop

In Python, the `for` loop is used to iterate over a sequence (such as a list, tuple, string, etc.) or any iterable object.

***Use Cases*** :

* Used when you know the number of iterations or the sequence to iterate over in advance.
    
* Suitable for iterating over sequences like lists, tuples, strings, and iterating a fixed number of times using functions like `range()`.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706268626380/7d1c5c10-ade7-41e3-a1a4-7c928e037c4c.jpeg align="center")

```python
for item in iterable:
    # Code block to be executed for each iteration
    # You can use 'item' to access the current element in the iteration
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706525175529/f508c869-d359-4d99-bb89-145d8c5ac6b8.png align="center")

Here's the breakdown:

* `item`: This is a variable that takes the value of the next element in the iterable for each iteration. You can use any valid variable name here.
    
* `iterable`: This is the sequence or iterable object over which the loop iterates. It could be a list, tuple, string, dictionary, range object, etc.
    
* Indentation: As with other control structures in Python, the code block to be executed within the loop is indented.
    

1.Here's a simple example of a `for` loop iterating over a list:

```python
my_list = [1, 2, 3, 4, 5]

for num in my_list:
    print(num)         


                           #o/p: 
                             1
                             2
                             3
                             4 
                             5
```

This loop will iterate over each element in `my_list`, and in each iteration, `num` will take the value of the current element, which will then be printed.

2.The `range()` function is commonly used with `for` loops to generate a sequence of numbers:

```python
for i in range(5):  # This will iterate from 0 to 4
    print(i)
```

3.You can also use `for` loops with dictionaries to iterate over keys, values, or key-value pairs:

```python
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
    print(key, my_dict[key])  # Accessing both key and value

# Or you can use items() method to get key-value pairs directly
for key, value in my_dict.items():
    print(key, value)
```

Remember that the indentation is crucial in Python to denote the scope of the loop.

another example:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706269582676/e99d49bf-6d83-430f-9a8c-5be0e1d9082b.png align="center")

\*\* **i** iterates over (**0 to19**) &lt;&lt;-&gt;&gt; which is **range(20)**

for example : here also **i** stars from **1** and ends at 11-1 =**10**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706524597514/dc5047c8-ef0f-4e1a-b3b8-e0f1a5f3fdd9.png align="center")

## More on range and 'for' loop

## without range

**1**. ***The***`range()`***function can take one, two, or three arguments*:**

1. `range(stop)`: Generates a sequence from `0` up to (but not including) the `stop` value.
    
2. `range(start, stop)`: Generates a sequence from `start` up to (but not including) the `stop` value.
    
3. `range(start, stop, step)`: Generates a sequence from `start` up to (but not including) the `stop` value, incrementing each time by the `step` value.
    

The `step` parameter specifies the amount by which the sequence increases from one element to the next. If the `step` parameter is omitted, it defaults to `1`. If the `step` parameter is negative, the sequence decreases by that amount instead.

```python
#print even numbers till 10
for i in range(2,11,2):       # 2 for increment 
  print(i)  #o/p : 2 4 6 8 10
```

**2**. ***for reverse order in range :***

for example : print even numbers till 10 in reverse order

```python

for i in range(10,0,-2):  #-2 for decrementing
  print(i)
```

**3**. ***for loop for collections :***

If you want to iterate over each element in a collection (such as a list, tuple, string, etc.) without explicitly using the `range()` function, you can use the `for` loop with the `in` keyword. This allows you to iterate directly over the elements of the collection.

Here's the syntax:

```python
for element in collection:
    # Code block to execute for each element
```

In this loop:

* `element` represents each individual element in the `collection`.
    
* `collection` is the iterable object (e.g., list, tuple, string) you want to iterate over.
    

Here's an example:

```python
my_list = [1, 2, 3, 4, 5]
for num in my_list:
    print(num)
```

This loop will print each element of the list `my_list` on a separate line:

```python
1
2
3
4
5
```

Similarly, you can iterate over the characters in a string:

```python
my_string = "hello"
for char in my_string:
    print(char)
```

This loop will print each character of the string `my_string` on a separate line:

```python
h
e
l
l
o
```

You can use this approach to iterate over the elements of any iterable object without explicitly using `range()`.

## Formatted Printing

1. **end parameter** - in Python, the `end` parameter is used with the `print()` function to specify what should be printed at the end of the output. By default, `print()` ends with a newline character (`\n`), which moves the cursor to the next line after printing.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706530001457/3d6b0400-95a5-456d-877a-3b141d97fcd0.png align="center")
    
2. **separator parameter** - `sep` parameter is used with the `print()` function to specify the separator between multiple items that are being printed. By default, the `sep` parameter is set to a single space character.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706530314019/e09105fa-b33f-4ba7-94cc-370af8ee16f7.png align="center")

for the problem "/" between is and 10 we use this method :

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706530915172/c2b2d0ea-3f59-45fb-b6ec-db4d555fed65.png align="center")

3\. **f-string :** (`f""`) syntax in Python with the `print()` function.

The `f""` string formatting, also known as f-strings, is a feature introduced in Python 3.6. It allows for easy string interpolation, where expressions inside curly braces `{}` are evaluated at runtime and replaced with their values.

* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706540518924/629b3172-5340-408c-8d57-cd6ce378da91.png align="center")
    

4.**format() :-**

* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706625652331/8144705a-c09f-4a70-9f25-e80b41546493.png align="center")
    

5\. Format specifier:-

Format specifiers in Python are used to control the formatting of variables when they are inserted into strings using the `str.format()` method or f-strings. They allow you to specify how variables should be displayed, such as their width, precision, alignment, and type.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706626340650/f77d942f-bc5c-4c9a-a712-ad02fe60e5ab.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706626760733/21688871-a6c9-4f2d-a2c4-3f35ecc4e82c.png align="center")

## Nested Loops

A loop inside another loop is called a nested loop. The inner loop will repeat its iterations for each iteration of the outer loop.This means that there is a loop contained inside another loop. In programming, this structure allows you to iterate over elements in multiple dimensions or perform repetitive tasks in a hierarchical manner.

For example, consider the following Python code that prints a multiplication table:

```python
s='vibgyor'
combinations=0
for i in range(7):
  for j in range(7):
   print(s[i],s[j])
   combinations=combinations+1 
#talkig about the number of permutations
print(combinations)
```

In this code:

* The outer loop iterates over each character of the string `'vibgyor'`.
    
* The inner loop also iterates over each character of the string `'vibgyor'`.
    
* Inside the nested loops, each combination of characters is printed.
    
* The variable `combinations` is incremented by 1 for each combination printed, effectively counting the total number of combinations.
    
* Finally, the total number of combinations is printed outside the nested loops.
    

example 2 : **for nested for**

```python
# Find all the prime numbers Less than the entered number.
n=int(input())
if(num>2):
  print(2,end=' ')

for i in range(3,n):
  flag=False
  for j in range(2,i):
    if(i%j==0):
      flag=False
      break
    else:
      flag=True
  if(flag):
    print(i,end=' ')
```

example 3 : while nested while

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706801747413/25ef9d0e-2fe6-42e1-be11-df33b862339b.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706801756261/22f1b452-27af-44cd-a97f-a4f6e01784bf.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706801762195/c9714fb7-73a6-43e4-a02f-b7f3d54f6fa6.png align="center")

## Break , Continuous and Pass statement

1. A `break` statement is used in programming to immediately exit a loop when certain conditions are met. When the `break` statement is encountered within a loop, the loop is terminated, and the program continues with the next statement after the loop.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706803594924/66da8131-d1b1-48cf-99de-bc5a3c2fc035.png align="center")

1. The `continue` statement is used in programming to immediately skip the rest of the current iteration of a loop (for example, a `for` loop or a `while` loop), and continue with the next iteration. When the `continue` statement is encountered within a loop, the remaining code inside the loop for the current iteration is skipped, and the loop proceeds with the next iteration.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706804297472/76bea984-64fa-40e6-bcdc-e38615389997.png align="center")
    
2. In Python, the `pass` statement is a null operation. It doesn't do anything when it's executed. It's typically used as a placeholder where syntactically some code is required but you don't want to perform any action.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1706804513311/b9ae7760-3393-413c-b7cc-8492efb26e40.png align="center")
    
    {here , in this code we don't want to do anything with the numbers which are not divisible by 3 }
    

!!!! This are the learnings that I gathered in week-3 . !!!!
