Course On Python Basics UNIT - 5: FLOW CONTROL IN PYTHON Structure 5.0 Learning Objectives 5.1 Introduction to Flow Control 5.2 Flow control using if-else in Python 5.3 For Loops in Python 5.4 While Loops in Python 5.5 Loop control statements in Python 5.6 Summary 5.7 Glossary 5.8 References Page 1 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 5.0 Learning Objectives After studying this unit, you will be able to: • Understand Flow Control in Python programming • Understand the use of ‘if-else’ and its types in Python • Use ‘For loop’ in Python • Understand the use of the ‘While loop’ in Python • Use various loop control statements 5.1 Introduction to Flow Control The sequence wherein individual statements, commands, or function calls in an imperative program are performed or evaluated is known as the flow of control in computer science. An imperative programming language is distinguished from a declarative programming language by its emphasis on explicit control flow. A control flow statement is a statement in an imperative programming language that causes a decision to be made between two or more pathways. Functions and language features exist in non-strict functional languages to achieve the same objective, although they are rarely referred to as control flow statements. A block, in turn, is a collection of statements that, in contrast to grouping, also specifies lexical scope. Interrupts and signals are low-level processes that can change the flow of control in a similar way to a subroutine, but they usually happen in response to an external stimulus or event (that can happen Page 2 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics asynchronously), rather than as a result of the execution of an in-line flow control statement. Control flow instructions function by changing the program counter at the computer language or assembly language level. Conditional or unconditional clearly elaborated, often known as leaps, are the sole control flow instructions available for some Central Processing Units (CPUs). It should be obvious why we should have python flow control by now. We require flow control to select the flow for your program and make it function precisely the way you want it to. We also use it in our day-to-day lives. For example, before crossing the street, we check to see if it is safe to do so. If such is not the case, we will wait till safety is established before crossing. We're basically making judgments and directing the code on how to run in certain conditions, such as which statement should execute before or after another, and so on. 5.2 Flow Control using if-else in Python In real life, there are times when we must make decisions and then determine what to do next based on those decisions. Similar circumstances exist in programming, where we must make judgments and then execute the following block of code depending on those decisions. In programming languages, decision-making statements determine the course of program execution. The if-else elif statement is being used to make decisions in Python. Page 3 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics • if statement: The if condition is the most basic decision-making condition. It is used to determine if a statement or a block of statements will run or not, i.e., if a condition is true, a block of statements will be performed; otherwise, it will not. Syntax: if condition # Statements to execute if # condition is true After examination, the condition will either be true or false. If indeed the value is true, the if statement will run the sequence of code below it; otherwise, it will not. We may also use a condition using the bracket '(' ')'. Python utilizes indentation to distinguish blocks, as we all know. As seen in the example below, the block behind the if statement would be identified if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block. Page 4 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Output: Page 5 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Because the if statement's condition is false. As a result, the part below the if statement is skipped. • if-else statement: If a condition is true, the if statement will run a block of statements; if the condition is false, the if statement will not. But what if the condition is false and we'll be doing something else? This is when the else statement comes in. When the condition is false, we may combine the else statement with the if statement to run a block of code. Syntax: if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false Page 6 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Output: Page 7 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics • nested-if statement: An if statement that has been the focus of another one if statement is known as a nested if. An if statement within another if statement is referred to as nested if statements. Yes, we may stack if statements within if statements in Python. We may put an if statement within another if statement. Syntax: if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here Page 8 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Output: • if-elif-else ladder statement: A user can choose from a variety of alternatives here. From the top- down, the if statements are performed. The statement linked with that if is performed as soon as one of the criteria controlling the if is Page 9 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics true, and the rest of the ladder is bypassed. The last else line will be performed when none of the criteria are true. Syntax: if (condition): statement elif (condition): statement . . else: statement Example: Page 10 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Short Hand if statement: Shorthand can be used when just a single statement has to be processed inside the if block. The if statement and the statement can be on the same line. Syntax: if condition: statement Example: Page 11 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Short Hand if-else statement: If there is just one statement to be performed in both the if and else blocks, this may be used to put the if-else statements on a single line. Syntax: statement_when_True if condition else statement_when_False Page 12 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Output: Page 13 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 5.3 For Loops in Python In Python, the for loop can be used for sequential traversal, that is, iterating over an iterable such as a string, tuple, list, and so on. It belongs to the definite iteration category. The number of repeats is explicitly determined in advance with defined iterations. There seems to be no C approach for looping in Python, i.e. for (i=0; in; i++). There is a \"for in\" loop, which is analogous to other languages for each loop. Let's have a look at how to utilize them for in-loop to do sequential traversals. Syntax: for var in iterable: # statements’ Example: The iterable in this example is a group of objects such as lists and tuples. For every item in an iterable, the nested statements inside of the for loops are performed once. Each time the loop is run, the variable var is set to the value of the iterable's next item. Page 14 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Page 15 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Page 16 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics • Python for loop with range() function: When a user has to repeat an activity a certain number of times, range() is a built-in method in Python. range() in Python 3.x is simply a renamed version of the Python method xrange() (2.x). The range() method is used to create a numeric series. Depending on the amount of arguments sent to the function, the user may determine where the sequence of integers will begin and stop, as well as how much the difference amid one integer and the next will be. range() accepts three parameters in total. ➢ start: the first integer in the sequence of integers to be returned. ➢ stop: the integer before whereby the integer sequence should be returned. The integer range ends at stop – 1. ➢ step: The increase among each integer in the series is determined by this integer value. Page 17 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 18 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Python for loop with else statement: The usage of else statements has indeed been reduced in most computer languages (C/C++, Java, and so on) in favor of if conditional statements. With for loops, Python additionally allows us to employ the else condition. Page 19 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Output Page 20 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 5.4 While Loop in Python In Python, While Loop is a programming construct that is used to continually execute a set of statements until a condition is met. When the condition in the program turns false, the next line directly following the loop is performed. While loop is classified as an indefinite iteration. The majority of the time the loop is run isn't set explicitly in advance, which is known as indefinite iteration. Syntax: while expression: statement(s) After a programming construct, any lines recessed by the same number of character spaces are regarded to be included in a single block of code. Python's way of grouping statements is indentation. When a while loop is run, expr is assessed in a Boolean context first, and then the loop body is run if it is true. The expr is then checked again, and if it is still true, the body is run once more, and so on until the expression is false. Page 21 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Output: Page 22 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics • While loop with else statement: As previously stated, the while loop performs the block till a condition is met. The statement immediately following the loop is performed when the condition turns false. Whenever your while condition is false, the else clause is performed. It will not be run if you exit the loop or if an exception is triggered. Example: Page 23 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 5.5 Loop control statements in Python In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely quit the loop, skip an iteration, or ignore the condition. Loop control statements can be used to do this. Control statements in loops alter the execution sequence. All automated objects generated in scope are deleted when execution exits that scope. The following three statements are supported by Python. • Break Statement: When an external condition is triggered, the break statement in Python is often used to pull the control out of the loop. Inside the loop, the body is a break statement (normally afterward if condition). Page 24 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 25 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Both loops in the above example are iterating the string 'pythonforbegineers,' and when they reach the character t' or 'g,' the if condition is true, and the flow of execution is taken out of the loop. • Continue Statement: In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely quit the loop, skip an iteration, or ignore the condition. Loop control statements can be used to do this. Continue is a loop control statement that allows you to change the loop's flow. The continue statement is a loop control statement that forces the loop to execute the next iteration while skipping the rest of the code inside the loop for the current iteration only. Whenever the continue statement is executed inside the loop, the code inside the loop following the Page 26 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics continue statement is skipped for the current iteration only, and the loop's next iteration begins. Example: Consider the following scenario: you need to develop a programme that produces numbers from 1 to 10, but not 4. It is mentioned that you must perform this with a loop, and that you may only use one loop. Here's when the continue statement comes into play. What we should do here is execute a loop from 1 to 10 times, comparing the number of the iterator with 4 each time. If it equals 4, we'll use the continue statement to skip to the next iteration without writing anything; otherwise, the value will be printed. Page 27 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: • Pass Statement: A null statement is the pass statement. The distinction among pass and comment is that the interpreter ignores comment, but pass is not. When the user is unsure of what code to write, the pass statement is typically used as a placeholder. As a result, the user merely types pass at that line. Whenever the user does not wish any code to run, pass is sometimes used. So, in places where empty code isn't permitted, such as loops, function declarations, class definitions, or if statements, the user can just pass. As a result, by utilising the pass statement, the user avoids this problem. Page 28 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: The pass statement get executed only when the condition is true. Page 29 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 5.6 Summary In this module we have learned about: • Flow control in Python in this module. • We understood that flow control is just a method of controlling the code by making specific judgments and keeping track of which statements should be executed and which should be ignored. • To do so, we have learned about many forms of conditional statements, including the if, if-else, and if elif else conditions. • We also learned about for and while loops, as well as their applications Page 30 of 31 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 5.7 Glossary • Imperative programming: Imperative programming is a software programming paradigm that employs statements to modify the state of a program. • Declarative programming: Declarative programming includes describing the job or desired outcome rather than the control flow for logic necessary for software to complete an activity. • Iterable: Any Python object that can yield its members one at a time, allowing it to be iterated over in a for-loop is called an iterable. • Traversal: Processing every character in a string, generally from left to right, is known as traversal. 5.8 References • https://docs.python.org/3/ • https://docs.python.org/3/tutorial/controlflow.html • https://www.oreilly.com/library/view/python-in- a/0596001886/ch04s09.html • https://pynative.com/python-control-flow-statements/ Page 31 of 31 All Rights Reserved. Vol. TLE001/03-2022
Search
Read the Text Version
- 1 - 31
Pages: