Thursday, February 29, 2024

FLOW CONTROL IN PYTHON

Python Flow Control

Introduction

  • Conditional Statements (if, elif, else)
  • Indentation 
  • Looping Constructs (for and while loops)
  • Break and Continue Statements
  • Iterative Over Sequences
  • Nested Loops and Conditional Statements
  • Range Function
  • Looping Through Dictionaries
  • Enumerate Function

After learning Python's basics, we may move on to more advanced topics. Python programmers must understand flow control. As the name indicates, flow control in Python requires program execution route knowledge. If a condition is met, the different flow control statements in Python execute a piece of the program; otherwise, it runs Python code.

Control flow and syntax in Python

The structures and procedures that help programmers control flow in Python statement execution order are called flow control in Python. It allows decisions, conditional code execution, and program execution flow control.

figure shows a flowchart to tell us what to do if it's raining.

As we can see in the above Python control flow statement/chart there is more than one way to go from start to end. This is the same for the codes we write in the computer program. In flow control charts the diamonds represent the branching points and the rectangles represent the other steps. The starting and ending steps are represented by a rounded rectangle.

Gaining a deeper understanding of how control flow statements in Python express yes/no options and these branching points is essential to comprehend flow control. To further understand, let's examine comparison operators, Boolean values, and Boolean operators in more detail.

Boolean Values

Similar to integer, text, and floating-point data types, boolean data types can only be True or False. However, Python's text, integer, and floating-point data types have unlimited values. Unlike strings, Python program flow control Boolean values are usually expressed with lowercase letters and a capital T and F. Code samples help understand Boolean values:

Comparison Operators

Programmers often compare values. We use a comparison operator then. Python provides extra comparison operators. These comparison operators compare two integers and yield a Boolean value. The table below lists all Python comparison operators.

Operator

Meaning

==

Equal to

!=

Not equal to

< 

Less than

> 

Greater than

<=

Less than or equal to

>=

Greater than or equal to

The above operators evaluate the True and False values depending on the values we pass to them. Let's look at some code for better understanding starting with == to !=.

The == operator evaluates both sides in the code above. Returns True if variables are equal, False otherwise. Similarly, the following operator!= (not equal) returns True if the two numbers aren't equal and False otherwise. The == and!= operators work with any data type. See this in programs with different data types.

The following code tests data types using == and!= operators. Remember that comparing strings to numerical types (e.g., integers or floating-point numbers) returns False, whereas comparing integers to floating-point numbers returns True if the values are equal.

The operators >, \=, and \ are not the same as >=. All data types except integers and floating-point numbers are incompatible with these operations. For the first operator < (less than), the left side result must be lower than the right side result. The second operator, >, compares left and right values to see whether the left is greater. Make sure the left and right numbers are equal using the third operator, <= (less than or equal to). The last operator, >=, checks if the left and right numbers are equal or larger. Since we have code examples, let's analyze them.

The code above shows all the circumstances and expected outcomes from the preceding paragraph.

The assignment operator "=" is also used extensively. A single '=' symbol represents it. On the graph, the variable is on the left and the value is on the right, representing its assignment. First, some example codes will be examined.

Here, we utilize the <= operator with 43 values to compare 'eggplant', which has 42 values previously assigned in the code.

The == operator (equal to) uses two equal signs, unlike the = operator (assignment). This is why people often confuse these two operators, however understanding the following helps us distinguish them.

  • The == operator (equal to) determines whether two numbers are equal if they are.
  • The value of the variable is assigned from its right side to its left side using the assignment operator =.
Boolean Operators
Boolean operators for value comparisons are and, or, and not. They evaluate these expressions to Booleans like the comparison operator. Start with the "and" operator and examine each one.

Binary Boolean Operators

The "and" and "or" operators are regarded as Binary Boolean Operators since they can only ever take on two values. The "and" operator evaluates the expression to True if both of the binary input values are True. If neither of the input values is True, it returns False. We may now look at the code that uses the "and" operator.


Now let’s look at the truth table of “and” operator

Expression

Evaluates to…

True and True

True

True and False

False

False and True

False

False and False

False

Due to the "and" operator's True values, all rows of the truth table except the first are False. The truth table shows all Boolean operation outcomes.

Next, we'll study the "or" operator. If one Boolean value is True, the expression is True; otherwise, it is False. Looking at the code may help.

The preceding code shows that all values are true unless there's just one true, which yields False. Next, examine the "or" operator's truth table.

Expression

Evaluates to…

True or True

True

True or False

False

False or True

False

False or False

False


The not Operator

Unlike the "and" and "or" operators, it processes one Boolean value at a time. All you need to flip a Boolean variable is the "not" operator. The "not" operator on a Boolean variable assigned to True returns False, and vice versa. We may inspect a code sample to understand.

From the above code, we can see that the "not" operator inverts Boolean values, turning "not True" into "False." The value of "not False" changes from True in the first not to False in the second not and vice versa in the third code.

Let's look at it truth table:

Expression

Evaluates to…

not True

False

not False

True

In the above truth table, we can see the True value becomes False and the False expression with the “not” operator becomes True.

Mixing Boolean and Comparison Operators

All Boolean expressions are compatible with comparison operators since they evaluate Boolean values. Because they often work with True and False, Boolean operators are also known as "and," "or," and "not" operators. Despite the lack of a Boolean operator in the comparison operator 4 < 5, the equation yields a Boolean result. Look at some code to understand.

The code checks if numbers are less than or equal to in brackets. The code's comparison operator analyzes bracket values to see if they satisfy the Boolean operator. They return True if the Boolean operator is met and False otherwise. The graphic from "Automated Boring Stuff with Python" below illustrates the coding process.



Elements of Flow Control
In programming, we often need to check a statement to advance the program or manage its execution. In addition, flow control statements usually begin with conditions and terminate with clauses. 

Conditions

Everything has demonstrated that the condition is Boolean. Because conditions always return True or False Booleans, they simplify flow control statements. The flow condition underpins all flow control statements, affecting program activity based on its true or false conclusion. 


Block of Code

Coding languages let us chunk code. Python uses sections of code separated by line space. In block world, three laws apply.

  • Blocks begin when the indentation increases.
  • Blocks can contain other blocks.
  • Blocks end when the indentation decreases to zero or a containing block’s indentation.
By looking at the indentation we can understand where a block of code started, but for better understanding let’s look at a basic code that shows the block of codes.

The first block begins before the first "if" statement; the line is indented after "if". The second "if" and the one following "else" are identical. Each code snippet above calls print() with one line.

Flow Control Statements

We've covered conditions and flow management, but we're not ready to dig further. The introductory figure's diamonds indicate flow control statements.


If Statements

The most common flow control expression is "if". The statement runs only if it is True in the "if" statement flow control; otherwise, it passes the condition and moves on to the next program region.

"If the condition is true, execute the next line; otherwise, forget it."" is another technique to simplify a "if" expression. Computer programming follows the same logic. Here are several Python "if" statement features:

  • The “if” keyword
  • A condition (it is an expression that evaluates to True or False)
  • A Colon
  • Starting on the next line, an indented block of code (it is called the if clause)
For a better understanding of the “if” condition let’s look at the code:

The output of the line that says "Hi, Alice." is demonstrated by the fact that the name is True in the code that is presented above. This indicates that the if condition is put into action. Please have a look at the flow diagram of the if statement so that you can better understand it.


Else Statements

We utilize a "if" statement to verify a condition and a "else" to execute a "false" condition. This "else" sentence executes the false statement. Simply put, if one condition is true, its claim is true. Consider running the code after the if statement. Since a code else statement does not include a condition, we may apply the following ideas to say:

  • The “else” keyword
  • A colon
  • Starting on the next line, an indented block of code (called the else clause)
For better understanding let’s look at the code that has both if and else because else is always followed by an “if” condition/statement.

The code above initializes the name with "Bob." Then, the if condition checks for "Alice" in the name. Since it's "Bob," the "if" condition doesn't execute, so the program ignores it and proceeds on to the otherwise statement, which always executes False. Let's look at the if-else statement flowchart for clarity.


In the above flowchart diagram, we can see the working principle of the “if-else statement”. That is when if the condition is False then the else block of code will execute. 

Elif statements

The code above initializes the name with "Bob." Then, the if condition checks for "Alice" in the name. Since it's "Bob," the "if" condition doesn't execute, so the program ignores it and proceeds on to the otherwise statement, which always executes False. Let's look at the if-else statement flowchart for clarity.

  • The “elif” keyword.
  • A condition (that is, an expression that evaluates to True or False)
  • A colon
  • Starting on the next line, an indented block of code (called the elif clause)
Let’s look at the different codes of “elif” for better understanding. In the first code, we have only one if statement/condition that is followed by an “elif” condition. 

The code shows that the if condition runs only if the age is less than 12, but when both "if" and "elif" are True, the "elif" condition runs regardless. The code below shows it.


Let’s look at the above codes flowchart for a better understanding of their working.

When both conditions are False, the program bypasses the "if" condition and proceeds right to the conclusion without executing any condition, but the "elif" condition will still run and execute the age code. We can't declare which assertion is "True." If even one is false, the program's conditions will ignore them. Elif statement chains only execute the first or final clause. If the statement's conditions are fulfilled, the subsequent "elif" clauses are skipped. This case may be examined using Python programs.

The code skips the "elif" condition when the condition matches or is True, therefore when the condition matches the name, it skips all the code. We must also change the code in the preceding part in the right order as it checks age 2000 first, which is more than 100. If someone is over 100 but under 2000, their code condition will execute.


With the name variable changed from "100" to "age," the code can now verify if the age is more than 2000. This is because it prints "You are not Alice, the grannie." after ignoring the age > 2000 condition if the age is more than 100, which is True. At this point, we can see if the age is more than 3000.

To ensure that the program outputs anything, we may include one "else" line after the final "elif" condition. Put simply, it guarantees that each clause will be executed. Here, the else clauses are executed if every single "elif" expression returns False. To better understand it, we shall examine the Python code.

In the above code, we can see that both the “if” and “elif” conditions are False therefore else statement will run and we can see that in the output also. Let’s look at the flowchart of the “if-elif-else” flow control.

In the above diagram, we can see that if all the conditions are False then the last condition which acts like the else statement will execute.

Loops

Programmers often rerun lines, functions, and portions of code. We should automate it since continual coding wastes time, space, and money. We use loops to overcome this constraint. Python has several loop types found in all programming languages. The while, for, and break statements are these.


While Loop Statements

We may repeat the code with a while statement. While loop or statement code runs until one condition is false or the criteria are fulfilled, in this instance True. Each statement must include the following:

  • the “while” keyword
  • a condition (that is, an expression that evaluates to True or False)
  • A colon
  • Starting on the next line, an indented block of code (called the while clause)

The words above show it's comparable to the "if" statement. They behave differently. A program performs the code within the while clause, but if it exits it, it returns to the beginning of the while statement and executes until the condition becomes false, unlike the "if" statement, which advances the program.

Here's the code for the "if" and "while" statements to see how they differ and what they produce during program execution.

The "if" statement in the preceding code prints "Hello world" when the condition is met. We want it to repeat the code, but it doesn't. Prints "Hello world" once if the condition is true after checking. The "while" statement lets us study the same code.

The code above repeats the "while" statement five times to keep the program running until the spam count drops below 5. We increment the spam count by one with each successful execution, thus the code runs until the "while" condition is True.

The "while" sentence is useful for printing frequently, but it has several drawbacks that we should consider.

While loops can form unending cycles, a major drawback. A program may not quit if the loop condition is not properly updated inside the loop body or if a logical error causes the loop to run forever.

While loops can yield more sophisticated code than the for loop. A for loop can enhance syntax and readability when iterating through a known-length series.

Loop variables must be managed carefully during startup and update. This might cause loop execution errors or unexpected behavior.

Loops often use external variables to influence their execution. Changing these variables elsewhere in the program might affect the loop unexpectedly. This external state dependence complicates matters.

Performance issues: the while loop may be more expensive than the "for" loop. Iterating over a predetermined sequence with a for loop is typically more efficient than "while" loops, which may need unnecessary condition checks.

Let's examine the statement's flowchart to comprehend the software's "while" loop.

The figure shows how the "while" loop works. After 5 spam messages, the condition becomes False, the loop ends, and the program either continues to the next block of code or instruction (if given) or finishes. When spam is less than 5, the loop returns to iteration 1. Consider programming where the "while" loop isn't working and more loops are needed.


The "while" loop in the given code creates an infinite loop, which is unsuitable for programming. The loop ended when we modified the order of "Your name" in the input.

The while loop can get caught in an endless loop. If this happens, use CTRL-C to stop the application. We mistakenly constructed a condition that is always True, therefore the while loop keeps running. We may now inspect the code that meets this requirement.


In the above code, the while condition is always true therefore print statement runs infinitely.

Break Statements

A break statement can terminate the while loop mid-condition fulfillment. Used as a shortcut to terminate the while loop clause early. When a while loop statement is reached, it finishes immediately. Adding "break" to the while clause is enough to implement the break statement in the loop. This code is identical to the last one but adds a "break" statement to the while clause.

Since its condition is always True, the while loop in the following code will print out whatever is entered endlessly. An if condition breaks the while loop anytime the user enters "your name" in the same sequence to stop the loop. After "your name" is entered, the software leaves the while clause and prints. It departs after printing the name. Break statements are used in while loops to loop until a condition is not fulfilled.

Continue Statements

Loops use the continue statement like the break statement. The program instantly returns to the loop's beginning and reevaluates its status when it reaches a "continue" statement. The continue command returns the loop to its start.

See the sample code to understand the continue statement:


The code excerpt shows that if the name is not "Rohit," the program goes to the continue statement, which re-executes the while loop. If the name is right, the code skips continue, moves to the next line, prints the message, and asks for the password. However, if the password is wrong, the code restarts the while loop. Our input was right, thus the application broke or terminated. So it continued to the next line, printed the last line, and stopped.


Note: Conditions treat various other data types as True and False. False are 0, 0.0, and '' (the empty string) when applied to the criterion, whereas True are all others.

For loops and the range() Function

The for loop is better when we know how long to repeat the condition or loop, while the while loop is better when we don't or when only one condition needs to halt, modify progress, or continue other portions of the program. A "for" loop and range() will work.

Python's for loop always says "for i in range(5)":

  • The “for” keyword
  • A variable name
  • The “in” keyword
  • A call to the range() method with up to three integers passed to it 
  • A colon
  • Starting on the next line, an indented block of code (called the for clause)
Let's look at the code using which uses for loop to better understand it.

The program structure is shown in this code: First, "My name is" is printed, then the "for" loop defines "i" and range(). Range() receives the number of iterations, such as 5. Python's range function starts at 0 and terminates at the integer's outer bound, therefore the program runs five times from 0 to 4, not 5. Since we're in the loop, the program will display the message on the following line and increase "i" by 1. If everything remains inside 5, we'll print the message. We'll continue until "i" equals 5, then terminate the loop and go on if there's further code. Because of this Python for loop constant, setting the upper range to 10 always goes down to 9, or 10-1, or n-1 in arithmetic. The maximum value in the range is here.


Note: Remember that "for" loops enable "break" and "continue" declarations. The "continue" statement will advance the counter if the "for" loop terminates and the program restarts. We can only use "continue" and "break" in "while" and "for" loops. Python will throw an error if we use these statements elsewhere.

The Starting, Stopping, and Stepping Arguments to range()

Comma-separated arguments are accepted by some computer functions. Python's range() method is in this class. We may set the range function's starting value (zero by default), iterations, and steps between iterations. Examine the Python code to understand.

Since Python does not have an upper bound, the count will only go to 19, and the third input is the step between iterations or outputting two digits. In the code above, commas separate the loop's start and endpoints. We concluded that the number ranged from 12 to 20 with a standard deviation of 2. Pass the less value as a second parameter to reduce it top-to-bottom. However, we must pass the third argument as negative. If the first argument is bigger than the second or endpoint argument and the step or final argument is negative, the "for" loop lowers with each iteration. Python programming can help us understand this.


Importing Modules

Built-in functions are available to all Python programs. This category includes print(), input(), len(), and others. Python's standard library includes several modules. Python programs use modules, a collection of functions. The math module houses math operations, the random module houses random number operations, etc.

Python can't use module methods without an import declaration. A source code import statement includes:

  • The import keyword
  • The name of the module
  • Optionally, more module names, as long as they are separated by commas

Importing the module activates all its functionality. Let's try the random module to understand how to import and use Python modules. This example uses random.ranint().

We used the random module's randint function and imported it using the import keyword. By passing numbers 1 and 10, we limit the random.randint() method's output. The minimum is one, maximum is 10.

From import Statements

The "from" keyword, module name, "import" keyword, and asterisk (*) constitute an alternative Python module import syntax. Example: "from random import *". This lets you call "random" module functions without prefixing them. Some prefer the traditional import statement, which lists the module name before invoking its functions. Code readability and function identification are improved by using the whole module name.


Summary

One of Python's most essential features is flow control, which lets developers organize code execution based on criteria. Boolean values and comparison operators are essential to Python decision-making. Comparison operators like ==,!=, <, >, <=, and >= determine Boolean values (True or False). The equality operator (==) and the assignment operator (=) are different.

Boolean operators like "and," "or," and "not" create programming flow by comparing terms to True or False. These operations let you combine criteria and modify program direction.

Using flow control words like "if," "else," and "elif," programmers may execute different code portions based on the situation. Use the "if" statement to choose and the "else" statement to handle false first conditions. You can evaluate several conditions sequentially using "elif".

Multiple loops in Python allow code to be executed repeatedly. If a condition is true, the "while" loop continues. Avoid endless loops by being careful. The "break" statement stops the loop early when a condition is met for safety.

The "for" loop and "range()" function can structure the procedure when the number of iterations is known. It has an indented code block, variable name, "for" keyword, "range()" call to calculate iterations, and "in" keyword. You may control flow statements with examples in Python loop flow with "break" and "continue" commands.

Python may be strengthened by adding modules with relevant functionality. While "from import" is an option, "import math," a more standardized import language, is easier to comprehend.

To conclude, Python loops and flow control structures in Python are essential for fast, intelligent applications. It helps programmers navigate the execution sequence, which is essential for ensuring code works in all settings.

No comments:

Post a Comment

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular