Custom Search

PYTHON: while

- a loop mechanism for iteration

In Python, setting a 'while condition: block' instruction makes the computer keep executing the block while the condition is true.

If the condition for looping is always true it will lead to an infinite loop. You therefore have to put in a 'break instruction'. At that point the computer starts executing whatever code follows the loop.

You can do this by using the 'if: else' command.

 

 

cost = 0

items = 0

while True:

Note the form of 'True' - you must put a capital letter, then lowercase for it to 'work' (be recognised as Python code)

loop=input("Do you wish to add an item? y/n")

if loop == "n":

To check if two values or variables are equal, we write two equal signs , because a single equal sign is the assignment instruction.

break

Note the form of 'break' - you must put a capital letter, then lowercase for it to 'work' (be recognised as Python code)

 

else:

answer = input("Price of ordered item? £")

price = float(answer)

Remember that input() returns a 'string' and we have to convert it to a 'number' to do calculations with it... in this case a decimal form - so we need to employ the float() function.

items=items+1

cost=cost+price

print ("Total cost of ",items, "items ordered: £", cost)