Loop command statements¶

Introduction¶

In this chapter, y'all will acquire how to make the estimator 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. At that place are two loop statements in Python: for and while . Nosotros will hash out the difference between these statements later in the chapter, but start let u.s.a. expect at an instance of a loop in the real world.

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

  1. greet customer
  2. ask for required type of petrol and amount
  3. ask whether customer needs other services
  4. inquire for required amount of money
  5. give money to cashier
  6. expect for change and receipt
  7. give change and receipt to client
  8. say thank you and goodbye

A petrol attendant performs these steps for each client, merely he does not follow them when there is no customer to serve. He likewise only performs them when it is his shift. If we were to write a computer programme to simulate this behaviour, information technology would not be enough simply to provide the steps and ask the reckoner to echo 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 outcome-controlled loop, the reckoner stops the loop execution when a condition is no longer true. In Python, you tin can use the while statement for this – it executes the loop trunk while the condition is truthful. The while statement checks the condition earlier 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 e'er executed at least once. Python has no such construct, only nosotros will run across afterward how y'all can simulate one.

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

If y'all wanted to get from Cape Town to Camps Bay, what loop algorithm would you apply? If you lot started past putting your car on the road to Camps Bay, you could:

  • drive for exactly 15 minutes. Subsequently 15 minutes, stop the motorcar and get out.
  • drive for exactly 8km. Afterwards 8km, stop the car and get out.
  • drive every bit long as y'all are not in Camps Bay. When you lot arrive, stop the machine and go out.

The commencement two algorithms are based on counting – the get-go counts time, and the 2d counts distance. Neither of these algorithms guarantees that you will arrive in Camps Bay. In the first example, you lot might hitting heavy traffic or none at all, and either fall short of or overshoot your desired destination. In the 2d instance, you might find a detour and stop up nowhere nearly Camps Bay.

The third algorithm is upshot-controlled. Yous acquit on driving as long as you are not at the beach. The status you keep checking is am I at the beach still?.

Many real-life activities are event-controlled. For example, you drink equally long as you are thirsty. Y'all read the newspaper as long as you are interested. Some activities are based on multiple events – for instance, a worker works as long as there is work to exercise and the fourth dimension is non 5pm.

The while argument¶

Python's upshot-controlled loop statement is the while argument. You should utilise it when you don't know beforehand how many times you will accept to execute the body of the loop. The while-body keeps repeating every bit long every bit the status is truthful. Here'south a menstruation control diagram for the while argument:

None

The loop consists of iii important parts: the initialisation, the condition, and the update. In the initialisation step, you set up the variable which you're going to use in the condition. In the status step, you perform a exam on the variable to see whether you should terminate the loop or execute the body another time. And then, after each successfully completed execution of the loop trunk, y'all update your variable.

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

Here is a uncomplicated Python example which adds the first ten integers together:

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

The variable used in the loop condition is the number i , which you utilise to count the integers from 1 to 10 . Start you initialise this number to 1 . In the condition, y'all check whether i is less than or equal to ten , and if this is true you execute the loop body. And then, at the end of the loop body, you update i past incrementing information technology by 1 .

Information technology is very important that you increment i at the end. If you lot did not, i would always be equal to 1 , the condition would always be true, and your program would never finish – nosotros phone call this an infinite loop. Whenever you write a while loop, brand sure that the variable you use in your condition is updated inside the loop body!

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

                                10                =                0                while                x                <                iii                :                y                +=                one                # wrong variable updated                production                =                1                count                =                1                while                count                <=                10                :                production                *=                count                # forgot to update count                x                =                0                while                x                <                5                :                impress                (                x                )                x                +=                one                # update statement is indented one level too petty, so it's outside the loop body                x                =                0                while                x                !=                5                :                print                (                x                )                10                +=                2                # 10 will never equal 5, because we are counting in even numbers!              

You might be wondering why the Python interpreter cannot catch space loops. This is known as the halting problem. Information technology is impossible for a reckoner to detect all possible infinite loops in some other program. It is upwardly to the programmer to avoid infinite loops.

In many of the examples above, we are counting to a predetermined number, so it would really exist more than appropriate for us to use a for loop (which will be introduced in the next section) – that is the loop construction which is more commonly used for counting loops. Hither is a more realistic example:

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

Hither we add together upward numbers from a list until the total reaches 100. We don't know how many times we will have to execute the loop, because we don't know the values of the numbers. Note that we might accomplish the end of the list of numbers earlier the total reaches 100 – if we try to access an chemical element across the end of the list we will get an fault, so we should add a bank check to make sure that this doesn't happen.

Exercise 1¶

  1. Write a program which uses a while loop to sum the squares of integers (starting from one ) until the total exceeds 200. Impress the terminal total and the final number to be squared and added.
  2. Write a program which keeps prompting the user to guess a give-and-take. The user is immune up to ten guesses – write your code in such a way that the secret word and the number of allowed guesses are like shooting fish in a barrel to alter. Print letters to give the user feedback.

The for statement¶

Python's other loop statement is the for statement. Y'all should use it when you need to exercise something for some predefined number of steps. Earlier we wait at Python's for loop syntax, we volition briefly look at the way for loops work in other languages.

Hither is an example of a for loop in Java:

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

You can encounter that this kind of for loop has a lot in common with a while loop – in fact, yous could say that information technology'south just a special case of a while loop. The initialisation footstep, the condition and the update step are all divers in the section in parentheses on the first line.

for loops are ofttimes used to perform an operation on every element of some kind of sequence. If you wanted to iterate over a list using the archetype-style for loop, yous would accept to count from aught to the end of the list, and then admission each list element by its index.

In Python, for loops make this use example elementary and easy by allowing you to iterate over sequences directly. Here is an example of a for statement which counts from i to 8:

                                for                i                in                range                (                i                ,                9                ):                print                (                i                )              

As we saw in the previous affiliate, range is an immutable sequence type used for ranges of integers – in this case, the range is counting from i to eight . The for loop will pace through each of the numbers in plow, performing the impress action for each one. When the terminate of the range is reached, the for loop will exit.

You lot can utilise for to iterate over other kinds of sequences too. You tin iterate over a list of strings similar this:

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

At each iteration of the loop, the next element of the listing pets is assigned to the variable pet , which yous can then access inside the loop body. The case in a higher place is functionally identical to this:

                                for                i                in                range                (                len                (                pets                )):                # i will iterate over 0, ane and two                pet                =                pets                [                i                ]                print                (                pet                )              

That is similar to the way for loops are written in, for example, Java. You lot should avoid doing this, as it'southward more difficult to read, and unnecessarily circuitous. If for some reason you lot need the index inside the loop as well as the list element itself, y'all can use the enumerate function to number the elements:

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

Like range , enumerate besides returns an iterator – each item it generates is a tuple in which the showtime value is the index of the element (starting at nothing) and the second is the element itself. In the loop above, at each iteration the value of the index is assigned to the variable i , and the chemical 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 within the loop, without changing the original list.

This brings us to a common for loop pitfall: modifying a list while you lot're iterating over it. The example higher up only modifies elements in-place, and doesn't alter their order around, but you can cause all kinds of errors and unintended behaviour if y'all insert or delete listing elements in the middle of iteration:

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

Sometimes yous can avoid this by iterating over a re-create of the list instead, only information technology won't help you in this example – as you delete elements from the original list, information technology will shrink, so the indices from the unmodified list copy will before long exceed the length of the modified list and you lot will get an fault. In general, if you desire to select a subset of elements from a list on the ground of some benchmark, you should use a list comprehension instead. Nosotros will look at them at the end of this chapter.

Exercise ii¶

  1. Write a programme which sums the integers from ane to 10 using a for loop (and prints the total at the end).
  2. Can you think of a style to do 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 iii ten two x 1; 5! is equal to 5 10 4 x iii x 2 x 1, etc.. Your program should just contain a single loop.
  4. Write a program which prompts the user for 10 floating-signal numbers and calculates their sum, product and average. Your program should but contain a single loop.
  5. Rewrite the previous plan and so that information technology has 2 loops – one which collects and stores the numbers, and one which processes them.

Nested loops¶

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

Consider the timetable example from the previous affiliate – allow 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 there is nada scheduled for that slot. How can we iterate over all the time slots and print out all our scheduled events?

                                # commencement let'southward define weekday names                WEEKDAYS                =                (                'Mon'                ,                'Tuesday'                ,                'Wednesday'                ,                'Thursday'                ,                'Friday'                ,                'Saturday'                ,                'Dominicus'                )                # now we iterate over each twenty-four hours in the timetable                for                day                in                timetable                :                # and over each timeslot in each day                for                i                ,                result                in                enumerate                (                solar day                ):                if                event                :                # if the slot is not an empty cord                print                (                "                %s                                  at                                %02d                :00 --                                %s                "                %                (                WEEKDAYS                [                day                ],                i                ,                event                ))              

Note that we have two for loops – the inner loop will be executed one time for every footstep in the outer loop'southward iteration. Also note that nosotros are using the enumerate office when iterating over the days – considering we need both the index of each time slot (and so that we tin impress the hour) and the contents of that slot.

You may take noticed that nosotros look up the proper noun of the weekday one time for every iteration of the inner loop – but the proper noun only changes in one case for every iteration of the outer loop. We tin can make our loop a little more efficient past moving this lookup out of the inner loop, so that we only perform it vii times and non 168 times!

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

This doesn't make much difference when you are looking up a value in a brusk tuple, but it could make a big difference if it were an expensive, time-consuming adding and you were iterating over hundreds or thousands of values.

Practice 3¶

  1. Write a plan which uses a nested for loop to populate a three-dimensional listing representing a calendar: the peak-level listing should contain a sub-list for each month, and each month should incorporate 4 weeks. Each week should be an empty list.
  2. Alter your code to make it easier to admission a calendar month in the agenda by a human-readable month name, and each week by a name which is numbered starting from one. Add an upshot (in the grade of a cord description) to the second calendar week in July.

Iterables, iterators and generators¶

In Python, any type which 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 listing or a tuple just means processing each value in turn.

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

What if the values in our sequence do follow a pattern, and tin can be calculated on the fly? Nosotros tin salve a lot of memory past computing values but when nosotros demand them, instead of computing them all up-front: instead of storing a big listing, we can shop but the information we demand for the calculation.

Python has a lot of built-in iterable types that generate values on need – they are often referred to as generators. We take already seen some examples, like range and enumerate . Yous tin can more often than not treat a generator just like whatever other sequence if y'all simply need to access its elements one at a time – for example, if you utilize information technology in a for loop:

                                # These two loops will do exactly the same affair:                for                i                in                (                ane                ,                2                ,                3                ,                4                ,                5                ):                print                (                i                )                for                i                in                range                (                1                ,                6                ):                print                (                i                )              

Yous may discover a deviation if yous attempt to impress out the generator'due south contents – by default all you will get is Python's standard string representation of the object, which shows you lot the object's type and its unique identifier. To impress out all the values of generator, we need to convert information technology to a sequence type like a listing, which will force all of the values to be generated:

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

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

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

  • The iterator "keeps your place" in the sequence, and has a method which lets you admission the next chemical element. In that location tin be multiple iterators associated with a single iterable at the same time – each one in a dissimilar place in the iteration. For case, y'all can iterate over the same list in both levels of a nested loop – each loop uses its own iterator, and they exercise not interfere with each other:

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

We will look in more detail at how these methods are defined in a later chapter, when nosotros discuss writing custom objects. For at present, here are some more examples of congenital-in generators defined in Python's itertools module:

                                # we demand to import the module in order to use it                import                itertools                # unlike range, count doesn't have an upper bound, and is not restricted to integers                for                i                in                itertools                .                count                (                1                ):                print                (                i                )                # 1, two, iii....                for                i                in                itertools                .                count                (                1                ,                0.five                ):                impress                (                i                )                # i.0, 1.v, 2.0....                # cycle repeats the values in another iterable over and over                for                animal                in                itertools                .                bicycle                ([                'true cat'                ,                'dog'                ]):                print                (                fauna                )                # 'cat', 'dog', 'cat', 'dog'...                # repeat repeats a single item                for                i                in                itertools                .                repeat                (                1                ):                # ...forever                print                (                i                )                # ane, i, i....                for                i                in                itertools                .                echo                (                ane                ,                3                ):                # or a set number of times                print                (                i                )                # ane, 1, 1                # concatenation combines multiple iterables sequentially                for                i                in                itertools                .                chain                (                numbers                ,                animals                ):                print                (                i                )                # print all the numbers and and so all the animals              

Some of these generators tin can go along for ever, then if yous utilize them in a for loop you will need some other check to make the loop terminate!

There is likewise a built-in function called zip which allows us to combine multiple iterables pairwise. It as well outputs a generator:

                                for                i                in                goose egg                ((                one                ,                2                ,                iii                ),                (                4                ,                5                ,                six                )):                print                (                i                )                for                i                in                zip                (                range                (                5                ),                range                (                5                ,                10                ),                range                (                10                ,                15                )):                print                (                i                )              

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

Practise 4¶

  1. Create a tuple of calendar month names and a tuple of the number of days in each month (presume that February has 28 days). Using a unmarried for loop, construct a dictionary which has the month names as keys and the corresponding mean solar day numbers as values.
  2. Now practise the same thing without using a for loop.

Comprehensions¶

Suppose that we have a list of numbers, and nosotros want to build a new list by doubling all the values in the first listing. Or that we want to excerpt all the even numbers from a listing of numbers. Or that we want to detect and capitalise all the animate being names in a list of animal names that start with a vowel. Nosotros can do each of these things by iterating over the original list, performing some kind of cheque on each element in turn, and appending values to a new list as we go:

                                numbers                =                [                1                ,                5                ,                2                ,                12                ,                14                ,                7                ,                18                ]                doubles                =                []                for                number                in                numbers                :                doubles                .                append                (                2                *                number                )                even_numbers                =                []                for                number                in                numbers                :                if                number                %                2                ==                0                :                even_numbers                .                suspend                (                number                )                animals                =                [                'aardvark'                ,                'true cat'                ,                'dog'                ,                'opossum'                ]                vowel_animals                =                []                for                beast                in                animals                :                if                animal                [                0                ]                in                'aeiou'                :                vowel_animals                .                suspend                (                animal                .                title                ())              

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

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

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

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

You tin think of the comprehension every bit a compact form of for loop, which has been rearranged slightly.

  • The starting time role ( 2 * number or number or animal.championship() ) defines what is going to be inserted into the new listing at each step of the loop. This is unremarkably some function of each item in the original iterable as it is processed.
  • The center part ( for number in numbers or for animal in animals ) corresponds to the kickoff line of a for loop, and defines what iterable is being iterated over and what variable name each detail is given inside the loop.
  • The last function (nothing or if number % 2 == 0 or if brute[0] in 'aeiou' ) is a condition which filters out some of the original items. Only items for which the condition is true volition exist processed (equally described in the offset part) and included in the new list. Y'all don't take to include this part – in the beginning case, nosotros want to double all the numbers in the original list.

List comprehensions tin be used to replace loops that are a lot more than complicated than this – even nested loops. The more complex the loop, the more complicated the corresponding list comprehension is likely to be. A long and convoluted list comprehension can be very difficult for someone reading your code to understand – sometimes information technology's better just to write the loop out in total.

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

                                numbers                =                [                1                ,                five                ,                2                ,                12                ,                14                ,                7                ,                18                ]                # a generator comprehension                doubles_generator                =                (                2                *                number                for                number                in                numbers                )                # a prepare comprehension                doubles_set                =                {                2                *                number                for                number                in                numbers                }                # a dict comprehension which uses the number as the cardinal and the doubled number as the value                doubles_dict                =                {                number                :                2                *                number                for                number                in                numbers                }              

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

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

Note

dict and gear up comprehensions were introduced in Python 3. In Python 2 you have to create a list or generator instead and convert it to a ready or a dict yourself.

Practise 5¶

  1. Create a string which contains the first x positive integers separated past commas and spaces. Retrieve that you tin can't bring together numbers – you have to catechumen them to strings first. Impress the output string.
  2. Rewrite the agenda program from exercise iii using nested comprehensions instead of nested loops. Endeavor to suspend a cord to 1 of the week lists, to make sure that you haven't reused the aforementioned list instead of creating a separate listing for each week.
  3. Now do something like to create a calendar which is a list with 52 empty sublists (one for each week in the whole year). Hint: how would yous modify the nested for loops?

The intermission and continue statements¶

break

Within the loop body, y'all can use the break argument to go out the loop immediately. You might desire to test for a special case which will result in immediate leave from the loop. For example:

                                    x                  =                  1                  while                  x                  <=                  10                  :                  if                  10                  ==                  5                  :                  pause                  print                  (                  x                  )                  x                  +=                  1                

The code fragment above volition only impress out the numbers 1 to iv . In the case where x is v , the pause statement will be encountered, and the flow of command will leave the loop immediately.

go along

The continue argument is similar to the break argument, in that it causes the flow of control to leave the current loop trunk at the point of encounter – only the loop itself is not exited. For example:

                                    for                  x                  in                  range                  (                  i                  ,                  10                  +                  ane                  ):                  # this will count from 1 to 10                  if                  10                  ==                  5                  :                  go along                  print                  (                  ten                  )                

This fragment will print all the numbers from 1 to 10 except 5 . In the case where x is v , the go along statement will be encountered, and the period of control will exit that loop trunk – but then the loop will continue with the next element in the range.

Note that if we replaced suspension with continue in the start example, we would become an infinite loop – because the continue argument would be triggered before 10 could be updated. ten would stay equal to 5 , and keep triggering the continue statement, for ever!

Using break to simulate a do-while loop¶

Recall that a while loop checks the condition before executing the loop body for the commencement time. Sometimes this is convenient, but sometimes it'southward non. What if you always need to execute the loop trunk at least one time?

                                    historic period                  =                  input                  (                  "Please enter your age: "                  )                  while                  not                  valid_number                  (                  age                  ):                  # let's presume that we've defined valid_number elsewhere                  age                  =                  input                  (                  "Please enter your age: "                  )                

We accept to ask the user for input at least once, considering the condition depends on the user input – so we take to do information technology once outside the loop. This is inconvenient, considering we have to repeat the contents of the loop body – and unnecessary repetition is normally a bad thought. What if nosotros desire to change the message to the user subsequently, and forget to modify information technology in both places? What if the loop body contains many lines of code?

Many other languages offer a structure called a practise-while loop, or a repeat-until loop, which checks the condition after executing the loop body. That ways that the loop torso volition always be executed at least once. Python doesn't have a structure like this, only nosotros can simulate it with the help of the suspension statement:

                                    while                  Truthful                  :                  age                  =                  input                  (                  "Please enter your age: "                  )                  if                  valid_number                  (                  age                  ):                  intermission                

We have moved the condition inside the loop torso, and we can check it at the finish, after asking the user for input. We have replaced the condition in the while statement with True – which is, of class, always true. At present the while statement will never cease after checking the condition – it tin only end if the intermission statement is triggered.

This trick can help us to brand this particular loop employ case wait amend, but it has its disadvantages. If we accidentally go out out the interruption statement, or write the loop in such a style that it tin can never be triggered, nosotros will accept an infinite loop! This code can also be more than hard to empathise, because the bodily status which makes the loop end is hidden inside the body of the loop. You should therefore apply this construct sparingly. Sometimes it's possible to rewrite the loop in such a way that the condition can be checked before the loop body and repetition is avoided:

                                    age                  =                  None                  # we can initialise age to something which is not a valid number                  while                  not                  valid_number                  (                  age                  ):                  # now nosotros tin apply the condition earlier asking the user annihilation                  age                  =                  input                  (                  "Delight enter your age: "                  )                

Do half dozen¶

  1. Write a program which repeatedly prompts the user for an integer. If the integer is even, impress the integer. If the integer is odd, don't impress anything. Exit the plan 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 grapheme or cord (chosen a sentinel) which signifies that there are no more entries. For example, you could be asked to enter your Pivot followed by a hash ( # ). The hash is the lookout man which indicates that you have finished entering your Pivot.

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

  3. Implement a simple reckoner with a menu. Display the post-obit options to the user, prompt for a choice, and carry out the requested action (e.g. prompt for two numbers and add them). Later each operation, return the user to the card. Exit the plan when the user selects 0 . If the user enters a number which is not in the menu, ignore the input and redisplay the card. You tin can assume that the user will enter a valid integer:

                                                --                      Calculator                      Menu                      --                      0.                      Quit                      i.                      Add                      two                      numbers                      two.                      Subtract                      2                      numbers                      3.                      Multiply                      two                      numbers                      4.                      Split up                      two                      numbers                    

Using loops to simplify lawmaking¶

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

                                    proper noun                  =                  input                  (                  "Delight enter your name: "                  )                  surname                  =                  input                  (                  "Please enter your surname: "                  )                  # let'due south store these equally strings for now, and convert them to numbers after                  age                  =                  input                  (                  "Please enter your age: "                  )                  acme                  =                  input                  (                  "Please enter your pinnacle: "                  )                  weight                  =                  input                  (                  "Please enter your weight: "                  )                

In that location'due south a lot of repetition in this snippet of lawmaking. Each line is exactly the same except for the name of the variable and the proper noun of the property nosotros ask for (and these values match each other, so there's really merely 1 difference). When nosotros write code like this we're likely to do a lot of copying and pasting, and information technology's like shooting fish in a barrel to make a fault. If we ever desire to change something, we'll need to modify each line.

How tin we improve on this? We tin 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 separate variables, we are going to use a dictionary – nosotros tin easily utilize the holding names as keys, and information technology's a sensible way to group these values:

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

Now there is no unnecessary duplication. We can easily modify the string that we use equally a prompt, or add together more code to execute for each property – we will only have to edit the lawmaking in one place, not in v places. To add together another holding, all we have to exercise is add another name to the list.

Exercise 7¶

  1. Modify the example in a higher place to include type conversion of the properties: age should be an integer, meridian and weight should be floats, and name and surname should exist strings.

Answers to exercises¶

Respond to exercise 1¶

  1. Here is an example programme:

                                                full                      =                      0                      number                      =                      0                      while                      total                      <                      200                      :                      number                      +=                      1                      total                      +=                      number                      **                      two                      print                      (                      "Full:                                            %d                      "                      %                      full                      )                      print                      (                      "Last number:                                            %d                      "                      %                      number                      )                    
  2. Here is an instance 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 word: "                      )                      if                      guessed_word                      ==                      SECRET_WORD                      :                      impress                      (                      "You lot guessed! Congratulations!"                      )                      else                      :                      guesses_left                      -=                      1                      print                      (                      "Incorrect! You have                                            %d                                              guesses left."                      %                      guesses_left                      )                    

Reply to practise ii¶

  1. Here is an case program:

                                                full                      =                      0                      for                      i                      in                      range                      (                      1                      ,                      10                      +                      ane                      ):                      total                      +=                      i                      impress                      (                      total                      )                    
  2. Recollect that we tin use the sum function to sum a sequence:

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

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

                                                full                      =                      0                      production                      =                      1                      for                      i                      in                      range                      (                      1                      ,                      10                      +                      1                      ):                      num                      =                      float                      (                      input                      (                      "Delight enter number                                            %d                      : "                      %                      i                      ))                      total                      +=                      num                      product                      *=                      num                      average                      =                      full                      /                      10                      print                      (                      "Sum:                                            %k                      \n                      Product:                                            %g                      \n                      Boilerplate:                                            %thou                      "                      %                      (                      total                      ,                      product                      ,                      boilerplate                      ))                    
  5. Hither is an example programme:

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

Answer to exercise 3¶

  1. Here is an example program:

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

                                                (                      Jan                      ,                      February                      ,                      MARCH                      ,                      April                      ,                      MAY                      ,                      JUNE                      ,                      JULY                      ,                      Baronial                      ,                      SEPTEMBER                      ,                      October                      ,                      Nov                      ,                      Dec                      )                      =                      range                      (                      12                      )                      (                      WEEK_1                      ,                      WEEK_2                      ,                      WEEK_3                      ,                      WEEK_4                      )                      =                      range                      (                      four                      )                      calendar                      [                      JULY                      ][                      WEEK_2                      ]                      .                      append                      (                      "Go on holiday!"                      )                    

Reply to exercise four¶

  1. Hither is an example program:

                                                months                      =                      (                      "January"                      ,                      "Feb"                      ,                      "March"                      ,                      "Apr"                      ,                      "May"                      ,                      "June"                      ,                      "July"                      ,                      "August"                      ,                      "September"                      ,                      "October"                      ,                      "November"                      ,                      "Dec"                      )                      num_days                      =                      (                      31                      ,                      28                      ,                      31                      ,                      30                      ,                      31                      ,                      thirty                      ,                      31                      ,                      31                      ,                      30                      ,                      31                      ,                      30                      ,                      31                      )                      month_dict                      =                      {}                      for                      month                      ,                      days                      in                      naught                      (                      months                      ,                      days                      ):                      month_dict                      [                      calendar month                      ]                      =                      days                    
  2. Here is an instance program:

                                                months                      =                      (                      "January"                      ,                      "Feb"                      ,                      "March"                      ,                      "Apr"                      ,                      "May"                      ,                      "June"                      ,                      "July"                      ,                      "August"                      ,                      "September"                      ,                      "October"                      ,                      "November"                      ,                      "Dec"                      )                      num_days                      =                      (                      31                      ,                      28                      ,                      31                      ,                      xxx                      ,                      31                      ,                      xxx                      ,                      31                      ,                      31                      ,                      thirty                      ,                      31                      ,                      30                      ,                      31                      )                      # the zipped output is a sequence of two-element tuples,                      # and so we tin can but use a dict conversion.                      month_dict                      =                      dict                      (                      zip                      (                      months                      ,                      days                      ))                    

Answer to exercise five¶

  1. Here is an case program:

                                                number_string                      =                      ", "                      .                      join                      (                      str                      (                      n                      )                      for                      n                      in                      range                      (                      1                      ,                      11                      ))                      print                      (                      number_string                      )                    
  2. Here is an example program:

                                                calendar                      =                      [[[]                      for                      w                      in                      range                      (                      4                      )]                      for                      m                      in                      range                      (                      12                      )]                      (                      Jan                      ,                      FEBRUARY                      ,                      MARCH                      ,                      April                      ,                      MAY                      ,                      JUNE                      ,                      JULY                      ,                      AUGUST                      ,                      SEPTEMBER                      ,                      Oct                      ,                      NOVEMBER                      ,                      DECEMBER                      )                      =                      range                      (                      12                      )                      (                      WEEK_1                      ,                      WEEK_2                      ,                      WEEK_3                      ,                      WEEK_4                      )                      =                      range                      (                      four                      )                      calendar                      [                      JULY                      ][                      WEEK_2                      ]                      .                      append                      (                      "Go on holiday!"                      )                    
  3.                                             calendar                      =                      [[]                      for                      due west                      in                      range                      (                      4                      )                      for                      chiliad                      in                      range                      (                      12                      )]                    

Answer to practise 6¶

  1. Hither is an example program:

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

                                                impress                      (                      "Please enter positive integers to be averaged. Enter a negative integer to terminate the listing."                      )                      nums                      =                      []                      while                      True                      :                      num                      =                      int                      (                      input                      (                      "Enter a number: "                      ))                      if                      num                      <                      0                      :                      break                      nums                      .                      append                      (                      num                      )                      average                      =                      float                      (                      sum                      (                      nums                      ))                      /                      len                      (                      nums                      )                      print                      (                      "average =                                            %g                      "                      %                      boilerplate                      )                    
  3. Here is an example program:

                                                menu                      =                      """-- Figurer Menu --                      0. Quit                      1. Add together two numbers                      2. Subtract ii numbers                      3. Multiply two numbers                      iv. Divide 2 numbers"""                      pick                      =                      None                      while                      selection                      !=                      0                      :                      impress                      (                      menu                      )                      selection                      =                      int                      (                      input                      (                      "Select an option: "                      ))                      if                      pick                      not                      in                      range                      (                      v                      ):                      print                      (                      "Invalid choice:                                            %d                      "                      %                      option                      )                      continue                      if                      choice                      ==                      0                      :                      go along                      a                      =                      bladder                      (                      input                      (                      "Please enter the get-go number: "                      ))                      b                      =                      bladder                      (                      input                      (                      "Please enter the 2d number: "                      ))                      if                      pick                      ==                      1                      :                      consequence                      =                      a                      +                      b                      elif                      selection                      ==                      2                      :                      result                      =                      a                      -                      b                      elif                      pick                      ==                      3                      :                      result                      =                      a                      *                      b                      elif                      pick                      ==                      4                      :                      issue                      =                      a                      /                      b                      print                      (                      "The consequence is                                            %one thousand                      ."                      %                      result                      )                    

Answer to exercise 7¶

  1. Here is an example program:

                                                person                      =                      {}                      properties                      =                      [                      (                      "name"                      ,                      str                      ),                      (                      "surname"                      ,                      str                      ),                      (                      "historic period"                      ,                      int                      ),                      (                      "height"                      ,                      float                      ),                      (                      "weight"                      ,                      bladder                      ),                      ]                      for                      prop                      ,                      p_type                      in                      properties                      :                      person                      [                      prop                      ]                      =                      p_type                      (                      input                      (                      "Please enter your                                            %s                      : "                      %                      prop                      ))