Full Transcript

Unit-III Iterative Statements(Loops) Loops and their importance In a programming language, a loop is a statement that contains instructions that continually repeats until a certain condition is reached. Loops help us remove the redundancy of code when a task has to...

Unit-III Iterative Statements(Loops) Loops and their importance In a programming language, a loop is a statement that contains instructions that continually repeats until a certain condition is reached. Loops help us remove the redundancy of code when a task has to be repeated several times. With the use of loops, we can cut short those hundred lines of code to a few. Suppose you want to print the text “Hello, World!” 10 times. Rather than writing a print statement 10 times, you can make use of loops by indicating the number of repetitions needed. Loop Types The three types of loops in Python programming are: 1. while loop 2. for loop 3. nested loops while loop The while loop provides a mechanism to repeat one or more statements while a particular condition becomes True. The while loop is known as a indefinite loop because the programmer don’t know exactly how many times the loop will repeat. In while loop, the condition is tested before any of the statements in the statement block is executed. If the condition is True, only then the statements will be executed otherwise if the Condition is False, it is jump to next statement which is outside of the while loop. Syntax: while condition: statements(code) Rajiv Gandhi University of Knowledge Technologies Page 1 Inside the while loop, we can have any number of statements. The condition may be anything as per our requirement. The loop stops running when the condition fails (become false), and the execution will move to the next line just below the while loop. Flow Diagram of while loop It first checks the condition, executes the conditional code if the condition is TRUE, and checks the condition again. Program control exits the loop if the condition is FALSE. Example 1: Print the text “Hello, World!” 5 times. num_of_times = 1 while num_of_times

Use Quizgecko on...
Browser
Browser