iv. Conditionals and loops¶

4.1. Conditional execution¶

4.1.1. The if argument¶

In order to write useful programs, we nearly always need the power to cheque conditions and change the behavior of the program accordingly. Provisional statements requite the states this power. The simplest course is the if statement, which has the genaral grade:

                                if                BOOLEAN                EXPRESSION                :                STATEMENTS              

A few of import things to note virtually if statements:

  1. The colon ( : ) is significant and required. It separates the header of the compound statement from the torso.

  2. The line after the colon must exist indented. Information technology is standard in Python to use four spaces for indenting.

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

Here is an case:

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

The boolean expression after the if statement is chosen 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 simple if statement like this, nothing happens, and the program continues on to the next argument.

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

Flowchart of an if statement

_images/flowchart_if_only.png

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

The indented statements that follow are chosen a cake. The start unindented argument marks the end of the block. Each argument inside the block must take the same indentation.

Indentation and the PEP 8 Python Way Guide

The Python community has developed a Style Guide for Python Code, ordinarily referred to but as "PEP eight". The Python Enhancement Proposals, or PEPs, are part of the process the Python customs uses to hash out and adopt changes to the language.

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

To help united states learn to write well styled Python lawmaking, there is a program chosen pep8 that works as an automatic manner guide checker for Python source code. pep8 is installable every bit a bundle on Debian based GNU/Linux systems like Ubuntu.

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

four.ane.2. The if else statement¶

Information technology is ofttimes the case that y'all want one thing to happen when a status information technology true, and something else to happen when it is false. For that we have the if else argument.

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

Here, the first print statement will execute if food is equal to 'spam' , and the impress argument indented nether the else clause will go executed when it is not.

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 status evaluates to True                else                :                STATEMENTS_2                # executed if condition evaluates to Faux              

Each argument inside the if cake of an if else argument is executed in order if the boolean expression evaluates to True . The unabridged block 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 two clauses of an if else statement, but there has to be at to the lowest degree one statement in each block. Occasionally, information technology is useful to accept a section with no statements (usually every bit a place keeper, or scaffolding, for code you oasis't written all the same). In that instance, you can use the pass statement, which does goose egg except act as a placeholder.

                                if                True                :                # This is always true                pass                # so this is always executed, just it does nothing                else                :                pass              

Python terminology

Python documentation sometimes uses the term suite of statements to mean what we take called a block hither. They mean the same thing, and since near other languages and estimator scientists use the word block, we'll stick with that.

Detect likewise that else is not a statement. The if statement has two 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.2. Chained conditionals¶

Sometimes at that place are more than ii possibilities and we need more than ii branches. One way to limited a computation like that is a chained provisional:

                            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 . Once again, exactly one co-operative volition exist executed. There is no limit of the number of elif statements but merely a single (and optional) final else statement is immune and it must be the last branch in the statement:

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

Each condition is checked in guild. If the offset is false, the adjacent is checked, and so on. If i of them is true, the corresponding branch executes, and the statement ends. Even if more than 1 condition is true, only the starting time true co-operative executes.

4.3. Nested conditionals¶

One provisional can also be nested within another. (Information technology is the same theme of composibility, again!) We could take written the previous case equally follows:

Flowchart of this nested conditional

_images/flowchart_nested_conditional.png

                            if              ten              <              y              :              STATEMENTS_A              else              :              if              ten              >              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 as well.

Although the indentation of the statements makes the structure apparent, nested conditionals very quickly get hard to read. In general, it is a good idea to avoid them when you can.

Logical operators often provide a style to simplify nested conditional statements. For case, we can rewrite the following code using a single conditional:

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

The print part is called only if we brand it past both the conditionals, so we can use the and operator:

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

Note

Python actually allows a short hand course for this, so the following will also piece of work:

                                if                0                <                x                <                10                :                print                (                "10 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 set of statements is called iteration. Python has two statements for iteration – the for statement, which we met last chapter, and the while argument.

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

four.iv.one. Reassignmnent¶

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

                                bruce                =                5                print                (                bruce                )                bruce                =                seven                impress                (                bruce                )              

The output of this program is

because the kickoff 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 betwixt an assignment argument and a boolean expression that tests for equality. Considering Python uses the equal token ( = ) for assignment, information technology is tempting to interpret a statement similar a = b as a boolean test. Dissimilar mathematics, it is not! Call back that the Python token for the equality operator is == .

Note also that an equality exam is symmetric, but assignment is non. For example, if a == vii so 7 == a . Merely in Python, the statement a = 7 is legal and 7 = a is not.

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

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

The third line changes the value of a but does non change the value of b , and then they are no longer equal.

Annotation

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

iv.4.2. Updating variables¶

When an assignment argument is executed, the correct-mitt-side expression (i.e. the expression that comes afterwards the assignment token) is evaluated first. So the result of that evaluation is written into the variable on the left mitt side, thereby changing information technology.

1 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 "get the current value of north, multiply it by three and add ane, and put the respond back into due north as its new value". So after executing the two lines above, n will have the value 16.

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

                                >>>                                w                =                x                +                one                Traceback (most recent call last):                                  File "<interactive input>", line 1, in                NameError:                name '10' is not defined              

Before you lot tin can update a variable, you have to initialize it, ordinarily with a simple assignment:

This second argument — updating a variable by adding ane to information technology — is very mutual. It is called an increment of the variable; subtracting 1 is called a decrement.

4.v. The for loop¶

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

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

The full general grade of a for loop is:

                            for              LOOP_VARIABLE              in              SEQUENCE              :              STATEMENTS            

This is another example of a compound statement in Python, and like 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 statement runs, so you do not need to create the variable earlier then. Each iteration assigns the the loop variable to the side by side element in the sequence, so executes the statements in the body. The statement finishes when the last element in the sequence is reached.

This type of flow is called a loop because information technology loops back around to the elevation subsequently each iteration.

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

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

Yous should run this example to see what information technology does.

Tip

As with all the examples you run into in this book, yous should try this code out yourself and see what it does. Y'all should as well try to anticipate the results before you do, and create your own related examples and try them out as well.

If y'all get the results you expected, pat yourself on the back and motility on. If you lot don't, attempt to figure out why. This is the essence of the scientific method, and is essential if you want to remember like a computer developer.

Often times you volition want a loop that iterates a given number of times, or that iterates over a given sequence of numbers. The range role come up in handy for that.

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

4.six. Tables¶

I 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 hand. To brand that easier, mathematics books independent long tables list the values of these functions. Creating the tables was tiresome and boring, and they tended to exist total of errors.

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

Well, near. For some operations, computers use tables of values to get an gauge answer and then perform computations to improve the approximation. In some cases, there have been errors in the underlying tables, virtually famously in the tabular array the Intel Pentium processor scrap used to perform floating-indicate sectionalization.

Although a log tabular array is not as useful as it once was, it notwithstanding makes a good example. The following program outputs a sequence of values in the left column and 2 raised to the power of that value in the right column:

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

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

                            0       1              i       2              2       iv              iii       8              four       16              v       32              vi       64              vii       128              8       256              9       512              10      1024              xi      2048              12      4096            

4.7. The while statement¶

The general syntax for the while statement looks like this:

                            while              BOOLEAN_EXPRESSION              :              STATEMENTS            

Like the branching statements and the for loop, the while argument 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.

Here is a simple example:

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

Observe that if number is set to 42 on the first line, the body of the while argument volition not execute at all.

Hither is a more than elaborate example program demonstrating the use of the while statement

                            proper name              =              'Harrison'              guess              =              input              (              "And then I'm thinking of person's name. Attempt to guess it: "              )              pos              =              0              while              guess              !=              name              and              pos              <              len              (              proper noun              ):              impress              (              "Nope, that'south not it! Hint: letter of the alphabet "              ,              finish              =              ''              )              print              (              pos              +              1              ,              "is"              ,              proper noun              [              pos              ]              +              ". "              ,              stop              =              ''              )              estimate              =              input              (              "Guess over again: "              )              pos              =              pos              +              1              if              pos              ==              len              (              name              )              and              name              !=              guess              :              impress              (              "Too bad, you couldn't become it.  The proper noun was"              ,              name              +              "."              )              else              :              print              (              "              \n              Groovy, you lot got it in"              ,              pos              +              i              ,              "guesses!"              )            

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

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

  2. If the status is simulated, exit the while statement and continue execution at the next statement.

  3. If the condition is true, execute each of the STATEMENTS in the body and then become dorsum to step 1.

The body consists of all of the statements beneath the header with the aforementioned indentation.

The body of the loop should modify the value of one or more than variables and then that somewhen the condition becomes faux and the loop terminates. Otherwise the loop will echo forever, which is called an infinite loop.

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

In the example here, we tin can bear witness that the loop terminates considering nosotros know that the value of len(proper noun) is finite, and we can encounter that the value of pos increments each time through the loop, so somewhen information technology will take to equal len(name) . In other cases, it is not so easy to tell.

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

four.8. Choosing between for and while

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

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

So whatever problem similar "iterate this weather model for grand 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 y'all are required to repeat some computation until some status is met, and y'all cannot calculate in accelerate when this will happen, as we did in the "greatest name" plan, you'll demand a while loop.

We call the start case definite iteration — we have some definite bounds for what is needed. The latter example is called indefinite iteration — we're not sure how many iterations nosotros'll need — we cannot even plant an upper jump!

4.9. Tracing a program¶

To write constructive computer programs a programmer needs to develop the ability to trace the execution of a computer program. Tracing involves "becoming the computer" and following the flow of execution through a sample programme run, recording the state of all variables and any output the program generates afterward each didactics is executed.

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

At the get-go of the trace, we 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 assume they enter 'Maribel' . The next line creates a variable named pos and gives it an intial value of 0 .

To continue runway of all this every bit y'all hand trace a program, make a column heading on a piece of newspaper for each variable created every bit the programme runs and another one for output. Our trace so far would wait something like this:

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

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

The user will now see

                            Nope, that'south not it! Hint: alphabetic character 1 is 'H'. Guess again:            

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

                            proper name       guess      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0    Nope, that'south not it! Hint: letter 1 is 'H'. Guess again:              'Harrison' 'Henry'    1    Nope, that'southward not it! Hint: letter 2 is 'a'. Guess again:            

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

                            proper name       approximate      pos  output              ----       -----      ---  ------              'Harrison' 'Maribel'  0    Nope, that's non it! Hint: alphabetic character 1 is 'H'. Guess again:              'Harrison' 'Henry'    i    Nope, that'southward not it! Hint: letter two is 'a'. Guess again:              'Harrison' 'Hakeem'   2    Nope, that's not information technology! Hint: letter three is 'r'. Guess over again:              'Harrison' 'Harold'   three    Nope, that's non information technology! Hint: letter 4 is 'r'. Judge again:              'Harrison' 'Harry'    four    Nope, that'due south not information technology! Hint: letter 5 is 'i'. Guess again:              'Harrison' 'Harrison' 5    Great, you got it in six guesses!            

Tracing can exist a flake tedious and error decumbent (that's why we get computers to exercise this stuff in the first place!), just it is an essential skill for a programmer to take. From a trace we can learn a lot about the way our code 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              +=              1              >>>                            count              2            

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

                            >>>                            northward              =              2              >>>                            n              +=              v              >>>                            n              7            

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

                            >>>                            northward              =              2              >>>                            northward              *=              5              >>>                            n              x              >>>                            n              -=              4              >>>                            n              6              >>>                            n              //=              two              >>>                            due north              3              >>>                            n              %=              ii              >>>                            n              one            

iv.xi. Another while example: Guessing game¶

The post-obit program implements a simple guessing game:

                            import              random              # Import the random module                            number              =              random              .              randrange              (              1              ,              g              )              # Get random number between [1 and chiliad)              guesses              =              0              approximate              =              int              (              input              (              "Judge my number between 1 and 1000: "              ))              while              guess              !=              number              :              guesses              +=              1              if              guess              >              number              :              print              (              approximate              ,              "is too high."              )              elif              guess              <              number              :              print              (              estimate              ,              " is besides low."              )              judge              =              int              (              input              (              "Guess again: "              ))              print              (              "              \n\n              Swell, y'all got it in"              ,              guesses              ,              "guesses!"              )            

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

four.12. The break argument¶

The break statement is used to immediately leave the body of its loop. The adjacent argument to be executed is the kickoff one after the body:

                            for              i              in              [              12              ,              16              ,              17              ,              24              ,              29              ]:              if              i              %              2              ==              one              :              # if the number is odd              suspension              # immediately go out the loop              impress              (              i              )              print              (              "done"              )            

This prints:

4.13. The continue statement¶

This is a control period statement that causes the program to immediately skip the processing of the residual of the body of the loop, for the current iteration. But the loop still carries on running for its remaining iterations:

                            for              i              in              [              12              ,              16              ,              17              ,              24              ,              29              ,              30              ]:              if              i              %              2              ==              1              :              # if the number is odd              go along              # don't process it              impress              (              i              )              print              (              "done"              )            

This prints:

4.14. Another for example¶

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

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

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

four.15. Nested Loops for Nested Data¶

Now we'll come upward with an fifty-fifty more adventurous list of structured data. In this instance, we have a list of students. Each student has a name which is paired up with another list 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"              ,              [              "Folklore"              ,              "Economic science"              ,              "Constabulary"              ,              "Stats"              ,              "Music"              ])]            

Here we've assigned a listing of v elements to the variable students . Let'south print out each educatee name, and the number of subjects they are enrolled for:

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

Python agreeably responds with the following output:

                            Aljandro takes ii courses              Justin takes 3 courses              Ed takes 4 courses              Margot takes iv courses              Peter takes v courses            

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

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

You should fix a list of your own data that interests you — possibly a list of your CDs, each containing a listing of song titles on the CD, or a listing of moving-picture show titles, each with a listing of movie stars who acted in the movie. You could and then ask questions similar "Which movies starred Angelina Jolie?"

4.sixteen. List comprehensions¶

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

                            >>>                            numbers              =              [              1              ,              two              ,              3              ,              iv              ]              >>>                            [              x              **              two              for              x              in              numbers              ]              [one, 4, nine, 16]              >>>                            [              10              **              2              for              x              in              numbers              if              x              **              2              >              8              ]              [9, 16]              >>>                            [(              x              ,              ten              **              2              ,              ten              **              3              )              for              x              in              numbers              ]              [(1, 1, 1), (2, four, 8), (iii, 9, 27), (4, 16, 64)]              >>>                            files              =              [              'bin'              ,              'Information'              ,              'Desktop'              ,              '.bashrc'              ,              '.ssh'              ,              '.vimrc'              ]              >>>                            [              name              for              name              in              files              if              name              [              0              ]              !=              '.'              ]              ['bin', 'Data', 'Desktop']              >>>                            messages              =              [              'a'              ,              'b'              ,              'c'              ]              >>>                            [              north              *              letter              for              n              in              numbers              for              letter of the alphabet              in              letters              ]              ['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc', 'aaaa', 'bbbb', 'cccc']              >>>            

The general syntax for a listing comprehension expression is:

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

This list expression has the aforementioned event every bit:

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

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

4.17. Glossary¶

append

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

block

A group of consecutive statements with the same indentation.

trunk

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

branch

Ane of the possible paths of the flow of execution determined past conditional execution.

chained conditional

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

Note

Nosotros will utilise the Python standard of 4 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 flow 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, commonly initialized to zilch and incremented in the body 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 we have an upper bound on the number of times the body will exist executed. Definite iteration is usually best coded as a for loop.

delimiter

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

increment

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

infinite loop

A loop in which the terminating condition is never satisfied.

indefinite iteration

A loop where we just need 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 be until they are assigned values, they are initialized when they are created. In other programming languages this is non the instance, 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 statement or group of statements that execute repeatedly until a terminating status is satisfied.

loop variable

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

nested loop

A loop within the body of another loop.

nesting

One programme structure within another, such as a conditional statement inside a branch of another conditional statement.

newline

A special character that causes the cursor to move to the outset of the next line.

prompt

A visual cue that tells the user to input data.

reassignment

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

tab

A special character that causes the cursor to move to the next tab terminate on the electric current line.

trichotomy

Given any real numbers a and b, exactly one of the following relations holds: a < b, a > b, or a == b. Thus when you lot can institute that two of the relations are simulated, y'all tin assume the remaining i is true.

trace

To follow the flow of execution of a plan by manus, recording the modify of state of the variables and whatever output produced.