iv. Conditionals and loops¶

4.1. Conditional execution¶

4.one.ane. The if statement¶

In lodge to write useful programs, we almost e'er need the power to cheque conditions and change the behavior of the programme accordingly. Provisional statements requite united states of america this ability. The simplest form is the if argument, which has the genaral form:

                                if                BOOLEAN                EXPRESSION                :                STATEMENTS              

A few important things to notation about if statements:

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

  2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.

  3. All lines indented the same amount after the colon will be executed whenever the BOOLEAN_EXPRESSION is true.

Here is an instance:

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

The boolean expression subsequently the if statement is called the condition. If it is true, then all the indented statements get executed. What happens if the condition is false, and nutrient is not equal to 'spam' ? In a elementary if statement like this, nothing happens, and the program continues on to the adjacent statement.

Run this example code and come across what happens. And so alter the value of food to something other than 'spam' and run information technology again, confirming that yous don't go any output.

Flowchart of an if statement

_images/flowchart_if_only.png

Every bit with the for statement from the last chapter, the if statement is a compound statement. Chemical compound statements consist of a header line and a body. The header line of the if statement begins with the keyword if followed by a boolean expression and ends with a colon ( : ).

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

Indentation and the PEP 8 Python Fashion Guide

The Python community has developed a Style Guide for Python Code, usually referred to simply as "PEP viii". The Python Enhancement Proposals, or PEPs, are office of the process the Python customs uses to discuss and adopt changes to the language.

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

To help us learn to write well styled Python code, there is a programme called pep8 that works as an automated style guide checker for Python source lawmaking. pep8 is installable every bit a parcel on Debian based GNU/Linux systems like Ubuntu.

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

4.1.2. The if else statement¶

It is frequently the example that yous desire one thing to happen when a condition it truthful, and something else to happen when information technology is false. For that we have the if else statement.

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

Here, the showtime print argument will execute if food is equal to 'spam' , and the print argument indented under the else clause will get executed when it is not.

Flowchart of a if else argument

_images/flowchart_if_else.png

The syntax for an if else statement looks similar this:

                                if                BOOLEAN                EXPRESSION                :                STATEMENTS_1                # executed if condition evaluates to Truthful                else                :                STATEMENTS_2                # executed if condition evaluates to False              

Each statement inside the if block of an if else argument is executed in order if the boolean expression evaluates to True . The entire block of statements is skipped if the boolean expression evaluates to Imitation , and instead all the statements under the else clause are executed.

There is no limit on the number of statements that can announced nether the two clauses of an if else statement, but there has to exist at to the lowest degree ane argument in each block. Occasionally, it is useful to accept a section with no statements (usually every bit a place keeper, or scaffolding, for code you haven't written withal). In that case, yous can use the pass statement, which does nothing except act equally a placeholder.

                                if                True                :                # This is e'er truthful                pass                # so this is ever executed, but it does nothing                else                :                pass              

Python terminology

Python documentation sometimes uses the term suite of statements to hateful what nosotros have called a cake here. They mean the same thing, and since most other languages and reckoner scientists use the discussion block, nosotros'll stick with that.

Notice too that else is non a argument. The if argument has 2 clauses, ane of which is the (optional) else clause. The Python documentation calls both forms, together with the next form nosotros are about to meet, the if argument.

iv.2. Chained conditionals¶

Sometimes there are more than two possibilities and we need more than two branches. One style to express a computation like that is a chained conditional:

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

Flowchart of this chained conditional

_images/flowchart_chained_conditional.png

elif is an abbreviation of else if . Again, exactly one branch volition exist executed. At that place is no limit of the number of elif statements merely only a single (and optional) final else statement is immune and it must exist the last branch in the statement:

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

Each condition is checked in order. If the offset is imitation, the adjacent is checked, and and then on. If i of them is true, the corresponding branch executes, and the statement ends. Fifty-fifty if more than ane condition is true, just the get-go truthful branch executes.

4.iii. Nested conditionals¶

One provisional can also be nested within another. (It is the same theme of composibility, again!) We could accept written the previous example equally follows:

Flowchart of this nested conditional

_images/flowchart_nested_conditional.png

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

The outer conditional contains ii branches. The second branch contains another if argument, which has two branches of its own. Those ii branches could contain conditional statements as well.

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

Logical operators often provide a way to simplify nested provisional statements. For example, we can rewrite the post-obit lawmaking using a single conditional:

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

The impress office is called only if nosotros make it past both the conditionals, so we can use the and operator:

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

Note

Python really allows a brusk hand form for this, then the following will also piece of work:

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

four.4. Iteration¶

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

Repeated execution of a prepare of statements is chosen iteration. Python has two statements for iteration – the for statement, which we met concluding chapter, and the while statement.

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

4.4.1. Reassignmnent¶

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

                                bruce                =                five                print                (                bruce                )                bruce                =                seven                impress                (                bruce                )              

The output of this program is

because the commencement time bruce is printed, its value is 5, and the 2nd time, its value is 7.

Here is what reassignment looks like in a state snapshot:

reassignment

With reassignment it is specially important 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. Different mathematics, it is not! Remember that the Python token for the equality operator is == .

Note too that an equality test is symmetric, simply assignment is not. For case, if a == 7 then 7 == a . But in Python, the statement a = 7 is legal and 7 = a is not.

Furthermore, in mathematics, a statement of equality is always true. If a == b now, then a will always equal b . In Python, an assignment statement tin make 2 variables equal, but because of the possibility of reassignment, they don't have to stay that style:

                                a                =                five                b                =                a                # afterward executing this line, a and b are now equal                a                =                3                # afterwards executing this line, a and b are no longer equal              

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

Note

In some programming languages, a unlike 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 pick, besides establish in languages like C, C++, Coffee, JavaScript, and PHP, though it does make things a fleck confusing for new programmers.

iv.4.2. Updating variables¶

When an assignment statement is executed, the right-hand-side expression (i.east. the expression that comes after the consignment token) is evaluated beginning. Then the upshot of that evaluation is written into the variable on the left paw side, thereby changing it.

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

The 2nd line ways "get the current value of due north, multiply information technology by three and add one, and put the answer back into n every bit its new value". And then after executing the 2 lines above, northward volition have the value xvi.

If you try to get the value of a variable that doesn't exist nevertheless, you'll get an fault:

                                >>>                                w                =                x                +                1                Traceback (nearly recent call concluding):                                  File "<interactive input>", line one, in                NameError:                proper noun '10' is non defined              

Earlier you tin can update a variable, yous have to initialize it, commonly with a elementary assignment:

This second argument — updating a variable past adding 1 to information technology — is very common. It is chosen an increment of the variable; subtracting one is chosen a decrement.

4.five. The for loop¶

The for loop processes each item in a sequence, and then information technology is used with Python's sequence data types - strings, lists, and tuples.

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

The general form of a for loop is:

                            for              LOOP_VARIABLE              in              SEQUENCE              :              STATEMENTS            

This is another example of a compound statement in Python, and similar the branching statements, information technology has a header terminated by a colon ( : ) and a body 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, so yous do not demand to create the variable before and then. Each iteration assigns the the loop variable to the next element in the sequence, and and so executes the statements in the body. The argument finishes when the last element in the sequence is reached.

This type of flow is called a loop considering it loops back around to the top after each iteration.

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

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

You should run this instance to see what it does.

Tip

Every bit with all the examples you see in this book, y'all should endeavour this code out yourself and see what it does. You should also try to anticipate the results before yous do, and create your own related examples and try them out every bit well.

If you get the results you expected, pat yourself on the back and move on. If you don't, try to effigy out why. This is the essence of the scientific method, and is essential if you want to call up like a figurer programmer.

Frequently times you will want a loop that iterates a given number of times, or that iterates over a given sequence of numbers. The range function come in handy for that.

                            >>>                            for              i              in              range              (              5              ):              ...                            print              (              'i is now:'              ,              i              )              ...              i is now 0              i is now 1              i is now two              i is now 3              i is now 4              >>>            

4.6. Tables¶

One of the things loops are good for is generating tables. Before computers were readily bachelor, people had to calculate logarithms, sines and cosines, and other mathematical functions past paw. To make that easier, mathematics books contained long tables listing the values of these functions. Creating the tables was slow and tiresome, and they tended to be total of errors.

When computers appeared on the scene, i of the initial reactions was, "This is cracking! We tin can use the computers to generate the tables, so there will exist no errors." That turned out to be true (generally) simply shortsighted. Before long thereafter, computers and calculators were so pervasive that the tables became obsolete.

Well, almost. For some operations, computers use tables of values to get an guess respond and so perform computations to better the approximation. In some cases, there have been errors in the underlying tables, most famously in the tabular array the Intel Pentium processor chip used to perform floating-point segmentation.

Although a log tabular array is non every bit useful as it once was, it all the same makes a good example. The following plan outputs a sequence of values in the left column and ii raised to the power of that value in the right column:

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

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

                            0       1              i       ii              2       four              3       eight              4       16              5       32              half-dozen       64              7       128              viii       256              9       512              10      1024              11      2048              12      4096            

4.7. 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 statement consisting of a header and a body. A while loop executes an unknown number of times, as long at the BOOLEAN EXPRESSION is true.

Hither is a simple example:

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

Notice that if number is fix to 42 on the first line, the trunk of the while argument volition not execute at all.

Here is a more than elaborate example program demonstrating the utilize of the while statement

                            name              =              'Harrison'              guess              =              input              (              "And then I'k thinking of person's proper noun. Effort to guess information technology: "              )              pos              =              0              while              guess              !=              proper name              and              pos              <              len              (              name              ):              print              (              "Nope, that's not it! Hint: letter "              ,              end              =              ''              )              print              (              pos              +              i              ,              "is"              ,              proper name              [              pos              ]              +              ". "              ,              end              =              ''              )              judge              =              input              (              "Guess once more: "              )              pos              =              pos              +              1              if              pos              ==              len              (              proper name              )              and              proper noun              !=              approximate              :              print              (              "Too bad, you couldn't go it.  The proper noun was"              ,              name              +              "."              )              else              :              print              (              "              \n              Bully, you got it in"              ,              pos              +              1              ,              "guesses!"              )            

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

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

  2. If the condition is simulated, get out the while statement and proceed 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 i.

The body 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 condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

An endless source of entertainment for reckoner programmers is the observation that the directions on shampoo, lather, rinse, repeat, are an infinite loop.

In the case here, we can bear witness that the loop terminates because we 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, and so eventually it volition have to equal len(proper noun) . In other cases, it is not so like shooting fish in a barrel to tell.

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

four.eight. Choosing between for and while

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

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

Then whatsoever trouble like "iterate this atmospheric condition model for g cycles", or "search this list of words", "find all prime numbers up to 10000" suggest that a for loop is all-time.

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

We telephone call the first instance definite iteration — we have some definite premises for what is needed. The latter case is called indefinite iteration — nosotros're not sure how many iterations we'll demand — we cannot even constitute an upper bound!

4.ix. Tracing a program¶

To write effective computer programs a developer needs to develop the ability to trace the execution of a estimator program. Tracing involves "condign the computer" and following the menstruation of execution through a sample program run, recording the country of all variables and any output the programme generates after each teaching is executed.

To understand this procedure, let's trace the execution of the program from The while statement section.

At the showtime of the trace, we have a local variable, name with an initial value of 'Harrison' . The user will enter a cord that is stored in the variable, judge . Let's presume they enter 'Maribel' . The next line creates a variable named pos and gives it an intial value of 0 .

To go along track of all this as you hand trace a program, make a column heading on a piece of paper for each variable created as the program runs and another one for output. Our trace so far would expect something like this:

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

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

The user will now come across

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

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

                            name       guess      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0    Nope, that's not it! Hint: letter i is 'H'. Guess again:              'Harrison' 'Henry'    one    Nope, that's not it! Hint: letter 2 is 'a'. Judge again:            

A full trace of the plan might produce something similar this:

                            name       guess      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0    Nope, that's not it! Hint: alphabetic character 1 is 'H'. Guess again:              'Harrison' 'Henry'    i    Nope, that's not information technology! Hint: letter of the alphabet 2 is 'a'. Judge over again:              'Harrison' 'Hakeem'   2    Nope, that'south not it! Hint: letter of the alphabet iii is 'r'. Guess once more:              'Harrison' 'Harold'   iii    Nope, that's not it! Hint: letter 4 is 'r'. Guess once more:              'Harrison' 'Harry'    iv    Nope, that's not it! Hint: alphabetic character 5 is 'i'. Approximate once more:              'Harrison' 'Harrison' 5    Great, you got it in vi guesses!            

Tracing tin be a fleck tedious and mistake prone (that's why nosotros get computers to do this stuff in the first place!), but it is an essential skill for a programmer to have. From a trace we can learn a lot about the way our lawmaking works.

4.x. Abbreviated assignment¶

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

                            >>>                            count              =              0              >>>                            count              +=              ane              >>>                            count              1              >>>                            count              +=              i              >>>                            count              ii            

count += i is an abreviation for count = count + 1 . We pronouce the operator as "plus-equals". The increment value does not have to be i:

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

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

                            >>>                            northward              =              2              >>>                            n              *=              5              >>>                            n              ten              >>>                            northward              -=              4              >>>                            n              6              >>>                            n              //=              2              >>>                            n              3              >>>                            n              %=              2              >>>                            n              1            

4.eleven. Another while instance: Guessing game¶

The following programme implements a simple guessing game:

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

This program makes use of the mathematical law of trichotomy (given real numbers a and b, exactly one of these three must exist true: a > b, a < b, or a == b).

4.12. The interruption statement¶

The break argument is used to immediately leave the torso of its loop. The side by side statement to be executed is the first ane later on the body:

                            for              i              in              [              12              ,              16              ,              17              ,              24              ,              29              ]:              if              i              %              two              ==              1              :              # if the number is odd              pause              # immediately get out the loop              impress              (              i              )              print              (              "washed"              )            

This prints:

iv.13. The continue argument¶

This is a control flow statement that causes the program to immediately skip the processing of the rest of the body of the loop, for the current iteration. Merely the loop yet carries on running for its remaining iterations:

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

This prints:

4.14. Another for example¶

Here is an example that combines several of the things we have learned:

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

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

4.15. Nested Loops for Nested Data¶

Now we'll come upward with an even more adventurous list of structured data. In this case, we take a list of students. Each student has a proper noun which is paired up with another listing of subjects that they are enrolled for:

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

Here we've assigned a list of five elements to the variable students . Let'south print out each educatee proper 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              (              name              ,              "takes"              ,              len              (              subjects              ),              "courses"              )            

Python agreeably responds with the following output:

                            Aljandro takes 2 courses              Justin takes 3 courses              Ed takes 4 courses              Margot takes 4 courses              Peter takes v courses            

Now we'd like to inquire how many students are taking CompSci. This needs a counter, and for each pupil nosotros demand a 2nd loop that tests each of the subjects in turn:

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

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

4.xvi. List comprehensions¶

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

                            >>>                            numbers              =              [              1              ,              two              ,              3              ,              4              ]              >>>                            [              x              **              2              for              x              in              numbers              ]              [1, 4, 9, xvi]              >>>                            [              10              **              2              for              ten              in              numbers              if              ten              **              2              >              8              ]              [9, xvi]              >>>                            [(              10              ,              x              **              two              ,              x              **              3              )              for              x              in              numbers              ]              [(ane, i, 1), (ii, 4, viii), (three, ix, 27), (4, 16, 64)]              >>>                            files              =              [              'bin'              ,              'Data'              ,              'Desktop'              ,              '.bashrc'              ,              '.ssh'              ,              '.vimrc'              ]              >>>                            [              proper noun              for              name              in              files              if              name              [              0              ]              !=              '.'              ]              ['bin', 'Data', 'Desktop']              >>>                            letters              =              [              'a'              ,              'b'              ,              'c'              ]              >>>                            [              north              *              letter              for              n              in              numbers              for              letter              in              letters              ]              ['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 effect every bit:

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

As you can see, the listing comprehension is much more compact.

4.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 same indentation.

torso

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

branch

I of the possible paths of the flow of execution determined by provisional execution.

chained conditional

A conditional co-operative with more than than 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 body. The header begins with a keyword and ends with a colon ( : ). The body contains a series of other Python statements, all indented the same amount.

Note

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

condition

The boolean expression in a provisional argument that determines which branch is executed.

conditional statement

A statement that controls the flow of execution depending on some condition. 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 runway of where the next character will be printed.

decrement

Decrease by 1.

definite iteration

A loop where nosotros accept an upper leap on the number of times the body will exist executed. Definite iteration is unremarkably best coded as a for loop.

delimiter

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

increase

Both every bit a noun and as a verb, increment means to increment by ane.

infinite loop

A loop in which the terminating condition is never satisfied.

indefinite iteration

A loop where we just demand to keep going until some condition is met. A while statement is used for this case.

initialization (of a variable)

To initialize a variable is to give it 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 instance they have either default or garbage values.

iteration

Repeated execution of a set of programming statements.

loop

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

loop variable

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

nested loop

A loop inside the trunk of some other loop.

nesting

1 program structure inside another, such as a provisional statement inside a branch of another conditional statement.

newline

A special character that causes the cursor to move to the beginning of the adjacent line.

prompt

A visual cue that tells the user to input data.

reassignment

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

tab

A special graphic symbol that causes the cursor to move to the next tab stop on the current line.

trichotomy

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

trace

To follow the flow of execution of a programme by hand, recording the alter of state of the variables and whatever output produced.