CONTROL FLOW, LOOPS, NESTED LOOP

Ad Code

CONTROL FLOW, LOOPS, NESTED LOOP

 

CONTROL FLOW (if statement)

The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison. If statement match with expression then returns True otherwise returns False.

Syntax:
if expression:
 statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.

Example: 
a = 3
if a > 2:
 print(a, "is greater")
print("done")
a = -1
if a < 0:
 print(a, "a is smaller")
print("Finish")

If-Else Statement

If-else statement contains the block of code (false block) that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

Syntax of if - else :
if test expression:
   Body of if stmts
else:
   Body of else stmts

Example: 
Enter basic pay then calculate and print net pay using following expression.
DA=50%, HRA=40% and IT=5% of basic pay if basic pay>=15000 otherwise DA=30%, HRA=20% and no any tax. 
bp=int(input("Enter basic pay: "));
if bp >= 15000:
    np=bp+bp*.85;
    print("Net Pay= ",np);
else: 
    np=bp+bp*.5;
    print("Net Pay= ",np);

If-elif-else

The elif statement allows us to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. If statement one is true then execute it, otherwise go to second statement or others, if none of above expression satisfy then performs else statement.

Syntax of if – elif - else :
If test expression:
     Body of if stmts
elif test expression:
     Body of elif stmts
else:
     Body of else stmts

Example:
Enter a number then check and print number is single, double, triple or multiple digit.
n=int(input(Enter any number:))
if n<10:
     print(n, is single digited)
elif n>9  and  n<100:
       print(n, is double digited)
elif n>99 and n<1000:
       print(n, is triple digited)
else:
   print(n, is multiple digited)

Example:
Python code for simple calculator.

a = float (input("Enter First Value: "))
b = float (input("Enter Second Value: "))
operator = input ("Enter Operator: ")
if operator == '+':
    print ("Result= ", a+b)
elif operator == '-':
    print ("Result= ", a-b)
elif operator == '*':
    print ("Result= ", a*b)
elif operator == '/':
    print ("Result= ", a/b)
else:
    print ("Operator Doesn't Macth the Criteria ")

Iteration or Loop Statement
Loops statements are used when we need to run same code again and again or execute the same work again and again.  A loop statement allows us to execute a statement or group of statements multiple times as long as the condition is true. Repeated execution of a set of statements with the help of loops is called iteration.

Statements:
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
 . 
While loop:
The while loop contains a boolean expression and the code inside the loop is repeatedly executed as long as the boolean expression is true. The statements that are executed inside while can be a single line of code or a block of multiple statements. 

Syntax:
while(expression):
     Statement(s)

Example1:
Print only Even number from 1 to 50 in descending order.
n = 50
while(n >=2 ):
    print(n)
    n =n-2

Example2:
Enter any number then count and print number of digits of that given number.
n=int(input("Enter a number"));
c=0;
while(n!=0):
    n=int(n/10);
    c=c+1;
print("No. of Digits=",c);

Example2:
Enter any decimal number then convert in binary format.
n=int(input("Enter decimal number"));
p=int(0);
r=int(0);
x=n;
while n!=0:
    b=int(n/2);
    d=n-b*2;
    r=r+d*pow(10,p);
    p=p+1;
    n=b;
print("Binary of",x," is ",r);

Step-by-Step Explanation of above code:

Step 1: n = int(input("Enter decimal number"))

  • input("Enter decimal number"): This statement asking the user to enter a decimal number. The input() function waits for the user to enter a value.
  • int(): Converts the input (which is a string) into an integer. So, whatever decimal number the user enters is converted into an integer and assigned to the variable n.

Step 2: p = int(0)

  • p is initialized to 0. It will be used as a position counter (starting from the rightmost bit) while constructing the binary number.

Step 3: r = int(0)

  • r is initialized to 0. This variable will hold the binary result. Initially, it is set to zero.

Step 4: x = n

  • x is a copy of n, used to preserve the original decimal number. This will be used in the final print statement to show the original input.

Step 5: while n != 0:

  • This starts a while loop that runs as long as n is not equal to 0.
  • The idea is to repeatedly divide the decimal number n by 2 to get the binary digits.

Step 6: b = int(n / 2)

  • b = int(n / 2): This line divides n by 2 (using integer division). It computes the quotient of the division, which represents the remaining number to process in the next iteration. This quotient is stored in b.

Step 7: d = n - b * 2

  • d = n - b * 2: This line calculates the remainder of the division, which is either 0 or 1. It's essentially the least significant bit (rightmost bit) of the binary number.
    • If n is even, d will be 0 (because n divided by 2 leaves no remainder).
    • If n is odd, d will be 1 (because n divided by 2 leaves a remainder of 1).

Step 8: r = r + d * pow(10, p)

  • pow(10, p): This line raises 10 to the power of p. It is used here to place the bit d in the correct position in the binary number. For example, if p = 0, it adds d * 1 to r; if p = 1, it adds d * 10 (moving the bit one place to the left), and so on.
  • r = r + d * pow(10, p): This adds the bit d to the current value of r, shifting it appropriately by using powers of 10.

Step 9: p = p + 1

  • This line increments p by 1, so the next bit will be placed in the next higher position in the binary number (next left bit).

Step 10: n = b

  • n = b: This line sets n to the quotient b from the division. The next iteration will now work with the smaller value b, repeating the process until n becomes 0.

Step 11: print("Binary of", x, "is", r)

  • After the while loop finishes (i.e., when n becomes 0), the program prints the binary equivalent of the decimal number x. The variable r contains the binary representation, and it's printed out as the result.

Example Walkthrough:

Let's say the user inputs n = 10 (decimal number).

1.      First Iteration (n = 10):

    • b = int(10 / 2) = 5 (quotient)
    • d = 10 - 5 * 2 = 0 (remainder)
    • r = 0 + 0 * pow(10, 0) = 0
    • p = 1 (incremented)
    • n = 5 (updated to quotient)

2.      Second Iteration (n = 5):

    • b = int(5 / 2) = 2 (quotient)
    • d = 5 - 2 * 2 = 1 (remainder)
    • r = 0 + 1 * pow(10, 1) = 10
    • p = 2 (incremented)
    • n = 2 (updated to quotient)

3.      Third Iteration (n = 2):

    • b = int(2 / 2) = 1 (quotient)
    • d = 2 - 1 * 2 = 0 (remainder)
    • r = 10 + 0 * pow(10, 2) = 10
    • p = 3 (incremented)
    • n = 1 (updated to quotient)

4.      Fourth Iteration (n = 1):

    • b = int(1 / 2) = 0 (quotient)
    • d = 1 - 0 * 2 = 1 (remainder)
    • r = 10 + 1 * pow(10, 3) = 1010
    • p = 4 (incremented)
    • n = 0 (updated to quotient, loop ends)

After the loop, the program prints:

Binary of 10 is 1010

Conclusion:

This program converts a decimal number to binary by repeatedly dividing the number by 2, storing the remainders (binary digits), and building the result.

For loop:

Python for loop is used for repeated execution of a group of statements for the desired number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects.

Syntax of for Loop
for value in sequence:  
     {loop body}   

Example:
n = 4
for i in range(0, n):
    print(i)

Example:
Print 10 natural numbers in reverse order.
For i in range(10,0,-1):
          Print(i)

Example:

Print only even number from 2 to 20 in descending order.

For i in range(20,1,-2):
          Print(i)

Step-by-Step Explanation:

Step 1: for i in range(20, 1, -2):

  • for i in ...: This line begins a for loop, which will iterate over a sequence of values. The variable i will take on the value of each item in the sequence, one by one, for each iteration.
  • range(20, 1, -2): This line generates a sequence of numbers using the range() function. It takes three arguments:
    • The first argument (20) is the starting value of the sequence. The loop will start with this value.
    • The second argument (1) is the stopping condition. The loop will stop when the value reaches 1 (but it will not include 1).
    • The third argument (-2) is the step value, which indicates how much to decrease the value after each iteration. In this case, -2 means that the value will decrease by 2 in each iteration (i.e., count backward by 2).

So, range(20, 1, -2) generates the sequence: 20, 18, 16, 14, 12, 10, 8, 6, 4, 2. The loop will run for each value in this sequence.

Step 2: print(i)

  • This line is the body of the for loop. For each value of i, it prints the value of i to the screen.
  • For example, in the first iteration, i will be 20, so print(i) will display 20. In the next iteration, i will be 18, and so on.

Summary:

  • The loop starts at 20 and counts down by 2 (i.e., 20, 18, 16, ...), stopping just before it reaches 1.
  • The print(i) statement prints each value as the loop runs through the sequence generated by range(20, 1, -2).
Nested Loop in Python

A nested loop in Python refers to a loop inside another loop. This means that one loop is placed inside the body of another loop. The inner loop runs completely for every single iteration of the outer loop.

Syntax:

for outer_variable in range(start, stop):
    # Outer loop body
    for inner_variable in range(start, stop):
        # Inner loop body

·  The outer loop runs first and controls how many times the inner loop will execute.

·  The inner loop will execute completely for every iteration of the outer loop.

Summary:

  • A nested loop is when you have one loop inside another loop.
  • The inner loop runs completely for every single iteration of the outer loop.
  • They are useful for iterating over multi-dimensional data or performing tasks that require multiple iterations.
Nested for loop

Example: Write python code of following
* * 
* * * 
* * * * 
* * * * * 

for i in range(0, 6):
    for j in range(0, i+1):
        print("*", end=" ")
    print()

Step-by-Step Explanation:

Step 1: for i in range(0, 6):

  • range(0, 6): The range() function generates a sequence of numbers from 0 to 5 (inclusive of 0, exclusive of 6). This means the outer loop (i) will iterate 6 times, with i taking the values 0, 1, 2, 3, 4, and 5 in each iteration.
  • Outer loop: The variable i will represent the current row number in the pattern.

Step 2: for j in range(0, i+1):

  • Inner loop: For each iteration of the outer loop, we have an inner loop.
  • range(0, i+1): This creates a sequence of numbers from 0 to i, inclusive. The i+1 ensures that the inner loop runs for exactly i + 1 iterations. This means the number of stars printed in each row depends on the value of i.
    • When i = 0, the inner loop will run 0 + 1 = 1 time.
    • When i = 1, the inner loop will run 1 + 1 = 2 times, and so on.

Step 3: print("*", end=" ")

  • print("*", end=" "): This prints a star (*) followed by a space.
  • end=" ": By default, the print() function ends with a newline (\n). Here, end=" " changes the behavior, so it adds a space (" ") after each star instead of moving to the next line. This ensures that the stars in each row are printed on the same line, separated by a space.

Step 4: print()

  • print(): After the inner loop finishes running, this print() function is called without any arguments. This prints a newline character (\n), causing the next set of stars to appear on a new line. This happens after the stars for each row are printed.

Summary:

  • The outer loop (for i in range(0, 6)) controls how many rows of stars will be printed.
  • The inner loop (for j in range(0, i+1)) controls how many stars will be printed in each row.
  • The print("*", end=" ") statement prints a star followed by a space, keeping the stars on the same line.
  • After each row is printed, the print() statement adds a new line to separate the rows.

This code will print a right-angled triangle pattern of stars, where the number of stars increases by 1 with each row.

Nested while loop

Preview:

i = 1
while i <= 6:            # Outer while loop
    j = 1
    while j <= i:        # Inner while loop
        print("*",end = " ")
        j += 1
    print()
    i += 1

# Example 1 of Nested For Loops (Pattern Programs)

for i in range(1,6):
 for j in range(0,i):
 print(i, end=" ")
 print('')

Output:


2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5

Break and continue:

In Python, break and continue statements can alter the flow of a normal loop. Sometimes we wish to terminate the current iteration or even the whole loop without checking test expression. The break and continue statements are used in these cases.

Break:

The break statement terminates the loop containing it and control of the program flows to the statement immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

The following shows the working of break statement in for and while loop:
for var in sequence:
   # code inside for loop
   If condition:
       break (if break condition satisfies it jumps to outside loop)
   # code inside for loop
# code outside for loop

Example: # Program to display all the elements before number 88.
for num in [11, 9, 88, 10, 90, 3, 19]:
    print(num)
    if(num==88):
       print("The number 88 is found")
       print("Terminating the loop")
       break

Output:
11 
88 
The number 88 is found

Continue: 
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

The following shows the working of break statement in for and while loop:

while test expression
   # code inside while loop
   If condition:
       continue (if continue condition satisfies it jumps to outside loop)
   # code inside while loop
# code outside while loop


Post a Comment

0 Comments

Ad Code