iv. Conditionals and loops¶

iv.1. Conditional execution¶

4.1.1. The if statement¶

In order to write useful programs, we almost ever need the ability to check conditions and change the behavior of the program accordingly. Provisional statements give u.s. this ability. The simplest form is the if statement, which has the genaral form:

                                if                BOOLEAN                EXPRESSION                :                STATEMENTS              

A few important things to notation nigh if statements:

  1. The colon ( : ) is meaning and required. It separates the header of the compound argument from the body.

  2. The line subsequently the colon must be indented. Information technology is standard in Python to use iv spaces for indenting.

  3. All lines indented the aforementioned amount after the colon volition be executed whenever the BOOLEAN_EXPRESSION is truthful.

Here is an example:

                                nutrient                =                'spam'                if                food                ==                'spam'                :                print                (                'Ummmm, my favorite!'                )                print                (                'I experience similar saying it 100 times...'                )                impress                (                100                *                (                food                +                '! '                ))              

The boolean expression afterwards the if argument is chosen the condition. If it is truthful, and then all the indented statements become executed. What happens if the status is false, and food is not equal to 'spam' ? In a simple if statement similar this, nothing happens, and the program continues on to the next argument.

Run this example code and see what happens. Then change the value of food to something other than 'spam' and run it over again, confirming that you lot don't get whatever output.

Flowchart of an if statement

_images/flowchart_if_only.png

Equally with the for statement from the terminal chapter, the if statement is a compound statement. Compound statements consist of a header line and a body. The header line of the if argument begins with the keyword if followed by a boolean expression and ends with a colon ( : ).

The indented statements that follow are called a cake. The outset unindented statement marks the end of the block. Each argument inside the block must have the same indentation.

Indentation and the PEP 8 Python Style Guide

The Python community has developed a Mode Guide for Python Lawmaking, usually referred to simply every bit "PEP 8". The Python Enhancement Proposals, or PEPs, are part of the process the Python community uses to discuss and prefer changes to the linguistic communication.

PEP eight recommends the utilise of 4 spaces per indentation level. We will follow this (and the other PEP 8 recommendations) in this book.

To help us learn to write well styled Python code, there is a program chosen pep8 that works as an automated mode guide checker for Python source lawmaking. pep8 is installable as a package on Debian based GNU/Linux systems similar Ubuntu.

In the Vim department of the appendix, Configuring Ubuntu for Python Web Development, there is pedagogy on configuring vim to run pep8 on your source code with the push of a push.

4.1.2. The if else statement¶

Information technology is frequently the instance that you want one thing to happen when a condition it true, and something else to happen when it is false. For that we have the if else statement.

                                if                food                ==                'spam'                :                print                (                'Ummmm, my favorite!'                )                else                :                print                (                "No, I won't accept it. I want spam!"                )              

Here, the first print statement will execute if food is equal to 'spam' , and the print statement indented under the else clause will get executed when information technology is non.

Flowchart of a if else statement

_images/flowchart_if_else.png

The syntax for an if else statement looks like this:

                                if                BOOLEAN                EXPRESSION                :                STATEMENTS_1                # executed if condition evaluates to True                else                :                STATEMENTS_2                # executed if condition evaluates to Faux              

Each statement within the if block of an if else statement is executed in order if the boolean expression evaluates to Truthful . The entire cake of statements is skipped if the boolean expression evaluates to False , and instead all the statements under the else clause are executed.

At that place is no limit on the number of statements that can appear under the ii clauses of an if else statement, but in that location has to exist at least one argument in each cake. Occasionally, it is useful to have a section with no statements (commonly as a place keeper, or scaffolding, for code y'all haven't written even so). In that instance, you lot can use the pass statement, which does nothing except act as a placeholder.

                                if                True                :                # This is always true                pass                # so this is always executed, but information technology does null                else                :                pass              

Python terminology

Python documentation sometimes uses the term suite of statements to mean what we have chosen a block hither. They mean the same thing, and since well-nigh other languages and figurer scientists employ the word cake, we'll stick with that.

Notice besides that else is not a statement. The if statement has 2 clauses, one of which is the (optional) else clause. The Python documentation calls both forms, together with the next form we are about to meet, the if statement.

4.two. Chained conditionals¶

Sometimes there are more than two possibilities and nosotros need more than two branches. One way to express a computation like that is a chained provisional:

                            if              x              <              y              :              STATEMENTS_A              elif              10              >              y              :              STATEMENTS_B              else              :              STATEMENTS_C            

Flowchart of this chained conditional

_images/flowchart_chained_conditional.png

elif is an abridgement of else if . Again, exactly i branch will be executed. At that place is no limit of the number of elif statements only just a single (and optional) last else statement is allowed and it must be the last branch in the statement:

                            if              option              ==              'a'              :              print              (              "You chose 'a'."              )              elif              selection              ==              'b'              :              print              (              "You chose 'b'."              )              elif              choice              ==              'c'              :              print              (              "You lot chose 'c'."              )              else              :              print              (              "Invalid selection."              )            

Each condition is checked in order. If the first is false, the adjacent is checked, and so on. If one of them is true, the corresponding co-operative executes, and the statement ends. Even if more than 1 condition is true, only the first truthful branch executes.

iv.3. Nested conditionals¶

Ane conditional tin can likewise be nested within another. (It is the same theme of composibility, again!) We could have written the previous example as follows:

Flowchart of this nested provisional

_images/flowchart_nested_conditional.png

                            if              x              <              y              :              STATEMENTS_A              else              :              if              10              >              y              :              STATEMENTS_B              else              :              STATEMENTS_C            

The outer provisional contains two branches. The second branch contains another if statement, which has two branches of its own. Those two branches could contain provisional statements also.

Although the indentation of the statements makes the structure apparent, nested conditionals very rapidly get hard to read. In general, it is a good thought to avoid them when y'all can.

Logical operators oftentimes provide a mode to simplify nested provisional statements. For example, nosotros tin can rewrite the following code using a single conditional:

                            if              0              <              ten              :              # presume 10 is an int here              if              x              <              x              :              print              (              "x is a positive single digit."              )            

The print function is called only if nosotros make it past both the conditionals, and then we can apply the and operator:

                            if              0              <              x              and              x              <              ten              :              print              (              "x is a positive single digit."              )            

Note

Python really allows a short hand form for this, then the post-obit will too piece of work:

                                if                0                <                ten                <                10                :                print                (                "x is a positive single digit."                )              

4.4. Iteration¶

Computers are oftentimes used to automate repetitive tasks. Repeating identical or like tasks without making errors is something that computers do well and people do poorly.

Repeated execution of a ready of statements is called iteration. Python has two statements for iteration – the for statement, which we met last chapter, and the while statement.

Before nosotros expect at those, we need to review a few ideas.

4.four.1. Reassignmnent¶

As we saw dorsum in the Variables are variable section, it is legal to brand more than than one consignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the sometime value).

                                bruce                =                5                print                (                bruce                )                bruce                =                7                print                (                bruce                )              

The output of this program is

because the beginning time bruce is printed, its value is 5, and the 2d time, its value is seven.

Hither is what reassignment looks like in a country snapshot:

reassignment

With reassignment it is specially of import to distinguish between an assignment statement and a boolean expression that tests for equality. Because Python uses the equal token ( = ) for assignment, it is tempting to interpret a statement like a = b as a boolean test. Unlike mathematics, it is not! Remember that the Python token for the equality operator is == .

Note too that an equality test is symmetric, but assignment is non. For example, if a == 7 then 7 == a . But in Python, the argument a = 7 is legal and 7 = a is non.

Furthermore, in mathematics, a statement of equality is e'er truthful. If a == b now, then a will always equal b . In Python, an assignment statement can brand two variables equal, only because of the possibility of reassignment, they don't have to stay that manner:

                                a                =                5                b                =                a                # later on executing this line, a and b are now equal                a                =                3                # subsequently executing this line, a and b are no longer equal              

The third line changes the value of a but does not modify the value of b , so they are no longer equal.

Notation

In some programming languages, a different symbol is used for assignment, such as <- or := , to avoid confusion. Python chose to use the tokens = for assignment, and == for equality. This is a common choice, also found in languages like C, C++, Java, JavaScript, and PHP, though it does brand things a bit confusing for new programmers.

4.4.2. Updating variables¶

When an assignment statement is executed, the right-paw-side expression (i.east. the expression that comes later the assignment token) is evaluated outset. Then the result of that evaluation is written into the variable on the left mitt side, thereby changing it.

One of the most common forms of reassignment is an update, where the new value of the variable depends on its old value.

The second line means "go the current value of n, multiply it past three and add one, and put the answer back into n every bit its new value". So subsequently executing the 2 lines in a higher place, northward will have the value xvi.

If you try to get the value of a variable that doesn't be yet, y'all'll get an error:

                                >>>                                w                =                ten                +                ane                Traceback (most contempo call terminal):                                  File "<interactive input>", line i, in                NameError:                proper noun 'x' is non defined              

Earlier yous can update a variable, you have to initialize information technology, commonly with a simple consignment:

This 2nd argument — updating a variable by adding 1 to it — is very mutual. It is called an increment of the variable; subtracting 1 is called a decrement.

iv.5. The for loop¶

The for loop processes each detail in a sequence, so it is used with Python's sequence data types - strings, lists, and tuples.

Each item in turn is (re-)assigned to the loop variable, and the trunk of the loop is executed.

The general form of a for loop is:

                            for              LOOP_VARIABLE              in              SEQUENCE              :              STATEMENTS            

This is some other example of a compound statement in Python, and similar the branching statements, it has a header terminated by a colon ( : ) and a torso consisting of a sequence of one or more statements indented the same amount from the header.

The loop variable is created when the for argument runs, and then you practise not need to create the variable before then. Each iteration assigns the the loop variable to the adjacent element in the sequence, and and then executes the statements in the trunk. The statement finishes when the last element in the sequence is reached.

This type of menstruation is chosen a loop considering it loops dorsum around to the peak afterward each iteration.

                            for              friend              in              [              'Margot'              ,              'Kathryn'              ,              'Prisila'              ]:              invitation              =              "Hi "              +              friend              +              ".  Please come up to my political party on Saturday!"              impress              (              invitation              )            

Running through all the items in a sequence is called traversing the sequence, or traversal.

Yous should run this instance to see what it does.

Tip

As with all the examples you run into in this book, you lot should try this lawmaking out yourself and see what it does. You should also try to conceptualize the results before you practise, and create your ain related examples and effort them out too.

If you get the results you expected, pat yourself on the dorsum and motility on. If you don't, try to figure out why. This is the essence of the scientific method, and is essential if you want to recall like a computer programmer.

Often times yous will desire a loop that iterates a given number of times, or that iterates over a given sequence of numbers. The range function come up in handy for that.

                            >>>                            for              i              in              range              (              5              ):              ...                            print              (              'i is at present:'              ,              i              )              ...              i is now 0              i is now ane              i is now two              i is at present three              i is now 4              >>>            

four.6. Tables¶

One of the things loops are practiced for is generating tables. Before computers were readily available, people had to calculate logarithms, sines and cosines, and other mathematical functions by manus. To make that easier, mathematics books contained long tables listing the values of these functions. Creating the tables was slow and boring, and they tended to be full of errors.

When computers appeared on the scene, one of the initial reactions was, "This is great! We can use the computers to generate the tables, so in that location volition be no errors." That turned out to be true (mostly) but shortsighted. Soon thereafter, computers and calculators were so pervasive that the tables became obsolete.

Well, almost. For some operations, computers apply tables of values to become an guess respond and then perform computations to ameliorate the approximation. In some cases, there have been errors in the underlying tables, well-nigh famously in the table the Intel Pentium processor chip used to perform floating-betoken partition.

Although a log table is not as useful as it once was, it yet makes a good instance. The following plan outputs a sequence of values in the left cavalcade and ii raised to the power of that value in the right column:

                            for              ten              in              range              (              13              ):              # Generate numbers 0 to 12              print              (              x              ,              '              \t              '              ,              2              **              x              )            

Using the tab graphic symbol ( '\t' ) makes the output align nicely.

                            0       1              i       2              2       4              iii       8              iv       sixteen              5       32              6       64              7       128              eight       256              9       512              10      1024              xi      2048              12      4096            

iv.vii. The while statement¶

The full general syntax for the while statement looks like this:

                            while              BOOLEAN_EXPRESSION              :              STATEMENTS            

Like the branching statements and the for loop, the while statement is a compound argument consisting of a header and a body. A while loop executes an unknown number of times, as long at the BOOLEAN EXPRESSION is true.

Here is a uncomplicated instance:

                            number              =              0              prompt              =              "What is the meaning of life, the universe, and everything? "              while              number              !=              "42"              :              number              =              input              (              prompt              )            

Discover that if number is prepare to 42 on the first line, the body of the while statement will not execute at all.

Hither is a more elaborate example program demonstrating the apply of the while argument

                            name              =              'Harrison'              guess              =              input              (              "And then I'm thinking of person's proper name. Try to guess it: "              )              pos              =              0              while              guess              !=              name              and              pos              <              len              (              name              ):              print              (              "Nope, that's not it! Hint: letter "              ,              end              =              ''              )              print              (              pos              +              ane              ,              "is"              ,              name              [              pos              ]              +              ". "              ,              stop              =              ''              )              judge              =              input              (              "Guess again: "              )              pos              =              pos              +              1              if              pos              ==              len              (              name              )              and              name              !=              gauge              :              print              (              "Likewise bad, you couldn't get it.  The proper noun was"              ,              name              +              "."              )              else              :              print              (              "              \northward              Great, you got it in"              ,              pos              +              1              ,              "guesses!"              )            

The flow of execution for a while statement works similar this:

  1. Evaluate the status ( BOOLEAN EXPRESSION ), yielding False or True .

  2. If the condition is false, exit the while argument and continue execution at the next statement.

  3. If the status is true, execute each of the STATEMENTS in the body and then go back to step one.

The torso consists of all of the statements below the header with the same indentation.

The body of the loop should change the value of one or more variables so that eventually the status becomes false and the loop terminates. Otherwise the loop will echo forever, which is called an infinite loop.

An endless source of amusement for computer programmers is the observation that the directions on shampoo, lather, rinse, echo, are an infinite loop.

In the case here, nosotros can show that the loop terminates because nosotros know that the value of len(name) is finite, and we can see that the value of pos increments each fourth dimension through the loop, then eventually it will take to equal len(name) . In other cases, it is not so piece of cake to tell.

What you will find here is that the while loop is more piece of work for y'all — the programmer — than the equivalent for loop. When using a while loop one has to control the loop variable yourself: give information technology an initial value, exam for completion, and then make sure you lot modify something in the body so that the loop terminates.

4.viii. Choosing between for and while

So why have 2 kinds of loop if for looks easier? This next example shows a case where we need the extra power that we go from the while loop.

Use a for loop if you lot know, earlier you lot start looping, the maximum number of times that yous'll need to execute the body. For instance, if you lot're traversing a list of elements, you know that the maximum number of loop iterations you tin mayhap demand is "all the elements in the listing". Or if you need to print the 12 times table, nosotros know right away how many times the loop will need to run.

So any problem like "iterate this atmospheric condition model for 1000 cycles", or "search this listing of words", "discover all prime numbers upwardly to 10000" suggest that a for loop is best.

By contrast, if you are required to repeat some computation until some condition is met, and y'all cannot calculate in advance when this will happen, as we did in the "greatest name" program, you'll demand a while loop.

We call the first instance definite iteration — we accept some definite premises for what is needed. The latter case is called indefinite iteration — we're non sure how many iterations nosotros'll need — nosotros cannot fifty-fifty constitute an upper bound!

four.ix. Tracing a program¶

To write constructive computer programs a developer needs to develop the ability to trace the execution of a reckoner programme. Tracing involves "becoming the estimator" and following the flow of execution through a sample programme run, recording the country of all variables and any output the program generates subsequently each instruction is executed.

To understand this process, let'due south trace the execution of the program from The while statement department.

At the beginning of the trace, nosotros have a local variable, name with an initial value of 'Harrison' . The user will enter a string that is stored in the variable, guess . Permit's presume they enter 'Maribel' . The next line creates a variable named pos and gives it an intial value of 0 .

To keep track of all this equally you hand trace a programme, brand a cavalcade heading on a slice of newspaper for each variable created as the program runs and another one for output. Our trace so far would look something like this:

                            name       guess      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0            

Since guess != proper noun and pos < len(name) evaluates to True (take a minute to convince yourself of this), the loop body is executed.

The user will now see

                            Nope, that's not it! Hint: letter 1 is 'H'. Estimate again:            

Assuming the user enters Karen this time, pos volition be incremented, guess != name and pos < len(name) again evaluates to True , and our trace will now await similar this:

                            name       guess      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0    Nope, that's non it! Hint: letter of the alphabet one is 'H'. Gauge again:              'Harrison' 'Henry'    1    Nope, that's not it! Hint: alphabetic character 2 is 'a'. Guess again:            

A full trace of the program might produce something like this:

                            proper name       estimate      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0    Nope, that's not it! Hint: letter 1 is 'H'. Guess again:              'Harrison' 'Henry'    ane    Nope, that's not information technology! Hint: letter ii is 'a'. Guess again:              'Harrison' 'Hakeem'   two    Nope, that's not it! Hint: letter three is 'r'. Guess again:              'Harrison' 'Harold'   iii    Nope, that's not it! Hint: letter iv is 'r'. Guess once again:              'Harrison' 'Harry'    4    Nope, that's non it! Hint: alphabetic character 5 is 'i'. Judge again:              'Harrison' 'Harrison' 5    Corking, you got information technology in half dozen guesses!            

Tracing tin can be a bit tedious and error decumbent (that's why nosotros get computers to do this stuff in the first identify!), but it is an essential skill for a programmer to have. From a trace we can larn a lot nearly the mode our lawmaking works.

4.10. Abbreviated assignment¶

Incrementing a variable is so common that Python provides an abbreviated syntax for it:

                            >>>                            count              =              0              >>>                            count              +=              1              >>>                            count              1              >>>                            count              +=              i              >>>                            count              2            

count += one is an abreviation for count = count + i . Nosotros pronouce the operator equally "plus-equals". The increment value does non have to exist i:

                            >>>                            n              =              2              >>>                            northward              +=              5              >>>                            n              7            

There are similar abbreviations for -= , *= , /= , //= and %= :

                            >>>                            n              =              2              >>>                            n              *=              5              >>>                            n              x              >>>                            northward              -=              four              >>>                            northward              6              >>>                            n              //=              two              >>>                            due north              3              >>>                            n              %=              2              >>>                            n              1            

4.11. Some other while example: Guessing game¶

The following programme implements a elementary guessing game:

                            import              random              # Import the random module                            number              =              random              .              randrange              (              1              ,              1000              )              # Get random number between [one and 1000)              guesses              =              0              approximate              =              int              (              input              (              "Judge my number betwixt 1 and 1000: "              ))              while              guess              !=              number              :              guesses              +=              1              if              guess              >              number              :              print              (              guess              ,              "is too high."              )              elif              gauge              <              number              :              print              (              estimate              ,              " is too low."              )              guess              =              int              (              input              (              "Approximate again: "              ))              print              (              "              \n\n              Great, you lot got it in"              ,              guesses              ,              "guesses!"              )            

This plan makes apply of the mathematical law of trichotomy (given real numbers a and b, exactly one of these 3 must be true: a > b, a < b, or a == b).

iv.12. The break statement¶

The break argument is used to immediately go out the body of its loop. The next statement to be executed is the outset one later on the body:

                            for              i              in              [              12              ,              16              ,              17              ,              24              ,              29              ]:              if              i              %              2              ==              1              :              # if the number is odd              break              # immediately exit the loop              print              (              i              )              print              (              "washed"              )            

This prints:

4.13. The continue statement¶

This is a control flow argument that causes the program to immediately skip the processing of the remainder of the body of the loop, for the electric current iteration. But the loop however carries on running for its remaining iterations:

                            for              i              in              [              12              ,              16              ,              17              ,              24              ,              29              ,              thirty              ]:              if              i              %              2              ==              i              :              # if the number is odd              continue              # don't process it              impress              (              i              )              impress              (              "washed"              )            

This prints:

4.14. Another for example¶

Hither is an example that combines several of the things nosotros have learned:

                            judgement              =              input              (              'Delight enter a sentence: '              )              no_spaces              =              ''              for              letter of the alphabet              in              sentence              :              if              letter              !=              ' '              :              no_spaces              +=              letter              print              (              "You judgement with spaces removed:"              )              print              (              no_spaces              )            

Trace this program and make sure yous feel confident you understand how it works.

4.15. Nested Loops for Nested Data¶

At present nosotros'll come up with an fifty-fifty more adventurous list of structured data. In this case, we have a list of students. Each student has a name which is paired upwards with another listing of subjects that they are enrolled for:

                            students              =              [(              "Alejandro"              ,              [              "CompSci"              ,              "Physics"              ]),              (              "Justin"              ,              [              "Math"              ,              "CompSci"              ,              "Stats"              ]),              (              "Ed"              ,              [              "CompSci"              ,              "Accounting"              ,              "Economic science"              ]),              (              "Margot"              ,              [              "InfSys"              ,              "Bookkeeping"              ,              "Economics"              ,              "CommLaw"              ]),              (              "Peter"              ,              [              "Sociology"              ,              "Economics"              ,              "Law"              ,              "Stats"              ,              "Music"              ])]            

Here nosotros've assigned a list of five elements to the variable students . Let's print out each student name, and the number of subjects they are enrolled for:

                            # print all students with a count of their courses.              for              (              name              ,              subjects              )              in              students              :              impress              (              proper noun              ,              "takes"              ,              len              (              subjects              ),              "courses"              )            

Python agreeably responds with the following output:

                            Aljandro takes ii courses              Justin takes three courses              Ed takes four courses              Margot takes 4 courses              Peter takes five courses            

Now we'd like to ask how many students are taking CompSci. This needs a counter, and for each student we need a second loop that tests each of the subjects in turn:

                            # Count how many students are taking CompSci              counter              =              0              for              (              proper noun              ,              subjects              )              in              students              :              for              s              in              subjects              :              # a nested loop!              if              s              ==              "CompSci"              :              counter              +=              1              print              (              "The number of students taking CompSci is"              ,              counter              )            
                            The number of students taking CompSci is 3            

You should gear up a list of your own data that interests you — maybe a list of your CDs, each containing a listing of song titles on the CD, or a list of moving picture titles, each with a listing of movie stars who acted in the movie. You could then inquire questions like "Which movies starred Angelina Jolie?"

4.xvi. List comprehensions¶

A list comprehension is a syntactic construct that enables lists to exist created from other lists using a compact, mathematical syntax:

                            >>>                            numbers              =              [              1              ,              ii              ,              three              ,              4              ]              >>>                            [              x              **              2              for              x              in              numbers              ]              [1, 4, 9, 16]              >>>                            [              10              **              two              for              ten              in              numbers              if              ten              **              two              >              eight              ]              [nine, 16]              >>>                            [(              x              ,              x              **              2              ,              10              **              3              )              for              x              in              numbers              ]              [(1, ane, ane), (2, 4, eight), (3, ix, 27), (4, 16, 64)]              >>>                            files              =              [              'bin'              ,              'Information'              ,              'Desktop'              ,              '.bashrc'              ,              '.ssh'              ,              '.vimrc'              ]              >>>                            [              name              for              proper noun              in              files              if              name              [              0              ]              !=              '.'              ]              ['bin', 'Data', 'Desktop']              >>>                            letters              =              [              'a'              ,              'b'              ,              'c'              ]              >>>                            [              n              *              letter              for              due north              in              numbers              for              alphabetic character              in              messages              ]              ['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc', 'aaaa', 'bbbb', 'cccc']              >>>            

The full general syntax for a list comprehension expression is:

                            [              expr              for              item1              in              seq1              for              item2              in              seq2              ...              for              itemx              in              seqx              if              condition              ]            

This list expression has the same result as:

                            output_sequence              =              []              for              item1              in              seq1              :              for              item2              in              seq2              :              ...              for              itemx              in              seqx              :              if              condition              :              output_sequence              .              append              (              expr              )            

As you can meet, the list comprehension is much more compact.

iv.17. Glossary¶

append

To add together new data to the end of a file or other data object.

block

A group of consecutive statements with the aforementioned indentation.

torso

The block of statements in a compound argument that follows the header.

co-operative

One of the possible paths of the menstruum of execution determined by conditional execution.

chained conditional

A provisional co-operative with more two possible flows of execution. In Python chained conditionals are written with if ... elif ... else statements.

compound statement

A Python statement that has two parts: a header and a torso. The header begins with a keyword and ends with a colon ( : ). The trunk contains a serial of other Python statements, all indented the same amount.

Note

We will use the Python standard of iv spaces for each level of indentation.

condition

The boolean expression in a conditional statement that determines which branch is executed.

conditional statement

A statement that controls the menses of execution depending on some status. In Python the keywords if , elif , and else are used for conditional statements.

counter

A variable used to count something, usually initialized to zero and incremented in the trunk of a loop.

cursor

An invisible marker that keeps rail of where the adjacent character will exist printed.

decrement

Decrease by ane.

definite iteration

A loop where nosotros have an upper bound on the number of times the body will be executed. Definite iteration is commonly best coded as a for loop.

delimiter

A sequence of one or more characters used to specify the boundary between separate parts of text.

increase

Both as a noun and as a verb, increment means to increase by 1.

space loop

A loop in which the terminating condition is never satisfied.

indefinite iteration

A loop where we only need to continue going until some condition is met. A while argument is used for this example.

initialization (of a variable)

To initialize a variable is to give information technology an initial value. Since in Python variables don't exist until they are assigned values, they are initialized when they are created. In other programming languages this is not the case, and variables can be created without being initialized, in which case they have either default or garbage values.

iteration

Repeated execution of a set of programming statements.

loop

A argument or group of statements that execute repeatedly until a terminating condition is satisfied.

loop variable

A variable used as part of the terminating condition of a loop.

nested loop

A loop inside the body of another loop.

nesting

One program structure within another, such as a provisional statement inside a branch of another conditional argument.

newline

A special grapheme that causes the cursor to motion to the commencement of the side by side line.

prompt

A visual cue that tells the user to input information.

reassignment

Making more than one assignment to the same variable during the execution of a plan.

tab

A special grapheme that causes the cursor to move to the side by side tab stop on the electric current line.

trichotomy

Given whatsoever real numbers a and b, exactly one of the following relations holds: a < b, a > b, or a == b. Thus when you can establish that 2 of the relations are false, you tin can assume the remaining ane is true.

trace

To follow the flow of execution of a program by mitt, recording the change of state of the variables and whatsoever output produced.