Computer Science, asked by massmuthu10, 3 months ago

Write a for statement that allows the loop body execution 10 times

Answers

Answered by farhaanaarif84
0

Answer:

In this chapter, you will learn how to make the computer execute a group of statements over and over as long as certain criterion holds. The group of statements being executed repeatedly is called a loop. There are two loop statements in Python: for and while. We will discuss the difference between these statements later in the chapter, but first let us look at an example of a loop in the real world.

A petrol attendant performs the following actions when serving a customer:

greet customer

ask for required type of petrol and amount

ask whether customer needs other services

ask for required amount of money

give money to cashier

wait for change and receipt

give change and receipt to customer

say thank you and goodbye

A petrol attendant performs these steps for each customer, but he does not follow them when there is no customer to serve. He also only performs them when it is his shift. If we were to write a computer program to simulate this behaviour, it would not be enough just to provide the steps and ask the computer to repeat them over and over. We would also need to tell it when to stop executing them.

There are two major kinds of programming loops: counting loops and event-controlled loops.

In a counting loop, the computer knows at the beginning of the loop execution how many times it needs to execute the loop. In Python, this kind of loop is defined with the for statement, which executes the loop body for every item in some list.

In an event-controlled loop, the computer stops the loop execution when a condition is no longer true. In Python, you can use the while statement for this – it executes the loop body while the condition is true. The while statement checks the condition before performing each iteration of the loop. Some languages also have a loop statement which performs the check after each iteration, so that the loop is always executed at least once. Python has no such construct, but we will see later how you can simulate one.

Counting loops are actually subset of event-control loop - the loop is repeated until the required number of iterations is reached.

If you wanted to get from Cape Town to Camps Bay, what loop algorithm would you use? If you started by putting your car on the road to Camps Bay, you could:

drive for exactly 15 minutes. After 15 minutes, stop the car and get out.

drive for exactly 8km. After 8km, stop the car and get out.

drive as long as you are not in Camps Bay. When you arrive, stop the car and get out.

Similar questions