Control Structures

Control Structures are just a way to specify the flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. There are three basic types of logic, or flow of control, known as:
  1. Decision Making Statements
  2. Loops
  3. Control Statements

DECISION-MAKING STATEMENTS

  • Decision-making is the anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.
  • As the name implies, decision-making allows us to run a particular block of code for a particular decision.
  • Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcomes. You need to determine which action to take and which statements to execute if the outcome is TRUE or FALSE otherwise.
  • Here, the decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision-making.
  • Python supports the usual logical conditions from mathematics:
    • Equals: a == b
    • Not Equals: a != b
    • Less than: a < b
    • Less than or equal to a <= b
    • Greater than: a > b
    • Greater than or equal to a >= b

PYTHON IF STATEMENT

  • The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if-block. The condition of if statement can be any valid logical expression that can be either evaluated to true or false.
  • Syntax

  • When the above code is executed, it produces the following result −


THE ELSE STATEMENT
  • An else statement can be combined with an if statement.
  • An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
  • The else statement is an optional statement and there could be at most only one else statement following if.
  • Syntax

  • Flow Diagram


THE ELIF STATEMENT

  • The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them.
  • We can have any number of elif statements in our program depending upon our need.
  • However, using elif is optional.
  • The elif statement works like an if-else-if ladder statement in C.
  • It must be succeeded by an if statement.
  • The syntax of the elif statement is given below.

  • Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows −


  • In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

SHORTHAND IF

  • If you have only one statement to execute, you can put it on the same line as the if statement.
  • Example
  • One line if statement:

SHORTHAND IF ... ELSE

  • If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:
  • Example
  • One line if-else statement:
  • This technique is known as Ternary Operators or Conditional Expressions.

SHORTHAND IF ... ELSE ..IF

  • You can also have multiple else statements on the same line:
  • Example
  • One line if-else statement, with 3 conditions:
AND

  • The and keyword is a logical operator and is used to combine conditional statements:
  • Example
  • Test if a is greater than b, AND if c is greater than a:

OR

  • The or keyword is a logical operator and is used to combine conditional statements:
  • Example
  • Test if a is greater than b, OR if c is greater than a:

NESTED IF

  • You can have if statements inside if statements, this is called nested if statements.

THE PASS STATEMENT

  • if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.


PYTHON LOOPS

  • The flow of the programs written in any programming language is sequential by default. Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of times.
  • For this purpose, The programming languages provide various types of loops that are capable of repeating some specific code several numbers of times.
  • Consider the following diagram to understand the working of a loop statement.

WHY DO WE USE LOOPS IN PYTHON?

  • The looping simplifies the complex problems into 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 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 that runs up to 10 iterations.
  • There are the following advantages of loops in Python.
    • It provides code reusability.
    • 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).

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.
  • This is less like the for a keyword in other programming languages and works more like an iterator method as found in other object-orientated programming languages.
  • With the for loop we can execute a set of statements, once for each item in a list, tuple, set, etc.
  • The syntax of for loop in python is given below.

  • Flow Diagram

  • Example: Print each fruit in a fruit list

  • Output

  • The for loop does not require an indexing variable to set beforehand.
  • Example: Iterating string using for loop

  • Output

  • Example: Program to print the table of the given number.

  • Output

  • Example: Program to print the sum of the given list.

  • Output

  • Even strings are iterable objects, they contain a sequence of characters:
  • Example: Loop through the letters in the word “AMIT":

  • Output

FOR LOOP USING RANGE() FUNCTION

  • To loop through a set of code a specified number of times, we can use the range() function,
  • The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
  • If we pass the range(10), it will generate the numbers from 0 to 9.
  • The syntax of the range() function is given below.
  • Syntax:

FOR LOOP USING RANGE() FUNCTION

  • The start represents the beginning of the iteration.
  • The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4 iterations. It is optional.
  • The step size is used to skip the specific numbers from the iteration. It is optional to use. By default, the step size is 1. It is optional.
  • Consider the following examples:

  • Output

  • Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
  • Example: Program to print numbers in sequence.

  • Output

  • Consider the following examples:

  • Output

  • Example: Program to print a table of a given number.
  • Output

  • The range() function defaults to 0 as a starting value, however, it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
  • Example: Using the start parameter:

  • Output

  • The range() function defaults to increment the sequence by 1, however, it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
  • Example: Increment the sequence with 3 (default is 1):

  • Output

  • Example: Program to print even number using step size in range().

  • Output

  • We can also use the range() function with a sequence of numbers. The len() function is combined with range() function which iterate through a sequence using indexing. Consider the following example.

  • Output

NESTED FOR LOOP IN PYTHON

  • Python allows us to nest any number of for loops inside a for a loop. The inner loop is executed n number of times for every iteration of the outer loop. The syntax is given below.

  • Example: Nested for loop

  • Output

  • Example: Program to number pyramid.

  • Output

  • Example: Print each adjective for every fruit:

  • Output

ELSE IN FOR LOOP

  • Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the for loop which can be executed only when all the iterations are exhausted. Here, we must notice that if the loop contains any of the break statements then the else statement will not be executed.
  • Example

  • Output

  • The for loop is completely exhausted since there is no break.
  • Example: Print all numbers from 0 to 5, and print a message when the loop has ended:

  • Output

THE BREAK STATEMENT

  • With the break statement we can stop the loop before it has looped through all the items:
  • Example: Exit the loop when x is "banana":

  • Output

  • Example:

  • In the above example, the loop is broken due to the break statement; therefore, the else statement will not be executed. The statement present immediate next to else block will be executed.
  • Output

  • The loop is broken due to the break statement...came out of the loop.

THE CONTINUE STATEMENT

  • With the continue statement, we can stop the current iteration of the loop, and continue with the next:
  • Example: Do not print banana:

  • Output

THE PASS STATEMENT

  • for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
  • Example

PYTHON WHILE LOOP

  • The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop.
  • It can be viewed as a repeating if statement. When we don't know the number of iterations then the while loop is most effective to use.
  • The syntax is given below. 

  • Here, the statements can be a single statement or a group of statements. The expression should be any valid Python expression resulting in true or false. The true is any non-zero value and false is 0.
  • Flow Diagram
  • Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. 
  • Example

  • Output

  • The block here, consisting of the print and increment statements, is executed repeatedly until the count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.
  • Example: Program to print 1 to 10 using while loop

  • Output

  • Example: Program to print table of given numbers.

  • Output

INFINITE WHILE LOOP

  • If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it turns into the infinite while loop.
  • Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.
  • Example

  • Output

  • Example

  • Output

USING ELSE WITH WHILE LOOP

  • Python allows us to use the else statement with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for loop, if the while loop is broken using break statement, then the else block will not be executed, and the statement present after else block will be executed. The else statement is optional to use with the while loop. Consider the following example.
  • Example

  • Output

  • In the above code, when the break statement is encountered, the while loop stopped its execution and skipped the else statement.
  • Example: Program to print Fibonacci numbers to a given limit

  • Output

USING NESTED LOOP

  • Python programming language allows using one loop inside another loop. The following section shows a few examples to illustrate the concept.
  • Syntax

  • The syntax for a nested while loop statement in the Python programming language is as follows −

  • A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.

USING ELSE WITH WHILE LOOP

  • Example: - The following program uses a nested for loop to find the prime numbers from 2 to 100 −

  • Output

PYTHON CONTROL STATEMENTS
  • Control statements in python are used to control the order of execution of the program based on the values and logic. Python provides us with 3 types of Control Statements:
    • Break
    • Continue
    • Pass
PYTHON BREAK STATEMENT
  • The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control go to the next line after the loop.
  • The break is commonly used in the cases where we need to break the loop for a given condition.
  • The syntax of the break is given below.
  • Flow Diagram
  • Example:
  • Output
  • Example:
  • Output
  • Example:

PYTHON CONTINUE STATEMENT
  • The continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the loop and starts with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular condition. The continue statement in Python is used to bring the program control to the beginning of the loop.
  • Syntax
  • Flow Diagram
  • Example
  • Output
  • Observe the output of the above code, the value 5 is skipped because we have provided the if condition using with continue statement in while loop. When it matched with the given condition than control transferred to the beginning of the while loop and it skipped the value 5 from the code.
PASS STATEMENT
  • The pass statement is a null operation since nothing happens when it is executed. It is used in the cases where a statement is syntactically needed but we don't want to use any executable statement at its place.
  • For example, it can be used while overriding a parent class method in the subclass but don't want to give its specific implementation in the subclass.
  • Pass is also used where the code will be written somewhere but not yet written in the program file. Consider the following example.
  • Example
  • Output

Comments

Popular posts from this blog

Modules

Classes and Objects