Loop command statements¶

Introduction¶

In this chapter, you volition learn how to brand the computer execute a group of statements over and over as long every bit certain criterion holds. The grouping of statements being executed repeatedly is chosen a loop. There are two loop statements in Python: for and while . We volition hash out the difference between these statements later in the affiliate, but start allow u.s. await at an example of a loop in the real globe.

A petrol bellboy performs the following deportment when serving a client:

  1. greet customer
  2. inquire for required blazon of petrol and corporeality
  3. ask whether customer needs other services
  4. ask for required amount of money
  5. give money to cashier
  6. wait for change and receipt
  7. give modify and receipt to customer
  8. say thank you lot and good day

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

At that place are two major kinds of programming loops: counting loops and event-controlled loops.

In a counting loop, the estimator knows at the kickoff of the loop execution how many times it needs to execute the loop. In Python, this kind of loop is defined with the for argument, which executes the loop trunk for every item in some listing.

In an event-controlled loop, the estimator stops the loop execution when a condition is no longer truthful. In Python, you can use the while argument for this – it executes the loop body while the status is true. The while statement checks the status before performing each iteration of the loop. Some languages also accept a loop statement which performs the check after each iteration, then that the loop is always executed at least in one case. Python has no such construct, but we will run into later how you can simulate one.

Counting loops are really subset of upshot-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 past putting your motorcar on the route to Camps Bay, you could:

  • drive for exactly 15 minutes. Afterward 15 minutes, stop the car and go out.
  • bulldoze for exactly 8km. After 8km, finish the car and leave.
  • bulldoze every bit long as you are not in Camps Bay. When you get in, stop the car and go out.

The first two algorithms are based on counting – the showtime counts fourth dimension, and the 2d counts distance. Neither of these algorithms guarantees that you will arrive in Camps Bay. In the first instance, you might hit heavy traffic or none at all, and either fall brusk of or overshoot your desired destination. In the second case, you might detect a detour and stop upward nowhere near Camps Bay.

The third algorithm is event-controlled. You carry on driving as long as you are non at the embankment. The status you go along checking is am I at the beach nonetheless?.

Many existent-life activities are event-controlled. For example, you beverage as long as you are thirsty. You lot read the newspaper as long as you are interested. Some activities are based on multiple events – for example, a worker works as long as there is piece of work to do and the time is not 5pm.

The while statement¶

Python's event-controlled loop statement is the while statement. You should apply it when you don't know beforehand how many times y'all will have to execute the body of the loop. The while-torso keeps repeating as long as the condition is true. Here's a flow control diagram for the while statement:

None

The loop consists of three important parts: the initialisation, the status, and the update. In the initialisation step, yous set upwardly the variable which you're going to use in the condition. In the status pace, you perform a exam on the variable to see whether you should terminate the loop or execute the body some other time. And so, afterwards each successfully completed execution of the loop trunk, you update your variable.

Note that the condition is checked before the loop body is executed for the first time – if the condition is fake at the start, the loop body will never be executed at all.

Hither is a uncomplicated Python example which adds the start ten integers together:

                                full                =                0                i                =                one                while                i                <=                10                :                total                +=                i                i                +=                1              

The variable used in the loop condition is the number i , which you use to count the integers from ane to ten . Showtime you initialise this number to 1 . In the condition, you bank check whether i is less than or equal to 10 , and if this is truthful you execute the loop body. Then, at the end of the loop torso, you update i by incrementing it by 1 .

It is very of import that you increment i at the end. If y'all did not, i would always be equal to 1 , the condition would always be true, and your program would never terminate – we call this an infinite loop. Whenever you lot write a while loop, brand sure that the variable you lot employ in your status is updated inside the loop body!

Here are a few common errors which might event in an infinite loop:

                                x                =                0                while                x                <                three                :                y                +=                1                # wrong variable updated                product                =                i                count                =                1                while                count                <=                10                :                product                *=                count                # forgot to update count                x                =                0                while                x                <                5                :                print                (                ten                )                x                +=                i                # update statement is indented i level too little, and then it'due south outside the loop body                x                =                0                while                ten                !=                5                :                print                (                x                )                10                +=                2                # ten volition never equal 5, because we are counting in even numbers!              

You might exist wondering why the Python interpreter cannot catch infinite loops. This is known as the halting problem. It is impossible for a computer to detect all possible infinite loops in another program. Information technology is up to the developer to avoid space loops.

In many of the examples in a higher place, we are counting to a predetermined number, then it would really exist more appropriate for us to use a for loop (which will be introduced in the adjacent department) – that is the loop construction which is more commonly used for counting loops. Here is a more realistic instance:

                                # numbers is a list of numbers -- we don't know what the numbers are!                total                =                0                i                =                0                while                i                <                len                (                numbers                )                and                total                <                100                :                full                +=                numbers                [                i                ]                i                +=                1              

Here we add up numbers from a list until the total reaches 100. We don't know how many times we will take to execute the loop, because we don't know the values of the numbers. Note that we might reach the end of the list of numbers before the total reaches 100 – if we try to access an element beyond the cease of the list nosotros will go an error, so we should add a check to make certain that this doesn't happen.

Exercise 1¶

  1. Write a program which uses a while loop to sum the squares of integers (starting from ane ) until the total exceeds 200. Print the final total and the last number to be squared and added.
  2. Write a programme which keeps prompting the user to guess a give-and-take. The user is allowed up to ten guesses – write your code in such a style that the secret word and the number of allowed guesses are piece of cake to change. Print messages to give the user feedback.

The for statement¶

Python's other loop statement is the for statement. You should use it when you need to do something for some predefined number of steps. Before we await at Python's for loop syntax, nosotros volition briefly expect at the way for loops work in other languages.

Here is an case of a for loop in Java:

                                for                (                int                count                =                1                ;                count                <=                viii                ;                count                ++                )                {                System                .                out                .                println                (                count                );                }              

You can run across that this kind of for loop has a lot in mutual with a while loop – in fact, y'all could say that it's just a special case of a while loop. The initialisation step, the condition and the update step are all divers in the section in parentheses on the starting time line.

for loops are often used to perform an operation on every chemical element of some kind of sequence. If y'all wanted to iterate over a list using the classic-style for loop, you would accept to count from zilch to the cease of the list, and then access each listing element by its index.

In Python, for loops make this use case simple and easy past assuasive yous to iterate over sequences directly. Here is an case of a for statement which counts from i to viii:

                                for                i                in                range                (                1                ,                nine                ):                print                (                i                )              

As we saw in the previous chapter, range is an immutable sequence type used for ranges of integers – in this case, the range is counting from ane to 8 . The for loop volition step through each of the numbers in plough, performing the impress action for each one. When the end of the range is reached, the for loop volition exit.

You tin use for to iterate over other kinds of sequences too. Yous can iterate over a list of strings like this:

                                pets                =                [                "cat"                ,                "canis familiaris"                ,                "budgie"                ]                for                pet                in                pets                :                print                (                pet                )              

At each iteration of the loop, the next element of the list pets is assigned to the variable pet , which y'all tin can then access within the loop body. The example higher up is functionally identical to this:

                                for                i                in                range                (                len                (                pets                )):                # i volition iterate over 0, 1 and ii                pet                =                pets                [                i                ]                print                (                pet                )              

That is similar to the way for loops are written in, for example, Java. Y'all should avoid doing this, as information technology'south more difficult to read, and unnecessarily circuitous. If for some reason you need the alphabetize inside the loop as well as the list chemical element itself, you can utilise the enumerate part to number the elements:

                                for                i                ,                pet                in                enumerate                (                pets                ):                pets                [                i                ]                =                pet                .                upper                ()                # rewrite the listing in all caps              

Like range , enumerate also returns an iterator – each item it generates is a tuple in which the first value is the index of the element (starting at zero) and the 2nd is the element itself. In the loop higher up, at each iteration the value of the index is assigned to the variable i , and the element is assigned to the variable pet , as before.

Why couldn't we just write pet = pet.upper() ? That would just assign a new value to the variable pet inside the loop, without changing the original list.

This brings us to a mutual for loop pitfall: modifying a list while you're iterating over information technology. The example above only modifies elements in-place, and doesn't alter their order effectually, but you can cause all kinds of errors and unintended behaviour if you insert or delete list elements in the heart of iteration:

                                numbers                =                [                1                ,                2                ,                two                ,                3                ]                for                i                ,                num                in                enumerate                (                numbers                ):                if                num                ==                2                :                del                numbers                [                i                ]                print                (                numbers                )                # oops -- we missed i, because nosotros shifted the elements effectually while we were iterating!              

Sometimes you tin avert this past iterating over a copy of the listing instead, but it won't help yous in this example – every bit you lot delete elements from the original list, it will shrink, then the indices from the unmodified list copy volition soon exceed the length of the modified list and y'all will get an error. In full general, if you desire to select a subset of elements from a list on the basis of some benchmark, you should use a list comprehension instead. We will look at them at the end of this affiliate.

Exercise 2¶

  1. Write a plan which sums the integers from 1 to x using a for loop (and prints the total at the end).
  2. Can you recall of a way to exercise this without using a loop?
  3. Write a program which finds the factorial of a given number. E.g. 3 factorial, or 3! is equal to 3 ten 2 x 1; 5! is equal to five x 4 10 3 x 2 10 1, etc.. Your program should only contain a single loop.
  4. Write a program which prompts the user for 10 floating-indicate numbers and calculates their sum, product and average. Your programme should only comprise a single loop.
  5. Rewrite the previous program and then that it has ii loops – one which collects and stores the numbers, and one which processes them.

Nested loops¶

Nosotros saw in the previous chapter that we can create multi-dimensional sequences – sequences in which each element is some other sequence. How exercise we iterate over all the values of a multi-dimensional sequence? We need to use loops inside other loops. When we practice this, nosotros say that we are nesting loops.

Consider the timetable example from the previous affiliate – let us say that the timetable contains seven days, and each day contains 24 time slots. Each time slot is a string, which is empty if at that place is nothing scheduled for that slot. How can we iterate over all the fourth dimension slots and print out all our scheduled events?

                                # offset let's ascertain weekday names                WEEKDAYS                =                (                'Monday'                ,                'Tuesday'                ,                'Wed'                ,                'Thursday'                ,                'Fri'                ,                'Saturday'                ,                'Sun'                )                # now we iterate over each day in the timetable                for                mean solar day                in                timetable                :                # and over each timeslot in each day                for                i                ,                event                in                enumerate                (                day                ):                if                result                :                # if the slot is not an empty cord                print                (                "                %due south                                  at                                %02d                :00 --                                %s                "                %                (                WEEKDAYS                [                day                ],                i                ,                event                ))              

Note that we accept ii for loops – the inner loop will be executed once for every step in the outer loop's iteration. Besides notation that nosotros are using the enumerate function when iterating over the days – considering nosotros need both the alphabetize of each time slot (and then that we can print the hour) and the contents of that slot.

You may take noticed that we look up the name of the weekday one time for every iteration of the inner loop – only the name only changes once for every iteration of the outer loop. Nosotros tin can make our loop a picayune more efficient past moving this lookup out of the inner loop, so that we just perform it seven times and non 168 times!

                                for                solar day                in                timetable                :                day_name                =                WEEKDAYS                [                day                ]                for                i                ,                result                in                enumerate                (                solar day                ):                if                event                :                print                (                "                %due south                                  at                                %02d                :00 --                                %due south                "                %                (                day_name                ,                i                ,                event                ))              

This doesn't make much difference when y'all are looking up a value in a short tuple, but information technology could make a big difference if it were an expensive, fourth dimension-consuming calculation and you were iterating over hundreds or thousands of values.

Exercise three¶

  1. Write a program which uses a nested for loop to populate a three-dimensional list representing a calendar: the superlative-level list should contain a sub-list for each month, and each month should comprise iv weeks. Each week should be an empty list.
  2. Modify your code to brand it easier to admission a calendar month in the calendar by a human-readable month name, and each week by a name which is numbered starting from ane. Add an consequence (in the grade of a cord description) to the second week in July.

Iterables, iterators and generators¶

In Python, any blazon which tin can be iterated over with a for loop is an iterable. Lists, tuples, strings and dicts are all commonly used iterable types. Iterating over a list or a tuple simply ways processing each value in plow.

Sometimes we use a sequence to store a series of values which don't follow any particular blueprint: each value is unpredictable, and can't exist calculated on the wing. In cases like this, we have no pick but to store each value in a list or tuple. If the list is very big, this can use up a lot of memory.

What if the values in our sequence do follow a pattern, and can be calculated on the fly? Nosotros can salve a lot of retentivity by calculating values only when we need them, instead of calculating them all upwardly-front: instead of storing a big list, we tin can store only the information nosotros need for the adding.

Python has a lot of congenital-in iterable types that generate values on demand – they are often referred to as generators. We have already seen some examples, like range and enumerate . You can mostly treat a generator just like any other sequence if yous just need to access its elements one at a time – for example, if yous use information technology in a for loop:

                                # These 2 loops volition do exactly the aforementioned thing:                for                i                in                (                1                ,                ii                ,                3                ,                4                ,                5                ):                print                (                i                )                for                i                in                range                (                i                ,                half-dozen                ):                impress                (                i                )              

You may notice a deviation if you attempt to print out the generator's contents – by default all you will get is Python'due south standard cord representation of the object, which shows you the object's blazon and its unique identifier. To impress out all the values of generator, nosotros need to convert it to a sequence type similar a list, which will force all of the values to be generated:

                                # this volition not be very helpful                print                (                range                (                100                ))                # this will testify you all the generated values                print                (                list                (                range                (                100                )))              

Yous can employ all these iterables almost interchangeably considering they all use the same interface for iterating over values: every iterable object has a method which tin be used to return an iterator over that object. The iterable and the iterator together grade a consistent interface which can be used to loop over a sequence of values – whether those values are all stored in retention or calculated as they are needed:

  • The iterable has a method for accessing an detail past its index. For example, a list just returns the item which is stored in a detail position. A range, on the other hand, calculates the integer in the range which corresponds to a detail index.

  • The iterator "keeps your place" in the sequence, and has a method which lets you access the next element. In that location can be multiple iterators associated with a single iterable at the aforementioned time – each one in a different place in the iteration. For example, yous can iterate over the same list in both levels of a nested loop – each loop uses its ain iterator, and they do not interfere with each other:

                                            animals                    =                    [                    'true cat'                    ,                    'dog'                    ,                    'fish'                    ]                    for                    first_animal                    in                    animals                    :                    for                    second_animal                    in                    animals                    :                    print                    (                    "Yesterday I bought a                                        %south                    . Today I bought a                                        %southward                    ."                    %                    (                    first_animal                    ,                    second_animal                    ))                  

We will await in more detail at how these methods are defined in a after chapter, when nosotros talk over writing custom objects. For at present, here are some more examples of congenital-in generators defined in Python'south itertools module:

                                # nosotros need to import the module in social club to use it                import                itertools                # different range, count doesn't take an upper bound, and is not restricted to integers                for                i                in                itertools                .                count                (                ane                ):                print                (                i                )                # 1, 2, 3....                for                i                in                itertools                .                count                (                one                ,                0.five                ):                print                (                i                )                # ane.0, 1.five, 2.0....                # bicycle repeats the values in another iterable over and over                for                animal                in                itertools                .                cycle                ([                'cat'                ,                'dog'                ]):                impress                (                animal                )                # 'cat', 'dog', 'true cat', 'dog'...                # repeat repeats a single particular                for                i                in                itertools                .                repeat                (                i                ):                # ...forever                print                (                i                )                # 1, 1, 1....                for                i                in                itertools                .                repeat                (                i                ,                3                ):                # or a set number of times                print                (                i                )                # one, 1, 1                # chain combines multiple iterables sequentially                for                i                in                itertools                .                concatenation                (                numbers                ,                animals                ):                print                (                i                )                # impress all the numbers and so all the animals              

Some of these generators tin can go along for e'er, then if you employ them in a for loop you volition need some other bank check to brand the loop stop!

There is too a congenital-in part called goose egg which allows united states to combine multiple iterables pairwise. It also outputs a generator:

                                for                i                in                aught                ((                1                ,                ii                ,                3                ),                (                4                ,                five                ,                vi                )):                print                (                i                )                for                i                in                zip                (                range                (                5                ),                range                (                5                ,                ten                ),                range                (                10                ,                15                )):                print                (                i                )              

The combined iterable will exist the same length as the shortest of the component iterables – if any of the component iterables are longer than that, their trailing elements will be discarded.

Exercise iv¶

  1. Create a tuple of calendar month names and a tuple of the number of days in each month (assume that February has 28 days). Using a unmarried for loop, construct a dictionary which has the calendar month names every bit keys and the corresponding day numbers every bit values.
  2. Now do the aforementioned affair without using a for loop.

Comprehensions¶

Suppose that we have a list of numbers, and we want to build a new listing by doubling all the values in the first list. Or that we want to extract all the even numbers from a list of numbers. Or that we want to find and capitalise all the animal names in a list of animate being names that start with a vowel. We tin practise each of these things by iterating over the original listing, performing some kind of check on each element in turn, and appending values to a new list as we go:

                                numbers                =                [                i                ,                5                ,                2                ,                12                ,                xiv                ,                7                ,                18                ]                doubles                =                []                for                number                in                numbers                :                doubles                .                suspend                (                2                *                number                )                even_numbers                =                []                for                number                in                numbers                :                if                number                %                two                ==                0                :                even_numbers                .                append                (                number                )                animals                =                [                'aardvark'                ,                'cat'                ,                'domestic dog'                ,                'opossum'                ]                vowel_animals                =                []                for                animal                in                animals                :                if                animal                [                0                ]                in                'aeiou'                :                vowel_animals                .                append                (                animal                .                championship                ())              

That's quite an unwieldy way to do something very simple. Fortunately, we can rewrite simple loops like this to use a cleaner and more readable syntax by using comprehensions.

A comprehension is a kind of filter which we can define on an iterable based on some condition. The result is some other iterable. Hither are some examples of list comprehensions:

                                doubles                =                [                ii                *                number                for                number                in                numbers                ]                even_numbers                =                [                number                for                number                in                numbers                if                number                %                2                ==                0                ]                vowel_animals                =                [                animal                .                title                ()                for                brute                in                animals                if                animal                [                0                ]                in                'aeiou'                ]              

The comprehension is the role written between square brackets on each line. Each of these comprehensions results in the creation of a new list object.

Y'all can think of the comprehension as a compact form of for loop, which has been rearranged slightly.

  • The first function ( ii * number or number or beast.title() ) defines what is going to be inserted into the new list at each step of the loop. This is usually some function of each particular in the original iterable as it is candy.
  • The center part ( for number in numbers or for animal in animals ) corresponds to the start line of a for loop, and defines what iterable is being iterated over and what variable name each item is given inside the loop.
  • The concluding part (nothing or if number % 2 == 0 or if beast[0] in 'aeiou' ) is a status which filters out some of the original items. Only items for which the condition is truthful will be candy (as described in the starting time part) and included in the new list. You don't have to include this part – in the first example, we want to double all the numbers in the original list.

List comprehensions tin can exist used to replace loops that are a lot more complicated than this – even nested loops. The more complex the loop, the more than complicated the corresponding list comprehension is likely to exist. A long and convoluted list comprehension can be very hard for someone reading your lawmaking to understand – sometimes it'due south meliorate just to write the loop out in full.

The terminal product of a comprehension doesn't have to be a list. You can create dictionaries or generators in a very similar way – a generator expression uses round brackets instead of square brackets, a set comprehension uses curly brackets, and a dict comprehension uses curly brackets and separates the key and the value using a colon:

                                numbers                =                [                i                ,                5                ,                two                ,                12                ,                14                ,                seven                ,                18                ]                # a generator comprehension                doubles_generator                =                (                2                *                number                for                number                in                numbers                )                # a set comprehension                doubles_set                =                {                2                *                number                for                number                in                numbers                }                # a dict comprehension which uses the number every bit the key and the doubled number equally the value                doubles_dict                =                {                number                :                two                *                number                for                number                in                numbers                }              

If your generator expression is a parameter being passed to a function, like sum , yous tin can leave the round brackets out:

                                sum_doubles                =                sum                (                ii                *                number                for                number                in                numbers                )              

Annotation

dict and set comprehensions were introduced in Python three. In Python ii yous have to create a list or generator instead and catechumen it to a set or a dict yourself.

Exercise 5¶

  1. Create a string which contains the first ten positive integers separated past commas and spaces. Remember that you can't bring together numbers – you have to catechumen them to strings first. Print the output string.
  2. Rewrite the agenda plan from exercise 3 using nested comprehensions instead of nested loops. Attempt to append a cord to ane of the week lists, to make sure that y'all haven't reused the aforementioned list instead of creating a split list for each week.
  3. Now do something like to create a calendar which is a listing with 52 empty sublists (1 for each week in the whole year). Hint: how would you modify the nested for loops?

The intermission and continue statements¶

intermission

Inside the loop trunk, you can use the break statement to exit the loop immediately. You might want to test for a special example which will result in immediate exit from the loop. For example:

                                    ten                  =                  1                  while                  10                  <=                  x                  :                  if                  x                  ==                  v                  :                  intermission                  impress                  (                  10                  )                  x                  +=                  1                

The code fragment higher up will only print out the numbers ane to four . In the instance where x is v , the break argument will be encountered, and the flow of command will get out the loop immediately.

continue

The keep statement is similar to the break argument, in that it causes the period of control to leave the current loop body at the point of encounter – just the loop itself is not exited. For example:

                                    for                  x                  in                  range                  (                  1                  ,                  10                  +                  1                  ):                  # this volition count from i to 10                  if                  ten                  ==                  5                  :                  continue                  print                  (                  10                  )                

This fragment volition print all the numbers from ane to 10 except 5 . In the example where ten is 5 , the continue statement volition exist encountered, and the menses of command will leave that loop torso – only so the loop will continue with the side by side element in the range.

Note that if nosotros replaced suspension with keep in the offset example, we would get an space loop – because the go on statement would be triggered earlier x could exist updated. 10 would stay equal to 5 , and keep triggering the go along statement, for ever!

Using interruption to simulate a do-while loop¶

Remember that a while loop checks the condition before executing the loop torso for the first time. Sometimes this is user-friendly, but sometimes it's not. What if you always need to execute the loop body at least in one case?

                                    historic period                  =                  input                  (                  "Please enter your age: "                  )                  while                  non                  valid_number                  (                  age                  ):                  # allow's presume that we've divers valid_number elsewhere                  age                  =                  input                  (                  "Please enter your age: "                  )                

We have to ask the user for input at least once, because the status depends on the user input – so we have to practise it once exterior the loop. This is inconvenient, because nosotros have to repeat the contents of the loop body – and unnecessary repetition is unremarkably a bad idea. What if we desire to change the bulletin to the user later on, and forget to change it in both places? What if the loop torso contains many lines of code?

Many other languages offer a structure called a do-while loop, or a repeat-until loop, which checks the condition subsequently executing the loop body. That means that the loop body will always be executed at least once. Python doesn't have a structure like this, only we can simulate it with the aid of the intermission argument:

                                    while                  True                  :                  age                  =                  input                  (                  "Please enter your age: "                  )                  if                  valid_number                  (                  age                  ):                  break                

Nosotros have moved the condition inside the loop body, and we tin bank check it at the end, after asking the user for input. We have replaced the condition in the while argument with True – which is, of course, always true. Now the while argument will never stop afterwards checking the status – information technology can merely stop if the break argument is triggered.

This flim-flam can help united states to make this particular loop use instance expect better, just it has its disadvantages. If nosotros accidentally leave out the intermission statement, or write the loop in such a way that information technology can never be triggered, we will have an space loop! This code can also be more hard to empathize, because the actual condition which makes the loop cease is hidden inside the torso of the loop. You lot should therefore use this construct sparingly. Sometimes it'south possible to rewrite the loop in such a mode that the condition can be checked before the loop trunk and repetition is avoided:

                                    historic period                  =                  None                  # we can initialise age to something which is not a valid number                  while                  non                  valid_number                  (                  historic period                  ):                  # at present we can use the condition before request the user anything                  historic period                  =                  input                  (                  "Delight enter your historic period: "                  )                

Exercise 6¶

  1. Write a programme which repeatedly prompts the user for an integer. If the integer is even, print the integer. If the integer is odd, don't print anything. Exit the program if the user enters the integer 99 .

  2. Some programs inquire the user to input a variable number of data entries, and finally to enter a specific character or string (called a sentinel) which signifies that there are no more entries. For instance, you lot could be asked to enter your PIN followed past a hash ( # ). The hash is the watch which indicates that you have finished entering your Pin.

    Write a programme which averages positive integers. Your plan should prompt the user to enter integers until the user enters a negative integer. The negative integer should exist discarded, and you should impress the average of all the previously entered integers.

  3. Implement a simple calculator with a menu. Display the following options to the user, prompt for a selection, and carry out the requested activeness (east.g. prompt for two numbers and add together them). Afterward each operation, return the user to the bill of fare. Leave the program when the user selects 0 . If the user enters a number which is not in the menu, ignore the input and redisplay the carte du jour. Y'all tin presume that the user will enter a valid integer:

                                                --                      Calculator                      Bill of fare                      --                      0.                      Quit                      1.                      Add                      two                      numbers                      ii.                      Decrease                      2                      numbers                      three.                      Multiply                      two                      numbers                      4.                      Split                      2                      numbers                    

Using loops to simplify code¶

We tin can use our knowledge of loops to simplify some kinds of redundant code. Consider this instance, in which we prompt a user for some personal details:

                                    name                  =                  input                  (                  "Please enter your name: "                  )                  surname                  =                  input                  (                  "Delight enter your surname: "                  )                  # let's store these as strings for now, and convert them to numbers afterwards                  age                  =                  input                  (                  "Please enter your age: "                  )                  height                  =                  input                  (                  "Please enter your summit: "                  )                  weight                  =                  input                  (                  "Please enter your weight: "                  )                

In that location's a lot of repetition in this snippet of code. Each line is exactly the same except for the name of the variable and the name of the property nosotros ask for (and these values match each other, and then there'due south really but one difference). When nosotros write code like this we're likely to do a lot of copying and pasting, and it'south like shooting fish in a barrel to make a mistake. If we ever want to change something, we'll need to change each line.

How can we improve on this? We can separate the parts of these lines that differ from the parts that don't, and use a loop to iterate over them. Instead of storing the user input in split variables, we are going to use a dictionary – we can easily use the holding names as keys, and information technology'south a sensible mode to group these values:

                                    person                  =                  {}                  for                  prop                  in                  [                  "name"                  ,                  "surname"                  ,                  "age"                  ,                  "height"                  ,                  "weight"                  ]:                  person                  [                  prop                  ]                  =                  input                  (                  "Please enter your                                    %due south                  : "                  %                  prop                  )                

At present in that location is no unnecessary duplication. We can easily change the string that we employ as a prompt, or add more than lawmaking to execute for each belongings – we will simply accept to edit the code in one identify, not in five places. To add together another property, all nosotros have to exercise is add another proper noun to the list.

Practice 7¶

  1. Change the case higher up to include blazon conversion of the properties: age should be an integer, height and weight should exist floats, and name and surname should be strings.

Answers to exercises¶

Respond to exercise 1¶

  1. Hither is an example program:

                                                total                      =                      0                      number                      =                      0                      while                      total                      <                      200                      :                      number                      +=                      1                      full                      +=                      number                      **                      ii                      print                      (                      "Total:                                            %d                      "                      %                      total                      )                      impress                      (                      "Last number:                                            %d                      "                      %                      number                      )                    
  2. Here is an example plan:

                                                GUESSES_ALLOWED                      =                      10                      SECRET_WORD                      =                      "caribou"                      guesses_left                      =                      GUESSES_ALLOWED                      guessed_word                      =                      None                      while                      guessed_word                      !=                      SECRET_WORD                      and                      guesses_left                      :                      guessed_word                      =                      input                      (                      "Gauge a discussion: "                      )                      if                      guessed_word                      ==                      SECRET_WORD                      :                      print                      (                      "You lot guessed! Congratulations!"                      )                      else                      :                      guesses_left                      -=                      1                      print                      (                      "Incorrect! Yous have                                            %d                                              guesses left."                      %                      guesses_left                      )                    

Answer to practice 2¶

  1. Here is an example program:

                                                total                      =                      0                      for                      i                      in                      range                      (                      1                      ,                      10                      +                      one                      ):                      total                      +=                      i                      impress                      (                      total                      )                    
  2. Recall that we can employ the sum function to sum a sequence:

                                                print                      (                      sum                      (                      range                      (                      one                      ,                      10                      +                      1                      )))                    
  3. Here is an example programme:

                                                num                      =                      int                      (                      input                      (                      "Please enter an integer: "                      ))                      num_fac                      =                      1                      for                      i                      in                      range                      (                      1                      ,                      num                      +                      1                      ):                      num_fac                      *=                      i                      print                      (                      "                      %d                      ! =                                            %d                      "                      %                      (                      num                      ,                      num_fac                      ))                    
  4. Here is an example program:

                                                total                      =                      0                      product                      =                      1                      for                      i                      in                      range                      (                      i                      ,                      10                      +                      one                      ):                      num                      =                      float                      (                      input                      (                      "Please enter number                                            %d                      : "                      %                      i                      ))                      total                      +=                      num                      production                      *=                      num                      average                      =                      full                      /                      10                      print                      (                      "Sum:                                            %grand                      \n                      Product:                                            %thou                      \due north                      Boilerplate:                                            %thou                      "                      %                      (                      total                      ,                      product                      ,                      average                      ))                    
  5. Here is an example program:

                                                numbers                      =                      []                      for                      i                      in                      range                      (                      ten                      ):                      numbers                      [                      i                      ]                      =                      bladder                      (                      input                      (                      "Please enter number                                            %d                      : "                      %                      (                      i                      +                      ane                      )))                      full                      =                      0                      production                      =                      one                      for                      num                      in                      numbers                      :                      full                      +=                      num                      product                      *=                      num                      boilerplate                      =                      full                      /                      10                      print                      (                      "Sum:                                            %g                      \n                      Production:                                            %chiliad                      \n                      Average:                                            %thou                      "                      %                      (                      total                      ,                      product                      ,                      average                      ))                    

Answer to practice three¶

  1. Here is an example programme:

                                                calendar                      =                      []                      for                      1000                      in                      range                      (                      12                      ):                      month                      =                      []                      for                      w                      in                      range                      (                      4                      ):                      calendar month                      .                      append                      ([])                      calendar                      .                      append                      (                      month                      )                    
  2. Here is an example program:

                                                (                      Jan                      ,                      Feb                      ,                      MARCH                      ,                      Apr                      ,                      MAY                      ,                      JUNE                      ,                      JULY                      ,                      AUGUST                      ,                      SEPTEMBER                      ,                      OCTOBER                      ,                      November                      ,                      DECEMBER                      )                      =                      range                      (                      12                      )                      (                      WEEK_1                      ,                      WEEK_2                      ,                      WEEK_3                      ,                      WEEK_4                      )                      =                      range                      (                      4                      )                      calendar                      [                      JULY                      ][                      WEEK_2                      ]                      .                      append                      (                      "Get on holiday!"                      )                    

Reply to exercise 4¶

  1. Here is an example program:

                                                months                      =                      (                      "Jan"                      ,                      "February"                      ,                      "March"                      ,                      "Apr"                      ,                      "May"                      ,                      "June"                      ,                      "July"                      ,                      "Baronial"                      ,                      "September"                      ,                      "October"                      ,                      "November"                      ,                      "December"                      )                      num_days                      =                      (                      31                      ,                      28                      ,                      31                      ,                      30                      ,                      31                      ,                      30                      ,                      31                      ,                      31                      ,                      30                      ,                      31                      ,                      30                      ,                      31                      )                      month_dict                      =                      {}                      for                      month                      ,                      days                      in                      naught                      (                      months                      ,                      days                      ):                      month_dict                      [                      month                      ]                      =                      days                    
  2. Here is an case plan:

                                                months                      =                      (                      "January"                      ,                      "February"                      ,                      "March"                      ,                      "Apr"                      ,                      "May"                      ,                      "June"                      ,                      "July"                      ,                      "August"                      ,                      "September"                      ,                      "October"                      ,                      "November"                      ,                      "December"                      )                      num_days                      =                      (                      31                      ,                      28                      ,                      31                      ,                      30                      ,                      31                      ,                      xxx                      ,                      31                      ,                      31                      ,                      30                      ,                      31                      ,                      30                      ,                      31                      )                      # the zipped output is a sequence of ii-element tuples,                      # so nosotros tin just use a dict conversion.                      month_dict                      =                      dict                      (                      zip                      (                      months                      ,                      days                      ))                    

Answer to exercise 5¶

  1. Here is an example program:

                                                number_string                      =                      ", "                      .                      bring together                      (                      str                      (                      n                      )                      for                      n                      in                      range                      (                      1                      ,                      11                      ))                      print                      (                      number_string                      )                    
  2. Here is an instance plan:

                                                agenda                      =                      [[[]                      for                      due west                      in                      range                      (                      iv                      )]                      for                      m                      in                      range                      (                      12                      )]                      (                      January                      ,                      FEBRUARY                      ,                      MARCH                      ,                      April                      ,                      MAY                      ,                      JUNE                      ,                      JULY                      ,                      AUGUST                      ,                      SEPTEMBER                      ,                      October                      ,                      November                      ,                      DECEMBER                      )                      =                      range                      (                      12                      )                      (                      WEEK_1                      ,                      WEEK_2                      ,                      WEEK_3                      ,                      WEEK_4                      )                      =                      range                      (                      iv                      )                      calendar                      [                      JULY                      ][                      WEEK_2                      ]                      .                      append                      (                      "Go on holiday!"                      )                    
  3.                                             calendar                      =                      [[]                      for                      westward                      in                      range                      (                      4                      )                      for                      m                      in                      range                      (                      12                      )]                    

Answer to exercise 6¶

  1. Hither is an instance program:

                                                while                      (                      Truthful                      ):                      num                      =                      int                      (                      input                      (                      "Enter an integer: "                      ))                      if                      num                      ==                      99                      :                      break                      if                      num                      %                      ii                      :                      continue                      print                      num                    
  2. Here is an example program:

                                                impress                      (                      "Please enter positive integers to be averaged. Enter a negative integer to end the list."                      )                      nums                      =                      []                      while                      Truthful                      :                      num                      =                      int                      (                      input                      (                      "Enter a number: "                      ))                      if                      num                      <                      0                      :                      intermission                      nums                      .                      suspend                      (                      num                      )                      average                      =                      float                      (                      sum                      (                      nums                      ))                      /                      len                      (                      nums                      )                      print                      (                      "average =                                            %m                      "                      %                      average                      )                    
  3. Hither is an instance plan:

                                                menu                      =                      """-- Calculator Menu --                      0. Quit                      1. Add ii numbers                      2. Subtract ii numbers                      3. Multiply two numbers                      four. Split ii numbers"""                      selection                      =                      None                      while                      selection                      !=                      0                      :                      print                      (                      carte du jour                      )                      selection                      =                      int                      (                      input                      (                      "Select an selection: "                      ))                      if                      selection                      not                      in                      range                      (                      5                      ):                      impress                      (                      "Invalid option:                                            %d                      "                      %                      pick                      )                      go along                      if                      selection                      ==                      0                      :                      go along                      a                      =                      bladder                      (                      input                      (                      "Please enter the first number: "                      ))                      b                      =                      float                      (                      input                      (                      "Please enter the second number: "                      ))                      if                      pick                      ==                      i                      :                      result                      =                      a                      +                      b                      elif                      selection                      ==                      2                      :                      effect                      =                      a                      -                      b                      elif                      choice                      ==                      3                      :                      result                      =                      a                      *                      b                      elif                      selection                      ==                      four                      :                      consequence                      =                      a                      /                      b                      impress                      (                      "The event is                                            %g                      ."                      %                      result                      )                    

Respond to exercise 7¶

  1. Here is an example programme:

                                                person                      =                      {}                      properties                      =                      [                      (                      "proper noun"                      ,                      str                      ),                      (                      "surname"                      ,                      str                      ),                      (                      "age"                      ,                      int                      ),                      (                      "summit"                      ,                      float                      ),                      (                      "weight"                      ,                      bladder                      ),                      ]                      for                      prop                      ,                      p_type                      in                      properties                      :                      person                      [                      prop                      ]                      =                      p_type                      (                      input                      (                      "Please enter your                                            %s                      : "                      %                      prop                      ))