Python Assignment In If Statement

Introduction

Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

When we fully execute each statement of a program, moving from the top to the bottom with each line executed in order, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.

Let’s look at some examples where we would use conditional statements:

  • If the student receives over 65% on her test, report that her grade passes; if not, report that her grade fails
  • If he has money in his account, calculate interest; if he doesn’t, charge a penalty fee
  • If they buy 10 oranges or more, calculate a discount of 5%; if they buy fewer, then don’t

Through evaluating conditions and assigning code to run based on whether or not those conditions are met, we are writing conditional code.

This tutorial will take you through writing conditional statements in the Python programming language.

If statement

We will start with the statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

In a plain text editor, open a file and write the following code:

With this code, we have the variable and are giving it the integer value of . We are then using the statement to evaluate whether or not the variable grade is greater than or equal ( ) to . If it does meet this condition, we are telling the program to print out the string.

Save the program as and run it in a local programming environment from a terminal window with the command .

In this case, the grade of 70 does meet the condition of being greater than or equal to 65, so you will receive the following output once you run the program:

Let’s now change the result of this program by changing the value of the variable to :

grade.py

When we save and run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.

To give one more example, let us calculate whether a bank account balance is below 0. Let’s create a file called and write the following program:

account.py

When we run the program with , we’ll receive the following output:

In the program we initialized the variable with the value of , which is less than 0. Since the balance met the condition of the statement (), once we save and run the code, we will receive the string output. Again, if we change the balance to 0 or a positive number, we will receive no output.

Else Statement

It is likely that we will want the program to do something even when an statement evaluates to false. In our grade example, we will want output whether the grade is passing or failing.

To do this, we will add an statement to the grade condition above that is constructed like this:

grade.py

Since the grade variable above has the value of , the statement evaluates as false, so the program will not print out . The statement that follows tells the program to do something anyway.

When we save and run the program, we’ll receive the following output:

If we then rewrite the program to give the grade a value of or higher, we will instead receive the output .

To add an statement to the bank account example, we rewrite the code like this:

account.py

Here, we changed the variable value to a positive number so that the statement will print. To get the first statement to print, we can rewrite the value to a negative number.

By combining an statement with an statement, you are constructing a two-part conditional statement that will tell the computer to execute certain code whether or not the condition is met.

Else if statement

So far, we have presented a Boolean option for conditional statements, with each statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Python as . The or else if statement looks like the statement and will evaluate another condition.

In the bank account program, we may want to have three discrete outputs for three different situations:

  • The balance is below 0
  • The balance is equal to 0
  • The balance is above 0

The statement will be placed between the statement and the statement as follows:

account.py

Now, there are three possible outputs that can occur once we run the program:

  • If the variable is equal to we will receive the output from the statement ()
  • If the variable is set to a positive number, we will receive the output from the statement ().
  • If the variable is set to a negative number, the output will be the string from the statement ().

What if we want to have more than three possibilities, though? We can do this by writing more than one statement into our code.

In the program, let’s rewrite the code so that there are a few letter grades corresponding to ranges of numerical grades:

  • 90 or above is equivalent to an A grade
  • 80-89 is equivalent to a B grade
  • 70-79 is equivalent to a C grade
  • 65-69 is equivalent to a D grade
  • 64 or below is equivalent to an F grade

To run this code, we will need one statement, three statements, and an statement that will handle all failing cases.

Let’s rewrite the code from the example above to have strings that print out each of the letter grades. We can keep our statement the same.

grade.py

Since statements will evaluate in order, we can keep our statements pretty basic. This program is completing the following steps:

  1. If the grade is greater than 90, the program will print , if the grade is less than 90, the program will continue to the next statement...

  2. If the grade is greater than or equal to 80, the program will print , if the grade is 79 or less, the program will continue to the next statement...

  3. If the grade is greater than or equal to 70, the program will print , if the grade is 69 or less, the program will continue to the next statement...

  4. If the grade is greater than or equal to 65, the program will print , if the grade is 64 or less, the program will continue to the next statement...

  5. The program will print because all of the above conditions were not met.

Nested If Statements

Once you are feeling comfortable with the , , and statements, you can move on to nested conditional statements. We can use nested statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested statement:

A few possible outputs can result from this code:

  • If evaluates to true, the program will then evaluate whether the also evaluates to true. If both cases are true, the output will be:
  • If, however, evaluates to true, but evaluates to false, then the output will be:
  • And if evaluates to false, the nested if-else statement will not run, so the statement will run alone, and the output will be:

We can also have multiple statements nested throughout our code:

In the above code, there is a nested statement inside each statement in addition to the statement. This will allow for more options within each condition.

Let’s look at an example of nested statements with our program. We can check for whether a grade is passing first (greater than or equal to 65%), then evaluate which letter grade the numerical grade should be equivalent to. If the grade is not passing, though, we do not need to run through the letter grades, and instead can have the program report that the grade is failing. Our modified code with the nested statement will look like this:

grade.py

If we run the code with the variable set to the integer value , the first condition is met, and the program will print out . Next, it will check to see if the grade is greater than or equal to 90, and since this condition is also met, it will print out .

If we run the code with the variable set to , then the first condition is not met, so the program will skip the nested statements and move down to the statement, with the program printing out .

We can of course add even more options to this, and use a second layer of nested if statements. Perhaps we will want to evaluate for grades of A+, A and A- separately. We can do so by first checking if the grade is passing, then checkingto see if the grade is 90 or above, then checkingto see if the grade is over 96 for an A+ for instance:

grade.py

In the code above, for a variable set to , the program will run the following:

  1. Check if the grade is greater than or equal to 65 (true)
  2. Print out
  3. Check if the grade is greater than or equal to 90 (true)
  4. Check if the grade is greater than 96 (false)
  5. Check if the grade is greater than 93 and also less than or equal to 96 (true)
  6. Print
  7. Leave these nested conditional statements and continue with remaining code

The output of the program for a grade of 96 therefore looks like this:

Nested statements can provide the opportunity to add several specific levels of conditions to your code.

Conclusion

By using conditional statements like the statement, you will have greater control over what your program executes. Conditional statements tell the program to evaluate whether a certain condition is being met. If the condition is met it will execute specific code, but if it is not met the program will continue to move down to other code.

To continue practicing conditional statements, try using different operators, combining operators with or , and using conditional statements alongside loops. You can also go through our tutorial on How To Make a Simple Calculator Program to gain more familiarity with conditional statements.

4. Conditionals and loops¶

4.1. Conditional execution¶

4.1.1. The statement¶

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

A few important things to note about statements:

  1. The colon () is significant and required. It separates the header of the 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 example:

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

Run this example code and see what happens. Then change the value of to something other than and run it again, confirming that you don’t get any output.

Flowchart of an if statement

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

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

Indentation and the PEP 8 Python Style Guide

The Python community has developed a Style Guide for Python Code, usually referred to simply as “PEP 8”. The Python Enhancement Proposals, or PEPs, are part of the process the Python community 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 book.

To help us learn to write well styled Python code, there is a program called pep8 that works as an automatic style guide checker for Python source code. is installable as a package 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 on your source code with the push of a button.

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

4.1.2. The statement¶

It is frequently the case 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 statement.

Here, the first print statement will execute if is equal to , and the print statement indented under the clause will get executed when it is not.

Flowchart of a if else statement

The syntax for an statement looks like this:

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

There is no limit on the number of statements that can appear under the two clauses of an statement, but there has to be at least one statement in each block. Occasionally, it is useful to have a section with no statements (usually as a place keeper, or scaffolding, for code you haven’t written yet). In that case, you can use the statement, which does nothing except act as a placeholder.

Python terminology

Python documentation sometimes uses the term suite of statements to mean what we have called a block here. They mean the same thing, and since most other languages and computer scientists use the word block, we’ll stick with that.

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

iffood=='spam':print('Ummmm, my favorite!')else:print("No, I won't have it. I want spam!")
ifBOOLEANEXPRESSION:STATEMENTS_1# executed if condition evaluates to Trueelse:STATEMENTS_2# executed if condition evaluates to False
ifTrue:# This is always truepass# so this is always executed, but it does nothingelse:pass

4.2. Chained conditionals¶

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

Flowchart of this chained conditional

is an abbreviation of . Again, exactly one branch will be executed. There is no limit of the number of statements but only a single (and optional) final statement is allowed and it must be the last branch in the statement:

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

ifx<y:STATEMENTS_Aelifx>y:STATEMENTS_Belse:STATEMENTS_C
ifchoice=='a':print("You chose 'a'.")elifchoice=='b':print("You chose 'b'.")elifchoice=='c':print("You chose 'c'.")else:print("Invalid choice.")

4.3. Nested conditionals¶

One conditional can also 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 conditional

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

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

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

The function is called only if we make it past both the conditionals, so we can use the operator:

Note

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

if0<x<10:print("x is a positive single digit.")
ifx<y:STATEMENTS_Aelse:ifx>y:STATEMENTS_Belse:STATEMENTS_C
if0<x:# assume x is an int hereifx<10:print("x is a positive single digit.")
if0<xandx<10:print("x is a positive single digit.")

4.4. Iteration¶

Computers are often used to automate repetitive tasks. Repeating identical or similar 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 statement, which we met last chapter, and the statement.

Before we look at those, we 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 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).

The output of this program is

because the first time is printed, its value is 5, and the second time, its value is 7.

Here is what reassignment looks like in a state snapshot:

With reassignment it is especially 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 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 not. For example, if then . But in Python, the statement is legal and is not.

Furthermore, in mathematics, a statement of equality is always true. If now, then will always equal . In Python, an assignment statement can make two variables equal, but because of the possibility of reassignment, they don’t have to stay that way:

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

Note

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 make things a bit confusing for new programmers.

bruce=5print(bruce)bruce=7print(bruce)
a=5b=a# after executing this line, a and b are now equala=3# after executing this line, a and b are no longer equal

4.4.2. Updating variables¶

When an assignment statement is executed, the right-hand-side expression (i.e. the expression that comes after the assignment token) is evaluated first. Then the result of that evaluation is written into the variable on the left hand 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 “get the current value of n, multiply it by three and add one, and put the answer back into n as its new value”. So after executing the two lines above, will have the value 16.

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

Before you can update a variable, you have to initialize it, usually with a simple assignment:

This second statement — updating a variable by adding 1 to it — is very common. It is called an increment of the variable; subtracting 1 is called a decrement.

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

4.5. The loop¶

The loop processes each item 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 body of the loop is executed.

The general form of a loop is:

This is another example of a compound statement in Python, and like the branching statements, it 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 statement runs, so you do not need to create the variable before then. Each iteration assigns the the loop variable to the next element in the sequence, and then 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 it loops back around to the top after each iteration.

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

You should run this example to see what it does.

Tip

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

If you get the results you expected, pat yourself on the back and move 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 think like a computer programmer.

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

forLOOP_VARIABLEinSEQUENCE:STATEMENTS
forfriendin['Margot','Kathryn','Prisila']:invitation="Hi "+friend+". Please come to my party on Saturday!"print(invitation)
>>> foriinrange(5):... print('i is now:',i)...i is now 0i is now 1i is now 2i is now 3i is now 4>>>

4.6. Tables¶

One of the things loops are good for is generating tables. Before computers were readily available, people had to calculate logarithms, sines and cosines, and other mathematical functions by hand. 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 there will 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 use tables of values to get an approximate answer and then perform computations to improve the approximation. In some cases, there have been errors in the underlying tables, most famously in the table the Intel Pentium processor chip used to perform floating-point division.

Although a log table is not as useful as it once was, it still 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:

Using the tab character () makes the output align nicely.

forxinrange(13):# Generate numbers 0 to 12print(x,'\t',2**x)
0 11 22 43 84 165 326 647 1288 2569 51210 102411 204812 4096

4.7. The statement¶

The general syntax for the while statement looks like this:

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

Here is a simple example:

Notice that if is set to on the first line, the body of the statement will not execute at all.

Here is a more elaborate example program demonstrating the use of the statement

The flow of execution for a statement works like this:

  1. Evaluate the condition (), yielding or .
  2. If the condition is false, exit the statement and continue execution at the next statement.
  3. If the condition is true, execute each of the in the body and then go back to step 1.

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 amusement for computer programmers is the observation that the directions on shampoo, lather, rinse, repeat, are an infinite loop.

In the case here, we can prove that the loop terminates because we know that the value of is finite, and we can see that the value of increments each time through the loop, so eventually it will have to equal . In other cases, it is not so easy to tell.

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

whileBOOLEAN_EXPRESSION:STATEMENTS
number=0prompt="What is the meaning of life, the universe, and everything? "whilenumber!="42":number=input(prompt)
name='Harrison'guess=input("So I'm thinking of person's name. Try to guess it: ")pos=0whileguess!=nameandpos<len(name):print("Nope, that's not it! Hint: letter ",end='')print(pos+1,"is",name[pos]+". ",end='')guess=input("Guess again: ")pos=pos+1ifpos==len(name)andname!=guess:print("Too bad, you couldn't get it. The name was",name+".")else:print("\nGreat, you got it in",pos+1,"guesses!")

4.8. Choosing between and ¶

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

Use a loop if you know, before you start looping, the maximum number of times that you’ll need to execute the body. For example, if you’re traversing a list of elements, you know that the maximum number of loop iterations you can possibly need is “all the elements in the list”. Or if you need to print the 12 times table, we know right away how many times the loop will need to run.

So any problem like “iterate this weather model for 1000 cycles”, or “search this list of words”, “find all prime numbers up to 10000” suggest that a loop is best.

By contrast, if you are required to repeat some computation until some condition is met, and you cannot calculate in advance when this will happen, as we did in the “greatest name” program, you’ll need a loop.

We call the first case definite iteration — we have some definite bounds for what is needed. The latter case is called indefinite iteration — we’re not sure how many iterations we’ll need — we cannot even establish an upper bound!

4.9. Tracing a program¶

To write effective 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 program run, recording the state of all variables and any output the program generates after each instruction is executed.

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

At the start of the trace, we have a local variable, with an initial value of . The user will enter a string that is stored in the variable, . Let’s assume they enter . The next line creates a variable named and gives it an intial value of .

To keep 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 look something like this:

Since evaluates to (take a minute to convince yourself of this), the loop body is executed.

The user will now see

Assuming the user enters this time, will be incremented, again evaluates to , and our trace will now look like this:

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

Tracing can be a bit tedious and error prone (that’s why we 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 code works.

name guess pos output---- ----- --- ------'Harrison' 'Maribel' 0
Nope, that's not it! Hint: letter 1 is 'H'. Guess again:
name guess pos output---- ----- --- ------'Harrison' 'Maribel' 0 Nope, that's not it! Hint: letter 1 is 'H'. Guess again:'Harrison' 'Henry' 1 Nope, that's not it! Hint: letter 2 is 'a'. Guess again:
name guess pos output---- ----- --- ------'Harrison' 'Maribel' 0 Nope, that's not it! Hint: letter 1 is 'H'. Guess again:'Harrison' 'Henry' 1 Nope, that's not it! Hint: letter 2 is 'a'. Guess again:'Harrison' 'Hakeem' 2 Nope, that's not it! Hint: letter 3 is 'r'. Guess again:'Harrison' 'Harold' 3 Nope, that's not it! Hint: letter 4 is 'r'. Guess again:'Harrison' 'Harry' 4 Nope, that's not it! Hint: letter 5 is 'i'. Guess again:'Harrison' 'Harrison' 5 Great, you got it in 6 guesses!

4.10. Abbreviated assignment¶

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

is an abreviation for . We pronouce the operator as “plus-equals”. The increment value does not have to be 1:

There are similar abbreviations for , , , and :

>>> count=0>>> count+=1>>> count1>>> count+=1>>> count2
>>> n=2>>> n+=5>>> n7
>>> n=2>>> n \*=5>>> n10>>> n-=4>>> n6>>> n//=2>>> n3>>> n%=2>>> n1

4.11. Another example: Guessing game¶

The following program implements a simple guessing game:

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

importrandom# Import the random module number=random.randrange(1,1000)# Get random number between [1 and 1000)guesses=0guess=int(input("Guess my number between 1 and 1000: "))whileguess!=number:guesses+=1ifguess>number:print(guess,"is too high.")elifguess<number:print(guess," is too low.")guess=int(input("Guess again: "))print("\n\nGreat, you got it in",guesses,"guesses!")

4.12. The statement¶

The break statement is used to immediately leave the body of its loop. The next statement to be executed is the first one after the body:

This prints:

foriin[12,16,17,24,29]:ifi%2==1:# if the number is oddbreak# immediately exit the loopprint(i)print("done")

4.13. The statement¶

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. But the loop still carries on running for its remaining iterations:

This prints:

foriin[12,16,17,24,29,30]:ifi%2==1:# if the number is oddcontinue# don't process itprint(i)print("done")

4.14. Another example¶

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

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

sentence=input('Please enter a sentence: ')no_spaces=''forletterinsentence:ifletter!=' ':no_spaces+=letterprint("You sentence with spaces removed:")print(no_spaces)

4.15. Nested Loops for Nested Data¶

Now we’ll come up with an even more adventurous list of structured data. In this case, 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:

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

Python agreeably responds with the following output:

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:

You should set up a list of your own data that interests you — perhaps a list of your CDs, each containing a list of song titles on the CD, or a list of movie titles, each with a list of movie stars who acted in the movie. You could then ask questions like “Which movies starred Angelina Jolie?”

students=[("Alejandro",["CompSci","Physics"]),("Justin",["Math","CompSci","Stats"]),("Ed",["CompSci","Accounting","Economics"]),("Margot",["InfSys","Accounting","Economics","CommLaw"]),("Peter",["Sociology","Economics","Law","Stats","Music"])]
# print all students with a count of their courses.for(name,subjects)instudents:print(name,"takes",len(subjects),"courses")
Aljandro takes 2 coursesJustin takes 3 coursesEd takes 4 coursesMargot takes 4 coursesPeter takes 5 courses
# Count how many students are taking CompScicounter=0for(name,subjects)instudents:forsinsubjects:# a nested loop!ifs=="CompSci":counter+=1print("The number of students taking CompSci is",counter)
The number of students taking CompSci is 3

4.16. List comprehensions¶

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

The general syntax for a list comprehension expression is:

This list expression has the same effect as:

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

>>> numbers=[1,2,3,4]>>> [x**2forxinnumbers][1, 4, 9, 16]>>> [x**2forxinnumbersifx**2>8][9, 16]>>> [(x,x**2,x**3)forxinnumbers][(1, 1, 1), (2, 4, 8), (3, 9, 27), (4, 16, 64)]>>> files=['bin','Data','Desktop','.bashrc','.ssh','.vimrc']>>> [namefornameinfilesifname[0]!='.']['bin', 'Data', 'Desktop']>>> letters=['a','b','c']>>> [n*letterforninnumbersforletterinletters]['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc', 'aaaa', 'bbbb', 'cccc']>>>
[exprforitem1inseq1foritem2inseq2...foritemxinseqxifcondition]
output_sequence=[]foritem1inseq1:foritem2inseq2:...foritemxinseqx:ifcondition:output_sequence.append(expr)

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.
body
The block of statements in a compound statement that follows the header.
branch
One of the possible paths of the flow of execution determined by conditional execution.
chained conditional
A conditional branch with more than two possible flows of execution. In Python chained conditionals are written with 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 conditional statement that determines which branch is executed.
conditional statement
A statement that controls the flow of execution depending on some condition. In Python the keywords , , and are used for conditional statements.
counter
A variable used to count something, usually initialized to zero and incremented in the body of a loop.
cursor
An invisible marker that keeps track 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 be executed. Definite iteration is usually best coded as a loop.
delimiter
A sequence of one or more characters used to specify the boundary between separate parts of text.
increment
Both as a noun and as a verb, increment means to increase 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 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 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 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 conditional statement inside a branch of another conditional statement.
newline
A special character that causes the cursor to move to the beginning 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 program.
tab
A special character 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 following relations holds: a < b, a > b, or a == b. Thus when you can establish that two of the relations are false, you can assume the remaining one is true.
trace
To follow the flow of execution of a program by hand, recording the change of state of the variables and any output produced.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *