id
int64
0
25.6k
text
stringlengths
0
4.59k
2,500
begins and endsthey are not part of the string value note you can also use this function to put blank line on the screenjust call print(with nothing in between the parentheses when you write function namethe opening and closing parentheses at the end identify it as the name of function this is why in this bookyou'll see print(rather than print describes functions in more detail the input(function the input(function waits for the user to type some text on the keyboard and press enter myname input(this function call evaluates to string equal to the user' textand the line of code assigns the myname variable to this string value you can think of the input(function call as an expression that evaluates to whatever string the user typed in if the user entered 'al'then the expression would evaluate to myname 'alif you call input(and see an error messagelike nameerrorname 'alis not definedthe problem is that you're running the code with python instead of python printing the user' name the following call to print(actually contains the expression 'it is good to meet youmyname between the parentheses print('it is good to meet youmynameremember that expressions can always evaluate to single value if 'alis the value stored in myname on line then this expression evaluates to 'it is good to meet youalthis single string value is then passed to print()which prints it on the screen the len(function you can pass the len(function string value (or variable containing string)and the function evaluates to the integer value of the number of characters in that string print('the length of your name is:'print(len(myname)
2,501
len('hello' len('my very energetic monster just scarfed nachos ' len('' just like those exampleslen(mynameevaluates to an integer it is then passed to print(to be displayed on the screen the print(function allows you to pass it either integer values or string valuesbut notice the error that shows up when you type the following into the interactive shellprint(' am years old 'traceback (most recent call last)file ""line in print(' am years old 'typeerrorcan only concatenate str (not "int"to str the print(function isn' causing that errorbut rather it' the expression you tried to pass to print(you get the same error message if you type the expression into the interactive shell on its own ' am years old traceback (most recent call last)file ""line in ' am years old typeerrorcan only concatenate str (not "int"to str python gives an error because the operator can only be used to add two integers together or concatenate two strings you can' add an integer to stringbecause this is ungrammatical in python you can fix this by using string version of the integer insteadas explained in the next section the str()int()and float(functions if you want to concatenate an integer such as with string to pass to print()you'll need to get the value ' 'which is the string form of the str(function can be passed an integer value and will evaluate to string value version of the integeras followsstr( ' print(' am str( years old ' am years old python basics
2,502
years old evaluates to ' am ' years old 'which in turn evaluates to ' am years old this is the value that is passed to the print(function the str()int()and float(functions will evaluate to the stringintegerand floating-point forms of the value you passrespectively try converting some values in the interactive shell with these functions and watch what happens str( ' str(- '- int(' ' int('- '- int( int( float(' ' float( the previous examples call the str()int()and float(functions and pass them values of the other data types to obtain stringintegeror floating-point form of those values the str(function is handy when you have an integer or float that you want to concatenate to string the int(function is also helpful if you have number as string value that you want to use in some mathematics for examplethe input(function always returns stringeven if the user enters number enter spam input(into the interactive shell and enter when it waits for your text spam input( spam ' the value stored inside spam isn' the integer but the string ' if you want to do math using the value in spamuse the int(function to get the integer form of spam and then store this as the new value in spam spam int(spamspam now you should be able to treat the spam variable as an integer instead of string
2,503
note that if you pass value to int(that it cannot evaluate as an integerpython will display an error message int(' 'traceback (most recent call last)file ""line in int(' 'valueerrorinvalid literal for int(with base ' int('twelve'traceback (most recent call last)file ""line in int('twelve'valueerrorinvalid literal for int(with base 'twelvethe int(function is also useful if you need to round floating-point number down int( int( you used the int(and str(functions in the last three lines of your program to get value of the appropriate data type for the code print('what is your age?'ask for their age myage input(print('you will be str(int(myage in year 'te nd numbe equi va le nce although the string value of number is considered completely different value from the integer or floating-point versionan integer can be equal to floating point =' false = true = true python makes this distinction because strings are textwhile integers and floats are both numbers python basics
2,504
input(function always returns string (even if the user typed in number)you can use the int(myagecode to return an integer value of the string in myage this integer value is then added to in the expression int(myage the result of this addition is passed to the str(functionstr(int(myage the string value returned is then concatenated with the strings 'you will be and in year to evaluate to one large string value this large string is finally passed to print(to be displayed on the screen let' say the user enters the string ' for myage the string ' is converted to an integerso you can add one to it the result is the str(function converts the result back to stringso you can concatenate it with the second string'in year 'to create the final message these evaluation steps would look something like the followingprint('you will be str(int(myage in year 'print('you will be str(int' in year 'print('you will be str in year 'print('you will be str in year '' in year 'print('you will be print('you will be in year 'print('you will be in year 'summary you can compute expressions with calculator or enter string concatenations with word processor you can even do string replication easily by copying and pasting text but expressionsand their component values-operatorsvariablesand function calls--are the basic building blocks that make programs once you know how to handle these elementsyou will be able to instruct python to operate on large amounts of data for you it is good to remember the different types of operators (+-*///%and *for math operationsand and for string operationsand the three data types (integersfloating-point numbersand stringsintroduced in this introduced few different functions as well the print(and input(functions handle simple text output (to the screenand input (from the keyboardthe len(function takes string and evaluates to an int of the number of characters in the string the str()int()and float(functions will evaluate to the stringintegeror floating-point number form of the value they are passed
2,505
to repeat based on the values it has this is known as flow controland it allows you to write programs that make intelligent decisions practice questions which of the following are operatorsand which are values'hello- which of the following is variableand which is stringspam 'spam name three data types what is an expression made up ofwhat do all expressions dothis introduced assignment statementslike spam what is the difference between an expression and statementwhat does the variable bacon contain after the following code runsbacon bacon what should the following two expressions evaluate to'spam'spamspam'spam why is eggs valid variable name while is invalidwhat three functions can be used to get the integerfloating-point numberor string version of valuepython basics
2,506
' have eaten burritos extra creditsearch online for the python documentation for the len(function it will be on web page titled "built-in functions skim the list of other functions python haslook up what the round(function doesand experiment with it in the interactive shell
2,507
flow control soyou know the basics of individual instructions and that program is just series of instructions but programming' real strength isn' just running one instruction after another like weekend errand list based on how expressions evaluatea program can decide to skip instructionsrepeat themor choose one of several instructions to run in factyou almost never want your programs to start from the first line of code and simply execute every linestraight to the end flow control statements can decide which python instructions to execute under which conditions these flow control statements directly correspond to the symbols in flowchartso 'll provide flowchart versions of the code discussed in this figure - shows flowchart for what to do if it' raining follow the path made by the arrows from start to end
2,508
is rainingno go outside yes have umbrellano wait while yes no is rainingyes end figure - flowchart to tell you what to do if it is raining in flowchartthere is usually more than one way to go from the start to the end the same is true for lines of code in computer program flowcharts represent these branching points with diamondswhile the other steps are represented with rectangles the starting and ending steps are represented with rounded rectangles but before you learn about flow control statementsyou first need to learn how to represent those yes and no optionsand you need to understand how to write those branching points as python code to that endlet' explore boolean valuescomparison operatorsand boolean operators boolean values while the integerfloating-pointand string data types have an unlimited number of possible valuesthe boolean data type has only two valuestrue and false (boolean is capitalized because the data type is named after mathematician george boole when entered as python codethe boolean values true and false lack the quotes you place around stringsand they always start with capital or fwith the rest of the word in lowercase enter the following into the interactive shell (some of these instructions are intentionally incorrectand they'll cause error messages to appear
2,509
spam true true traceback (most recent call last)file ""line in true nameerrorname 'trueis not defined true syntaxerrorcan' assign to keyword like any other valueboolean values are used in expressions and can be stored in variables if you don' use the proper case or you try to use true and false for variable names python will give you an error message comparison operators comparison operatorsalso called relational operatorscompare two values and evaluate down to single boolean value table - lists the comparison operators table - comparison operators operator meaning =equal to !not equal to less than greater than <less than or equal to >greater than or equal to these operators evaluate to true or false depending on the values you give them let' try some operators nowstarting with =and ! = true = false ! true ! false as you might expect=(equal toevaluates to true when the values on both sides are the sameand !(not equal toevaluates to true when the two values are different the =and !operators can actually work with values of any data type flow control
2,510
true 'hello='hellofalse 'dog!'cattrue true =true true true !false true = true =' false note that an integer or floating-point value will always be unequal to string value the expression =' evaluates to false because python considers the integer to be different from the string ' the operatorson the other handwork properly only with integer and floating-point values true false false eggcount eggcount < true myage myage > true the diffe re nce be the = nd ope ators you might have noticed that the =operator (equal tohas two equal signswhile the operator (assignmenthas just one equal sign it' easy to confuse these two operators with each other just remember these pointsthe =operator (equal toasks whether two values are the same as each other the operator (assignmentputs the value on the right into the variable on the left to help remember which is whichnotice that the =operator (equal toconsists of two charactersjust like the !operator (not equal toconsists of two characters
2,511
some other valuelike in the eggcount examples (after allinstead of entering 'dog!'catin your codeyou could have just entered true you'll see more examples of this later when you learn about flow control statements boolean operators the three boolean operators (andorand notare used to compare boolean values like comparison operatorsthey evaluate these expressions down to boolean value let' explore these operators in detailstarting with the and operator binary boolean operators the and and or operators always take two boolean values (or expressions)so they're considered binary operators the and operator evaluates an expression to true if both boolean values are trueotherwiseit evaluates to false enter some expressions using and into the interactive shell to see it in action true and true true true and false false truth table shows every possible result of boolean operator table - is the truth table for the and operator table - the and operator' truth table expression evaluates to true and true true true and false false false and true false false and false false on the other handthe or operator evaluates an expression to true if either of the two boolean values is true if both are falseit evaluates to false false or true true false or false false you can see every possible outcome of the or operator in its truth tableshown in table - flow control
2,512
expression evaluates to true or true true true or false true false or true true false or false false the not operator unlike and and orthe not operator operates on only one boolean value (or expressionthis makes it unary operator the not operator simply evaluates to the opposite boolean value not true false not not not not true true much like using double negatives in speech and writingyou can nest not operators though there' never not no reason to do this in real programs table - shows the truth table for not table - the not operator' truth table expression evaluates to not true false not false true mixing boolean and comparison operators since the comparison operators evaluate to boolean valuesyou can use them in expressions with the boolean operators recall that the andorand not operators are called boolean operators because they always operate on the boolean values true and false while expressions like aren' boolean valuesthey are expressions that evaluate down to boolean values try entering some boolean expressions that use comparison operators into the interactive shell ( and ( true ( and ( false ( = or ( = true the computer will evaluate the left expression firstand then it will evaluate the right expression when it knows the boolean value for each
2,513
you can think of the computer' evaluation process for ( and ( as the following( and ( true and ( true and true true you can also use multiple boolean operators in an expressionalong with the comparison operators = and not = and = true the boolean operators have an order of operations just like the math operators do after any math and comparison operators evaluatepython evaluates the not operators firstthen the and operatorsand then the or operators elements of flow control flow control statements often start with part called the condition and are always followed by block of code called the clause before you learn about python' specific flow control statementsi'll cover what condition and block are conditions the boolean expressions you've seen so far could all be considered conditionswhich are the same thing as expressionscondition is just more specific name in the context of flow control statements conditions always evaluate down to boolean valuetrue or false flow control statement decides what to do based on whether its condition is true or falseand almost every flow control statement uses condition blocks of code lines of python code can be grouped together in blocks you can tell when block begins and ends from the indentation of the lines of code there are three rules for blocks blocks begin when the indentation increases blocks can contain other blocks blocks end when the indentation decreases to zero or to containing block' indentation flow control
2,514
let' find the blocks in part of small game programshown herename 'marypassword 'swordfishif name ='mary'print('hellomary'if password ='swordfish'print('access granted 'elseprint('wrong password 'you can view the execution of this program at the first block of code starts at the line print('hellomary'and contains all the lines after it inside this block is another block which has only single line in itprint('access granted 'the third block is also one line longprint('wrong password 'program execution in the previous hello py programpython started executing instructions at the top of the program going downone after another the program execution (or simplyexecutionis term for the current instruction being executed if you print the source code on paper and put your finger on each line as it is executedyou can think of your finger as the program execution not all programs execute by simply going straight downhowever if you use your finger to trace through program with flow control statementsyou'll likely find yourself jumping around the source code based on conditionsand you'll probably skip entire clauses flow control statements nowlet' explore the most important piece of flow controlthe statements themselves the statements represent the diamonds you saw in the flowchart in figure - and they are the actual decisions your programs will make if statements the most common type of flow control statement is the if statement an if statement' clause (that isthe block following the if statementwill execute if the statement' condition is true the clause is skipped if the condition is false in plain englishan if statement could be read as"if this condition is trueexecute the code in the clause in pythonan if statement consists of the following the if keyword condition (that isan expression that evaluates to true or false
2,515
colon starting on the next linean indented block of code (called the if clausefor examplelet' say you have some code that checks to see whether someone' name is alice (pretend name was assigned some value earlier if name ='alice'print('hialice 'all flow control statements end with colon and are followed by new block of code (the clausethis if statement' clause is the block with print('hialice 'figure - shows what flowchart of this code would look like start name ='alicetrue print('hialice 'false end figure - the flowchart for an if statement else statements an if clause can optionally be followed by an else statement the else clause is executed only when the if statement' condition is false in plain englishan else statement could be read as"if this condition is trueexecute this code or elseexecute that code an else statement doesn' have conditionand in codean else statement always consists of the followingthe else keyword colon starting on the next linean indented block of code (called the else clauseflow control
2,516
else statement to offer different greeting if the person' name isn' alice if name ='alice'print('hialice 'elseprint('hellostranger 'figure - shows what flowchart of this code would look like start name ='alicetrue print('hialice 'false print('hellostranger 'end figure - the flowchart for an else statement elif statements while only one of the if or else clauses will executeyou may have case where you want one of many possible clauses to execute the elif statement is an "else ifstatement that always follows an if or another elif statement it provides another condition that is checked only if all of the previous conditions were false in codean elif statement always consists of the followingthe elif keyword condition (that isan expression that evaluates to true or falsea colon starting on the next linean indented block of code (called the elif clauselet' add an elif to the name checker to see this statement in action if name ='alice'print('hialice '
2,517
print('you are not alicekiddo 'this timeyou check the person' ageand the program will tell them something different if they're younger than you can see the flowchart for this in figure - start name ='alicetrue print('hialice 'true print('you are not alicekiddo 'false age false end figure - the flowchart for an elif statement the elif clause executes if age is true and name ='aliceis false howeverif both of the conditions are falsethen both of the clauses are skipped it is not guaranteed that at least one of the clauses will be executed when there is chain of elif statementsonly one or none of the clauses will be executed once one of the statementsconditions is found to be truethe rest of the elif clauses are automatically skipped for exampleopen new file editor window and enter the following codesaving it as vampire pyname 'carolage if name ='alice'print('hialice 'elif age print('you are not alicekiddo 'elif age flow control
2,518
elif age print('you are not alicegrannie 'you can view the execution of this program at herei've added two more elif statements to make the name checker greet person with different answers based on age figure - shows the flowchart for this start name ='alicetrue print('hialice 'true print('you are not alicekiddo 'true print('unlike youalice is not an undeadimmortal vampire 'true print('you are not alicegrannie 'false age false age false age false end figure - the flowchart for multiple elif statements in the vampire py program
2,519
them to introduce bug remember that the rest of the elif clauses are automatically skipped once true condition has been foundso if you swap around some of the clauses in vampire pyyou run into problem change the code to look like the followingand save it as vampire pyname 'carolage if name ='alice'print('hialice 'elif age print('you are not alicekiddo 'elif age print('you are not alicegrannie 'elif age print('unlike youalice is not an undeadimmortal vampire 'you can view the execution of this program at say the age variable contains the value before this code is executed you might expect the code to print the string 'unlike youalice is not an undeadimmortal vampire howeverbecause the age condition is true (after all , is greater than the string 'you are not alicegrannie is printedand the rest of the elif statements are automatically skipped remember that at most only one of the clauses will be executedand for elif statementsthe order mattersfigure - shows the flowchart for the previous code notice how the diamonds for age and age are swapped optionallyyou can have an else statement after the last elif statement in that caseit is guaranteed that at least one (and only oneof the clauses will be executed if the conditions in every if and elif statement are falsethen the else clause is executed for examplelet' re-create the alice program to use ifelifand else clauses name 'carolage if name ='alice'print('hialice 'elif age print('you are not alicekiddo 'elseprint('you are neither alice nor little kid 'you can view the execution of this program at /littlekidfigure - shows the flowchart for this new codewhich we'll save as littlekid py in plain englishthis type of flow control structure would be "if the first condition is truedo this elseif the second condition is truedo that otherwisedo something else when you use ifelifand else statements togetherremember these rules about how to order them to avoid bugs like the one in figure - firstthere is always exactly one if statement any flow control
2,520
to be sure that at least one clause is executedclose the structure with an else statement start name ='alicetrue print('hialice 'true print('you are not alicekiddo 'true print('you are not alicegrannie ' print('unlike youalice is not an undeadimmortal vampire 'false age false age false age true false end figure - the flowchart for the vampire py program the path will logically never happenbecause if age were greater than it would have already been greater than
2,521
name ='alicetrue print('hialice 'true print('you are not alicekiddo 'false age false print('you are neither alice nor little kid 'end figure - flowchart for the previous littlekid py program while loop statements you can make block of code execute over and over again using while statement the code in while clause will be executed as long as the while statement' condition is true in codea while statement always consists of the followingthe while keyword condition (that isan expression that evaluates to true or falsea colon starting on the next linean indented block of code (called the while clauseflow control
2,522
difference is in how they behave at the end of an if clausethe program execution continues after the if statement but at the end of while clausethe program execution jumps back to the start of the while statement the while clause is often called the while loop or just the loop let' look at an if statement and while loop that use the same condition and take the same actions based on that condition here is the code with an if statementspam if spam print('helloworld 'spam spam here is the code with while statementspam while spam print('helloworld 'spam spam these statements are similar--both if and while check the value of spamand if it' less than they print message but when you run these two code snippetssomething very different happens for each one for the if statementthe output is simply "helloworld but for the while statementit' "helloworld repeated five timestake look at the flowcharts for these two pieces of codefigures - and - to see why this happens start true spam print('helloworld 'spam spam false end figure - the flowchart for the if statement code
2,523
true spam print('helloworld 'spam spam false end figure - the flowchart for the while statement code the code with the if statement checks the conditionand it prints helloworld only once if that condition is true the code with the while loopon the other handwill print it five times the loop stops after five prints because the integer in spam increases by one at the end of each loop iterationwhich means that the loop will execute five times before spam is false in the while loopthe condition is always checked at the start of each iteration (that iseach time the loop is executedif the condition is truethen the clause is executedand afterwardthe condition is checked again the first time the condition is found to be falsethe while clause is skipped an annoying while loop here' small example program that will keep asking you to typeliterallyyour name select file new to open new file editor windowenter the following codeand save the file as yourname pyname 'while name !'your name'print('please type your name 'name input(print('thank you!'you can view the execution of this program at firstthe program sets the name variable to an empty string this is so flow control
2,524
execution will enter the while loop' clause the code inside this clause asks the user to type their namewhich is assigned to the name variable since this is the last line of the blockthe execution moves back to the start of the while loop and reevaluates the condition if the value in name is not equal to the string 'your name'then the condition is trueand the execution enters the while clause again but once the user types your namethe condition of the while loop will be 'your name!'your name'which evaluates to false the condition is now falseand instead of the program execution reentering the while loop' clausepython skips past it and continues running the rest of the program figure - shows flowchart for the yourname py program start true name !'your nameprint('please type your name 'false name input(print('thank you!'end figure - flowchart of the yourname py program nowlet' see yourname py in action press to run itand enter something other than your name few times before you give the program what it wants please type your name al please type your name albert please type your name %#@#%*(^&!!
2,525
your name thank youif you never enter your namethen the while loop' condition will never be falseand the program will just keep asking forever herethe input(call lets the user enter the right string to make the program move on in other programsthe condition might never actually changeand that can be problem let' look at how you can break out of while loop break statements there is shortcut to getting the program execution to break out of while loop' clause early if the execution reaches break statementit immediately exits the while loop' clause in codea break statement simply contains the break keyword pretty simplerighthere' program that does the same thing as the previous programbut it uses break statement to escape the loop enter the following codeand save the file as yourname pywhile trueprint('please type your name 'name input(if name ='your name'break print('thank you!'you can view the execution of this program at yourname the first line creates an infinite loopit is while loop whose condition is always true (the expression trueafter allalways evaluates down to the value true after the program execution enters this loopit will exit the loop only when break statement is executed (an infinite loop that never exits is common programming bug just like beforethis program asks the user to enter your name nowhoweverwhile the execution is still inside the while loopan if statement checks whether name is equal to 'your nameif this condition is truethe break statement is run and the execution moves out of the loop to print('thank you!'otherwisethe if statement' clause that contains the break statement is skippedwhich puts the execution at the end of the while loop at this pointthe program execution jumps back to the start of the while statement to recheck the condition since this condition is merely the true boolean valuethe execution enters the loop to ask the user to type your name again see figure - for this program' flowchart run yourname pyand enter the same text you entered for yourname py the rewritten program should respond in the same way as the original flow control
2,526
true true print('please type your name 'name input( false name ='your nametrue break false print('thank you!'end figure - the flowchart for the yourname py program with an infinite loop note that the path will logically never happenbecause the loop condition is always true continue statements like break statementscontinue statements are used inside loops when the program execution reaches continue statementthe program execution immediately jumps back to the start of the loop and reevaluates the loop' condition (this is also what happens when the execution reaches the end of the loop let' use continue to write program that asks for name and password enter the following code into new file editor window and save the program as swordfish py
2,527
if you ever run program that has bug causing it to get stuck in an infinite looppress ctrl- or select shell restart shell from idle' menu this will send keyboardinterrupt error to your program and cause it to stop immediately try stopping program by creating simple infinite loop in the file editorand save the program as infiniteloop py while trueprint('helloworld!'when you run this programit will print helloworldto the screen forever because the while statement' condition is always true ctrl- is also handy if you want to simply terminate your program immediatelyeven if it' not stuck in an infinite loop while trueprint('who are you?'name input(if name !'joe'continue print('hellojoe what is the password(it is fish )'password input(if password ='swordfish'break print('access granted 'if the user enters any name besides joe the continue statement causes the program execution to jump back to the start of the loop when the program reevaluates the conditionthe execution will always enter the loopsince the condition is simply the value true once the user makes it past that if statementthey are asked for password if the password entered is swordfishthen the break statement is runand the execution jumps out of the while loop to print access granted otherwisethe execution continues to the end of the while loopwhere it then jumps back to the start of the loop see figure - for this program' flowchart flow control
2,528
true true print('who are you?'name input( false true continue name !'joefalse print('hellojoe what is the password(it is fish )'password input(false break password ='swordfishtrue print('access granted 'end figure - flowchart for swordfish py the path will logically never happenbecause the loop condition is always true
2,529
conditions will consider some values in other data types equivalent to true and false when used in conditions and '(the empty stringare considered falsewhile all other values are considered true for examplelook at the following programname 'while not nameprint('enter your name:'name input(print('how many guests will you have?'numofguests int(input()if numofguestsprint('be sure to have enough room for all your guests 'print('done'you can view the execution of this program at /howmanyguestsif the user enters blank string for namethen the while statement' condition will be true and the program continues to ask for name if the value for numofguests is not then the condition is considered to be trueand the program will print reminder for the user you could have entered not name !'instead of not nameand numofguests ! instead of numofguestsbut using the truthy and falsey values can make your code easier to read run this program and give it some input until you claim to be joethe program shouldn' ask for passwordand once you enter the correct passwordit should exit who are youi' finethanks who are youwho are youjoe hellojoe what is the password(it is fish mary who are youjoe hellojoe what is the password(it is fish swordfish access granted you can view the execution of this program at flow control
2,530
the while loop keeps looping while its condition is true (which is the reason for its name)but what if you want to execute block of code only certain number of timesyou can do this with for loop statement and the range(function in codea for statement looks something like for in range( )and includes the followingthe for keyword variable name the in keyword call to the range(method with up to three integers passed to it colon starting on the next linean indented block of code (called the for clauselet' create new program called fivetimes py to help you see for loop in action print('my name is'for in range( )print('jimmy five times (str( ')'you can view the execution of this program at the code in the for loop' clause is run five times the first time it is runthe variable is set to the print(call in the clause will print jimmy five times ( after python finishes an iteration through all the code inside the for loop' clausethe execution goes back to the top of the loopand the for statement increments by one this is why range( results in five iterations through the clausewith being set to then then then and then the variable will go up tobut will not includethe integer passed to range(figure - shows flowchart for the fivetimes py program when you run this programit should print jimmy five times followed by the value of five times before leaving the for loop my name is jimmy five times ( jimmy five times ( jimmy five times ( jimmy five times ( jimmy five times ( note you can use break and continue statements inside for loops as well the continue statement will continue to the next value of the for loop' counteras if the program execution had reached the end of the loop and returned to the start in factyou can use continue and break statements only inside while and for loops if you try to use these statements elsewherepython will give you an error
2,531
print('my name is'looping for in range ( print('jimmy five times (str( ')'done looping end figure - the flowchart for fivetimes py as another for loop exampleconsider this story about the mathematician carl friedrich gauss when gauss was boya teacher wanted to give the class some busywork the teacher told them to add up all the numbers from to young gauss came up with clever trick to figure out the answer in few secondsbut you can write python program with for loop to do this calculation for you total for num in range( )total total num print(totalthe result should be , when the program first startsthe total variable is set to the for loop then executes total total num times by the time the loop has finished all of its iterationsevery integer from to will have been added to total at this pointtotal is printed to the screen even on the slowest computersthis program takes less than second to complete (young gauss figured out way to solve the problem in seconds there are pairs of numbers that add up to and so onuntil since is , the sum of all the numbers from to is , clever kid!flow control
2,532
you can actually use while loop to do the same thing as for loopfor loops are just more concise let' rewrite fivetimes py to use while loop equivalent of for loop print('my name is' while print('jimmy five times (str( ')' you can view the execution of this program at /fivetimeswhileif you run this programthe output should look the same as the fivetimes py programwhich uses for loop the startingstoppingand stepping arguments to range(some functions can be called with multiple arguments separated by commaand range(is one of them this lets you change the integer passed to range(to follow any sequence of integersincluding starting at number other than zero for in range( )print(ithe first argument will be where the for loop' variable startsand the second argument will be up tobut not includingthe number to stop at the range(function can also be called with three arguments the first two arguments will be the start and stop valuesand the third will be the step argument the step is the amount that the variable is increased by after each iteration for in range( )print(iso calling range( will count from zero to eight by intervals of two
2,533
for for loops for example ( never apologize for my puns)you can even use negative number for the step argument to make the for loop count down instead of up for in range( - - )print(ithis for loop would have the following output running for loop to print with range( - - should print from five down to zero importing modules all python programs can call basic set of functions called built-in functionsincluding the print()input()and len(functions you've seen before python also comes with set of modules called the standard library each module is python program that contains related group of functions that can be embedded in your programs for examplethe math module has mathematicsrelated functionsthe random module has random number-related functionsand so on before you can use the functions in moduleyou must import the module with an import statement in codean import statement consists of the followingthe import keyword the name of the module optionallymore module namesas long as they are separated by commas once you import moduleyou can use all the cool functions of that module let' give it try with the random modulewhich will give us access to the random randint(function enter this code into the file editorand save it as printrandom pyimport random for in range( )print(random randint( )flow control
2,534
when you save your python scriptstake care not to give them name that is used by one of python' modulessuch as random pysys pyos pyor math py if you accidentally name one of your programssayrandom pyand use an import random statement in another programyour program would import your random py file instead of python' random module this can lead to errors such as attributeerrormodule 'randomhas no attribute 'randint'since your random py doesn' have the functions that the real random module has don' use the names of any built-in python functions eithersuch as print(or input(problems like these are uncommonbut can be tricky to solve as you gain more programming experienceyou'll become more aware of the standard names used by python' modules and functionsand will run into these problems less frequently when you run this programthe output will look something like this you can view the execution of this program at printrandomthe random randint(function call evaluates to random integer value between the two integers that you pass it since randint(is in the random moduleyou must first type random in front of the function name to tell python to look for this function inside the random module here' an example of an import statement that imports four different modulesimport randomsysosmath now we can use any of the functions in these four modules we'll learn more about them later in the book from import statements an alternative form of the import statement is composed of the from keywordfollowed by the module namethe import keywordand starfor examplefrom random import with this form of import statementcalls to functions in random will not need the random prefix howeverusing the full name makes for more readable codeso it is better to use the import random form of the statement
2,535
the last flow control concept to cover is how to terminate the program programs always terminate if the program execution reaches the bottom of the instructions howeveryou can cause the program to terminateor exitbefore the last instruction by calling the sys exit(function since this function is in the sys moduleyou have to import sys before your program can use it open file editor window and enter the following codesaving it as exitexample pyimport sys while trueprint('type exit to exit 'response input(if response ='exit'sys exit(print('you typed response 'run this program in idle this program has an infinite loop with no break statement inside the only way this program will end is if the execution reaches the sys exit(call when response is equal to exitthe line containing the sys exit(call is executed since the response variable is set by the input(functionthe user must enter exit in order to stop the program short programguess the number the examples 've shown you so far are useful for introducing basic conceptsbut now let' see how everything you've learned comes together in more complete program in this sectioni'll show you simple "guess the numbergame when you run this programthe output will look something like thisi am thinking of number between and take guess your guess is too low take guess your guess is too low take guess your guess is too high take guess good jobyou guessed my number in guessesflow control
2,536
guessthenumber pythis is guess the number game import random secretnumber random randint( print(' am thinking of number between and 'ask the player to guess times for guessestaken in range( )print('take guess 'guess int(input()if guess secretnumberprint('your guess is too low 'elif guess secretnumberprint('your guess is too high 'elsebreak this condition is the correct guessif guess =secretnumberprint('good jobyou guessed my number in str(guessestakenguesses!'elseprint('nope the number was thinking of was str(secretnumber)you can view the execution of this program at /guessthenumberlet' look at this code line by linestarting at the top this is guess the number game import random secretnumber random randint( firsta comment at the top of the code explains what the program does thenthe program imports the random module so that it can use the random randint(function to generate number for the user to guess the return valuea random integer between and is stored in the variable secretnumber print(' am thinking of number between and 'ask the player to guess times for guessestaken in range( )print('take guess 'guess int(input()the program tells the player that it has come up with secret number and will give the player six chances to guess it the code that lets the player enter guess and checks that guess is in for loop that will loop at most six times the first thing that happens in the loop is that the player types in guess since input(returns stringits return value is passed straight into
2,537
variable named guess if guess secretnumberprint('your guess is too low 'elif guess secretnumberprint('your guess is too high 'these few lines of code check to see whether the guess is less than or greater than the secret number in either casea hint is printed to the screen elsebreak this condition is the correct guessif the guess is neither higher nor lower than the secret numberthen it must be equal to the secret number--in which caseyou want the program execution to break out of the for loop if guess =secretnumberprint('good jobyou guessed my number in str(guessestakenguesses!'elseprint('nope the number was thinking of was str(secretnumber)after the for loopthe previous if else statement checks whether the player has correctly guessed the number and then prints an appropriate message to the screen in both casesthe program displays variable that contains an integer value (guessestaken and secretnumbersince it must concatenate these integer values to stringsit passes these variables to the str(functionwhich returns the string value form of these integers now these strings can be concatenated with the operators before finally being passed to the print(function call short programrockpaperscissors let' use the programming concepts we've learned so far to create simple rockpaperscissors game the output will look like thisrockpaperscissors wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit paper versus paper it is tie wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit scissors versus paper you winflow control
2,538
enter your move( )ock ( )aper ( )cissors or ( )uit type the following source code into the file editorand save the file as rpsgame pyimport randomsys print('rockpaperscissors'these variables keep track of the number of winslossesand ties wins losses ties while truethe main game loop print('% wins% losses% ties(winslossesties)while truethe player input loop print('enter your move( )ock ( )aper ( )cissors or ( )uit'playermove input(if playermove =' 'sys exit(quit the program if playermove ='ror playermove ='por playermove =' 'break break out of the player input loop print('type one of rpsor 'display what the player choseif playermove =' 'print('rock versus 'elif playermove =' 'print('paper versus 'elif playermove =' 'print('scissors versus 'display what the computer choserandomnumber random randint( if randomnumber = computermove 'rprint('rock'elif randomnumber = computermove 'pprint('paper'elif randomnumber = computermove 'sprint('scissors'display and record the win/loss/tieif playermove =computermoveprint('it is tie!'ties ties elif playermove ='rand computermove =' 'print('you win!'wins wins
2,539
print('you win!'wins wins elif playermove ='sand computermove =' 'print('you win!'wins wins elif playermove ='rand computermove =' 'print('you lose!'losses losses elif playermove ='pand computermove =' 'print('you lose!'losses losses elif playermove ='sand computermove =' 'print('you lose!'losses losses let' look at this code line by linestarting at the top import randomsys print('rockpaperscissors'these variables keep track of the number of winslossesand ties wins losses ties firstwe import the random and sys module so that our program can call the random randint(and sys exit(functions we also set up three variables to keep track of how many winslossesand ties the player has had while truethe main game loop print('% wins% losses% ties(winslossesties)while truethe player input loop print('enter your move( )ock ( )aper ( )cissors or ( )uit'playermove input(if playermove =' 'sys exit(quit the program if playermove ='ror playermove ='por playermove =' 'break break out of the player input loop print('type one of rpsor 'this program uses while loop inside of another while loop the first loop is the main game loopand single game of rockpaperscissors is player on each iteration through this loop the second loop asks for input from the playerand keeps looping until the player has entered an rpsor for their move the rpand correspond to rockpaperand scissorsrespectivelywhile the means the player intends to quit in that casesys exit(is called and the program exits if the player has entered rpor sthe execution breaks out of the loop otherwisethe program reminds the player to enter rpsor and goes back to the start of the loop flow control
2,540
if playermove =' 'print('rock versus 'elif playermove =' 'print('paper versus 'elif playermove =' 'print('scissors versus 'the player' move is displayed on the screen display what the computer choserandomnumber random randint( if randomnumber = computermove 'rprint('rock'elif randomnumber = computermove 'pprint('paper'elif randomnumber = computermove 'sprint('scissors'nextthe computer' move is randomly selected since random randint(can only return random numberthe or integer value it returns is stored in variable named randomnumber the program stores ' '' 'or 'sstring in computermove based on the integer in randomnumberas well as displays the computer' move display and record the win/loss/tieif playermove =computermoveprint('it is tie!'ties ties elif playermove ='rand computermove =' 'print('you win!'wins wins elif playermove ='pand computermove =' 'print('you win!'wins wins elif playermove ='sand computermove =' 'print('you win!'wins wins elif playermove ='rand computermove =' 'print('you lose!'losses losses elif playermove ='pand computermove =' 'print('you lose!'losses losses elif playermove ='sand computermove =' 'print('you lose!'losses losses
2,541
and displays the results on the screen it also increments the winslossesor ties variable appropriately once the execution reaches the endit jumps back to the start of the main program loop to begin another game summary by using expressions that evaluate to true or false (also called conditions)you can write programs that make decisions on what code to execute and what code to skip you can also execute code over and over again in loop while certain condition evaluates to true the break and continue statements are useful if you need to exit loop or jump back to the loop' start these flow control statements will let you write more intelligent programs you can also use another type of flow control by writing your own functionswhich is the topic of the next practice questions what are the two values of the boolean data typehow do you write themwhat are the three boolean operatorswrite out the truth tables of each boolean operator (that isevery possible combination of boolean values for the operator and what they evaluate towhat do the following expressions evaluate to( and ( = not ( ( or ( = not (( or ( = )(true and trueand (true =false(not falseor (not true what are the six comparison operatorswhat is the difference between the equal to operator and the assignment operatorexplain what condition is and where you would use one identify the three blocks in this codespam if spam = print('eggs'if spam print('bacon'flow control
2,542
print('ham'print('spam'print('spam' write code that prints hello if is stored in spamprints howdy if is stored in spamand prints greetingsif anything else is stored in spam what keys can you press if your program is stuck in an infinite loop what is the difference between break and continue what is the difference between range( )range( )and range( in for loop write short program that prints the numbers to using for loop then write an equivalent program that prints the numbers to using while loop if you had function named bacon(inside module named spamhow would you call it after importing spamextra creditlook up the round(and abs(functions on the internetand find out what they do experiment with them in the interactive shell
2,543
functions you're already familiar with the print()input()and len(functions from the previous python provides several builtin functions like thesebut you can also write your own functions function is like miniprogram within program to better understand how functions worklet' create one enter this program into the file editor and save it as hellofunc pydef hello()print('howdy!'print('howdy!!!'print('hello there 'hello(hello(hello(
2,544
/hellofuncthe first line is def statement which defines function named hello(the code in the block that follows the def statement is the body of the function this code is executed when the function is callednot when the function is first defined the hello(lines after the function are function calls in codea function call is just the function' name followed by parenthesespossibly with some number of arguments in between the parentheses when the program execution reaches these callsit will jump to the top line in the function and begin executing the code there when it reaches the end of the functionthe execution returns to the line that called the function and continues moving through the code as before since this program calls hello(three timesthe code in the hello(function is executed three times when you run this programthe output looks like thishowdyhowdy!!hello there howdyhowdy!!hello there howdyhowdy!!hello there major purpose of functions is to group code that gets executed multiple times without function definedyou would have to copy and paste this code each timeand the program would look like thisprint('howdy!'print('howdy!!!'print('hello there 'print('howdy!'print('howdy!!!'print('hello there 'print('howdy!'print('howdy!!!'print('hello there 'in generalyou always want to avoid duplicating code because if you ever decide to update the code--iffor exampleyou find bug you need to fix--you'll have to remember to change the code everywhere you copied it as you get more programming experienceyou'll often find yourself deduplicating codewhich means getting rid of duplicated or copy-andpasted code deduplication makes your programs shortereasier to readand easier to update
2,545
when you call the print(or len(functionyou pass them valuescalled argumentsby typing them between the parentheses you can also define your own functions that accept arguments type this example into the file editor and save it as hellofunc pydef hello(name)print('hellonamehello('alice'hello('bob'when you run this programthe output looks like thishelloalice hellobob you can view the execution of this program at /hellofunc the definition of the hello(function in this program has parameter called name parameters are variables that contain arguments when function is called with argumentsthe arguments are stored in the parameters the first time the hello(function is calledit is passed the argument 'alicethe program execution enters the functionand the parameter name is automatically set to 'alice'which is what gets printed by the print(statement one special thing to note about parameters is that the value stored in parameter is forgotten when the function returns for exampleif you added print(nameafter hello('bob'in the previous programthe program would give you nameerror because there is no variable named name this variable is destroyed after the function call hello('bob'returnsso print(namewould refer to name variable that does not exist this is similar to how program' variables are forgotten when the program terminates 'll talk more about why that happens later in the when discuss what function' local scope is definecallpassargumentparameter the terms definecallpassargumentand parameter can be confusing let' look at code example to review these termsu def sayhello(name)print('hellonamev sayhello('al'to define function is to create itjust like an assignment statement like spam creates the spam variable the def statement defines the sayhello(function the sayhello('al'line calls the now-created functionsending the execution to the top of the function' code this function call is also known as passing the string value 'alto the function value being functions
2,546
is assigned to local variable named name variables that have arguments assigned to them are parameters it' easy to mix up these termsbut keeping them straight will ensure that you know precisely what the text in this means return values and return statements when you call the len(function and pass it an argument such as 'hello'the function call evaluates to the integer value which is the length of the string you passed it in generalthe value that function call evaluates to is called the return value of the function when creating function using the def statementyou can specify what the return value should be with return statement return statement consists of the followingthe return keyword the value or expression that the function should return when an expression is used with return statementthe return value is what this expression evaluates to for examplethe following program defines function that returns different string depending on what number it is passed as an argument enter this code into the file editor and save it as magic ball pyimport random def getanswer(answernumber)if answernumber = return 'it is certainelif answernumber = return 'it is decidedly soelif answernumber = return 'yeselif answernumber = return 'reply hazy try againelif answernumber = return 'ask again laterelif answernumber = return 'concentrate and ask againelif answernumber = return 'my reply is noelif answernumber = return 'outlook not so goodelif answernumber = return 'very doubtfulr random randint( fortune getanswer(rprint(fortune
2,547
/magic ballwhen this program startspython first imports the random module then the getanswer(function is defined because the function is being defined (and not called)the execution skips over the code in it nextthe random randint(function is called with two arguments and it evaluates to random integer between and (including and themselves)and this value is stored in variable named the getanswer(function is called with as the argument the program execution moves to the top of the getanswer(function and the value is stored in parameter named answernumber thendepending on the value in answernumberthe function returns one of many possible string values the program execution returns to the line at the bottom of the program that originally called getanswer(the returned string is assigned to variable named fortunewhich then gets passed to print(call and is printed to the screen note that since you can pass return values as an argument to another function callyou could shorten these three linesr random randint( fortune getanswer(rprint(fortuneto this single equivalent lineprint(getanswer(random randint( ))rememberexpressions are composed of values and operators function call can be used in an expression because the call evaluates to its return value the none value in pythonthere is value called nonewhich represents the absence of value the none value is the only value of the nonetype data type (other programming languages might call this value nullnilor undefined just like the boolean true and false valuesnone must be typed with capital this value-without- -value can be helpful when you need to store something that won' be confused for real value in variable one place where none is used is as the return value of print(the print(function displays text on the screenbut it doesn' need to return anything in the same way len(or input(does but since all function calls need to evaluate to return valueprint(returns none to see this in actionenter the following into the interactive shellspam print('hello!'hellonone =spam true functions
2,548
definition with no return statement this is similar to how while or for loop implicitly ends with continue statement alsoif you use return statement without value (that isjust the return keyword by itself)then none is returned keyword arguments and the print(function most arguments are identified by their position in the function call for examplerandom randint( is different from random randint( the function call random randint( will return random integer between and because the first argument is the low end of the range and the second argument is the high end (while random randint( causes an errorhoweverrather than through their positionkeyword arguments are identified by the keyword put before them in the function call keyword arguments are often used for optional parameters for examplethe print(function has the optional parameters end and sep to specify what should be printed at the end of its arguments and between its arguments (separating them)respectively if you ran program with the following codeprint('hello'print('world'the output would look like thishello world the two outputted strings appear on separate lines because the print(function automatically adds newline character to the end of the string it is passed howeveryou can set the end keyword argument to change the newline character to different string for exampleif the code were thisprint('hello'end=''print('world'the output would look like thishelloworld the output is printed on single line because there is no longer newline printed after 'helloinsteadthe blank string is printed this is useful if you need to disable the newline that gets added to the end of every print(function call
2,549
will automatically separate them with single space enter the following into the interactive shellprint('cats''dogs''mice'cats dogs mice but you could replace the default separating string by passing the sep keyword argument different string enter the following into the interactive shellprint('cats''dogs''mice'sep=','cats,dogs,mice you can add keyword arguments to the functions you write as wellbut first you'll have to learn about the list and dictionary data types in the next two for nowjust know that some functions have optional keyword arguments that can be specified when the function is called the call stack imagine that you have meandering conversation with someone you talk about your friend alicewhich then reminds you of story about your coworker bobbut first you have to explain something about your cousin carol you finish you story about carol and go back to talking about boband when you finish your story about bobyou go back to talking about alice but then you are reminded about your brother davidso you tell story about himand then get back to finishing your original story about alice your conversation followed stack-like structurelike in figure - the conversation is stack-like because the current topic is always at the top of the stack carol alice bob bob bob alice alice alice david alice alice alice figure - your meandering conversation stack similar to our meandering conversationcalling function doesn' send the execution on one-way trip to the top of function python will remember which line of code called the function so that the execution can return there when it encounters return statement if that original function called other functionsthe execution would return to those function calls firstbefore returning from the original function call functions
2,550
abcdcallstack pydef ()print(' (starts' ( (print(' (returns'def ()print(' (starts' (print(' (returns'def ()print(' (starts'print(' (returns'def ()print(' (starts'print(' (returns' (if you run this programthe output will look like thisa(starts (starts (starts (returns (returns (starts (returns (returns you can view the execution of this program at /abcdcallstackwhen (is called it calls (which in turn calls (the (function doesn' call anythingit just displays (starts and (returns before returning to the line in (that called it once execution returns to the code in (that called ()it returns to the line in (that called (the execution continues to the next line in the (function which is call to (like the (functionthe (function also doesn' call anything it just displays (starts and (returns before returning to the line in (that called it since (contains no other codethe execution returns to the line in (that called (the last line in (displays (returns before returning to the original (call at the end of the program the call stack is how python remembers where to return the execution after each function call the call stack isn' stored in variable in your programratherpython handles it behind the scenes when your program calls functionpython creates frame object on the top of the call stack frame
2,551
remember where to return if another function call is madepython puts another frame object on the call stack above the other one when function call returnspython removes frame object from the top of the stack and moves the execution to the line number stored in it note that frame objects are always added and removed from the top of the stack and not from any other place figure - illustrates the state of the call stack in abcdcallstack py as each function is called and returns ( ( ( ( ( ( ( ( ( ( ( (figure - the frame objects of the call stack as abcdcallstack py calls and returns from functions the top of the call stack is which function the execution is currently in when the call stack is emptythe execution is on line outside of all functions the call stack is technical detail that you don' strictly need to know about to write programs it' enough to understand that function calls return to the line number they were called from howeverunderstanding call stacks makes it easier to understand local and global scopesdescribed in the next section local and global scope parameters and variables that are assigned in called function are said to exist in that function' local scope variables that are assigned outside all functions are said to exist in the global scope variable that exists in local scope is called local variablewhile variable that exists in the global scope is called global variable variable must be one or the otherit cannot be both local and global think of scope as container for variables when scope is destroyedall the values stored in the scope' variables are forgotten there is only one global scopeand it is created when your program begins when your program terminatesthe global scope is destroyedand all its variables are forgotten otherwisethe next time you ran programthe variables would remember their values from the last time you ran it local scope is created whenever function is called any variables assigned in the function exist within the function' local scope when the function returnsthe local scope is destroyedand these variables are forgotten the next time you call the functionthe local variables will not remember the values stored in them from the last time the function was called local variables are also stored in frame objects on the call stack functions
2,552
code in the global scopeoutside of all functionscannot use any local variables howevercode in local scope can access global variables code in function' local scope cannot use variables in any other local scope you can use the same name for different variables if they are in different scopes that isthere can be local variable named spam and global variable also named spam the reason python has different scopes instead of just making everything global variable is so that when variables are modified by the code in particular call to functionthe function interacts with the rest of the program only through its parameters and the return value this narrows down the number of lines of code that may be causing bug if your program contained nothing but global variables and had bug because of variable being set to bad valuethen it would be hard to track down where this bad value was set it could have been set from anywhere in the programand your program could be hundreds or thousands of lines longbut if the bug is caused by local variable with bad valueyou know that only the code in that one function could have set it incorrectly while using global variables in small programs is fineit is bad habit to rely on global variables as your programs get larger and larger local variables cannot be used in the global scope consider this programwhich will cause an error when you run itdef spam()eggs spam(print(eggsif you run this programthe output will look like thistraceback (most recent call last)file " :/test py"line in print(eggsnameerrorname 'eggsis not defined the error happens because the eggs variable exists only in the local scope created when spam(is called once the program execution returns from spamthat local scope is destroyedand there is no longer variable named eggs so when your program tries to run print(eggs)python gives you an error saying that eggs is not defined this makes sense if you think about itwhen the program execution is in the global scopeno local scopes existso there can' be any local variables this is why only global variables can be used in the global scope
2,553
new local scope is created whenever function is calledincluding when function is called from another function consider this programdef spam()eggs bacon(print(eggsdef bacon()ham eggs spam(you can view the execution of this program at /otherlocalscopeswhen the program startsthe spam(function is called and local scope is created the local variable eggs is set to then the bacon(function is called and second local scope is created multiple local scopes can exist at the same time in this new local scopethe local variable ham is set to and local variable eggs--which is different from the one in spam()' local scope--is also created and set to when bacon(returnsthe local scope for that call is destroyedincluding its eggs variable the program execution continues in the spam(function to print the value of eggs since the local scope for the call to spam(still existsthe only eggs variable is the spam(function' eggs variablewhich was set to this is what the program prints the upshot is that local variables in one function are completely separate from the local variables in another function global variables can be read from local scope consider the following programdef spam()print(eggseggs spam(print(eggsyou can view the execution of this program at /readglobalsince there is no parameter named eggs or any code that assigns eggs value in the spam(functionwhen eggs is used in spam()python considers it reference to the global variable eggs this is why is printed when the previous program is run functions
2,554
technicallyit' perfectly acceptable to use the same variable name for global variable and local variables in different scopes in python butto simplify your lifeavoid doing this to see what happensenter the following code into the file editor and save it as localglobalsamename pydef spam()eggs 'spam localprint(eggsprints 'spam localdef bacon()eggs 'bacon localprint(eggsprints 'bacon localspam(print(eggsprints 'bacon localeggs 'globalbacon(print(eggsprints 'globalwhen you run this programit outputs the followingbacon local spam local bacon local global you can view the execution of this program at /localglobalsamenamethere are actually three different variables in this programbut confusingly they are all named eggs the variables are as followsu variable named eggs that exists in local scope when spam(is called variable named eggs that exists in local scope when bacon(is called variable named eggs that exists in the global scope since these three separate variables all have the same nameit can be confusing to keep track of which one is being used at any given time this is why you should avoid using the same variable name in different scopes the global statement if you need to modify global variable from within functionuse the global statement if you have line such as global eggs at the top of functionit tells python"in this functioneggs refers to the global variableso don' create local variable with this name for exampleenter the following code into the file editor and save it as globalstatement pydef spam()global eggs eggs 'spam
2,555
spam(print(eggswhen you run this programthe final print(call will output thisspam you can view the execution of this program at /globalstatementbecause eggs is declared global at the top of spam(when eggs is set to 'spamthis assignment is done to the globally scoped eggs no local eggs variable is created there are four rules to tell whether variable is in local scope or global scopeif variable is being used in the global scope (that isoutside of all functions)then it is always global variable if there is global statement for that variable in functionit is global variable otherwiseif the variable is used in an assignment statement in the functionit is local variable but if the variable is not used in an assignment statementit is global variable to get better feel for these ruleshere' an example program enter the following code into the file editor and save it as samenamelocalglobal pydef spam()global eggs eggs 'spamthis is the global def bacon()eggs 'baconthis is local def ham()print(eggsthis is the global eggs this is the global spam(print(eggsin the spam(functioneggs is the global eggs variable because there' global statement for eggs at the beginning of the function in bacon()eggs is local variable because there' an assignment statement for it in that function in ham(eggs is the global variable because there is no assignment statement or global statement for it in that function if you run samenamelocalglobal pythe output will look like thisspam functions
2,556
/samenamelocalglobalin functiona variable will either always be global or always be local the code in function can' use local variable named eggs and then use the global eggs variable later in that same function note if you ever want to modify the value stored in global variable from in functionyou must use global statement on that variable if you try to use local variable in function before you assign value to itas in the following programpython will give you an error to see thisenter the following into the file editor and save it as samenameerror pydef spam()print(eggserroreggs 'spam localeggs 'globalspam(if you run the previous programit produces an error message traceback (most recent call last)file " :/samenameerror py"line in spam(file " :/samenameerror py"line in spam print(eggserrorunboundlocalerrorlocal variable 'eggsreferenced before assignment you can view the execution of this program at /samenameerrorthis error happens because python sees that there is an assignment statement for eggs in the spam(function andthereforeconsiders eggs to be local but because print(eggsis executed before eggs is assigned anythingthe local variable eggs doesn' exist python will not fall back to using the global eggs variable unc tions "bl ack box softenall you need to know about function are its inputs (the parametersand output valueyou don' always have to burden yourself with how the function' code actually works when you think about functions in this high-level wayit' common to say that you're treating function as "black box this idea is fundamental to modern programming later in this book will show you several modules with functions that were written by other people while you can take peek at the source code if you're curiousyou don' need to know how these functions work in order to use them and because writing functions without global variables is encouragedyou usually don' have to worry about the function' code interacting with the rest of your program
2,557
right nowgetting an erroror exceptionin your python program means the entire program will crash you don' want this to happen in real-world programs insteadyou want the program to detect errorshandle themand then continue to run for exampleconsider the following programwhich has divide-byzero error open file editor window and enter the following codesaving it as zerodivide pydef spam(divideby)return divideby print(spam( )print(spam( )print(spam( )print(spam( )we've defined function called spamgiven it parameterand then printed the value of that function with various parameters to see what happens this is the output you get when you run the previous code traceback (most recent call last)file " :/zerodivide py"line in print(spam( )file " :/zerodivide py"line in spam return divideby zerodivisionerrordivision by zero you can view the execution of this program at /zerodividea zerodivisionerror happens whenever you try to divide number by zero from the line number given in the error messageyou know that the return statement in spam(is causing an error errors can be handled with try and except statements the code that could potentially have an error is put in try clause the program execution moves to the start of following except clause if an error happens you can put the previous divide-by-zero code in try clause and have an except clause contain code to handle what happens when this error occurs def spam(divideby)tryreturn divideby except zerodivisionerrorprint('errorinvalid argument 'print(spam( )print(spam( )print(spam( )print(spam( )functions
2,558
immediately moves to the code in the except clause after running that codethe execution continues as normal the output of the previous program is as follows errorinvalid argument none you can view the execution of this program at /tryexceptzerodividenote that any errors that occur in function calls in try block will also be caught consider the following programwhich instead has the spam(calls in the try blockdef spam(divideby)return divideby tryprint(spam( )print(spam( )print(spam( )print(spam( )except zerodivisionerrorprint('errorinvalid argument 'when this program is runthe output looks like this errorinvalid argument you can view the execution of this program at /spamintrythe reason print(spam( )is never executed is because once the execution jumps to the code in the except clauseit does not return to the try clause insteadit just continues moving down the program as normal short programzigzag let' use the programming concepts you've learned so far to create small animation program this program will create back-and-forthzigzag pattern until the user stops it by pressing the mu editor' stop button or by pressing ctrl- when you run this programthe output will look something like this*********************
2,559
***********************************type the following source code into the file editorand save the file as zigzag pyimport timesys indent how many spaces to indent indentincreasing true whether the indentation is increasing or not trywhile truethe main program loop print(indentend=''print('********'time sleep( pause for / of second if indentincreasingincrease the number of spacesindent indent if indent = change directionindentincreasing false elsedecrease the number of spacesindent indent if indent = change directionindentincreasing true except keyboardinterruptsys exit(let' look at this code line by linestarting at the top import timesys indent how many spaces to indent indentincreasing true whether the indentation is increasing or not firstwe'll import the time and sys modules our program uses two variablesthe indent variable keeps track of how many spaces of indentation are before the band of eight asterisks and indentincreasing contains boolean value to determine if the amount of indentation is increasing or decreasing trywhile truethe main program loop print(indentend=''print('********'time sleep( pause for / of second functions
2,560
user presses ctrl- while python program is runningpython raises the keyboardinterrupt exception if there is no tryexcept statement to catch this exceptionthe program crashes with an ugly error message howeverfor our programwe want it to cleanly handle the keyboardinterrupt exception by calling sys exit((the code for this is in the except statement at the end of the program the while trueinfinite loop will repeat the instructions in our program forever this involves using indent to print the correct amount of spaces of indentation we don' want to automatically print newline after these spacesso we also pass end='to the first print(call second print(call prints the band of asterisks the time sleep(function hasn' been covered yetbut suffice it to say that it introduces one-tenth-second pause in our program at this point if indentincreasingincrease the number of spacesindent indent if indent = indentincreasing false change direction nextwe want to adjust the amount of indentation for the next time we print asterisks if indentincreasing is truethen we want to add one to indent but once indent reaches we want the indentation to decrease elsedecrease the number of spacesindent indent if indent = indentincreasing true change direction meanwhileif indentincreasing was falsewe want to subtract one from indent once indent reaches we want the indentation to increase once again either waythe program execution will jump back to the start of the main program loop to print the asterisks again except keyboardinterruptsys exit(if the user presses ctrl- at any point that the program execution is in the try blockthe keyboardinterrrupt exception is raised and handled by this except statement the program execution moves inside the except blockwhich runs sys exit(and quits the program this wayeven though the main program loop is an infinite loopthe user has way to shut down the program
2,561
functions are the primary way to compartmentalize your code into logical groups since the variables in functions exist in their own local scopesthe code in one function cannot directly affect the values of variables in other functions this limits what code could be changing the values of your variableswhich can be helpful when it comes to debugging your code functions are great tool to help you organize your code you can think of them as black boxesthey have inputs in the form of parameters and outputs in the form of return valuesand the code in them doesn' affect variables in other functions in previous single error could cause your programs to crash in this you learned about try and except statementswhich can run code when an error has been detected this can make your programs more resilient to common error cases practice questions why are functions advantageous to have in your programswhen does the code in function executewhen the function is defined or when the function is called what statement creates function what is the difference between function and function call how many global scopes are there in python programhow many local scopes what happens to variables in local scope when the function call returns what is return valuecan return value be part of an expression if function does not have return statementwhat is the return value of call to that function how can you force variable in function to refer to the global variable what is the data type of none what does the import areallyourpetsnamederic statement do if you had function named bacon(in module named spamhow would you call it after importing spam how can you prevent program from crashing when it gets an error what goes in the try clausewhat goes in the except clausefunctions
2,562
for practicewrite programs to do the following tasks the collatz sequence write function named collatz(that has one parameter named number if number is eventhen collatz(should print number / and return this value if number is oddthen collatz(should print and return number then write program that lets the user type in an integer and that keeps calling collatz(on that number until the function returns the value (amazingly enoughthis sequence actually works for any integer--sooner or laterusing this sequenceyou'll arrive at even mathematicians aren' sure why your program is exploring what' called the collatz sequencesometimes called "the simplest impossible math problem "remember to convert the return value from input(to an integer with the int(functionotherwiseit will be string value hintan integer number is even if number = and it' odd if number = the output of this program could look something like thisenter number input validation add try and except statements to the previous project to detect whether the user types in noninteger string normallythe int(function will raise valueerror error if it is passed noninteger stringas in int('puppy'in the except clauseprint message to the user saying they must enter an integer
2,563
lists one more topic you'll need to understand before you can begin writing programs in earnest is the list data type and its cousinthe tuple lists and tuples can contain multiple valueswhich makes writing programs that handle large amounts of data easier and since lists themselves can contain other listsyou can use them to arrange data into hierarchical structures in this 'll discuss the basics of lists 'll also teach you about methodswhich are functions that are tied to values of certain data type then 'll briefly cover the sequence data types (liststuplesand stringsand show how they compare with each other in the next 'll introduce you to the dictionary data type
2,564
list is value that contains multiple values in an ordered sequence the term list value refers to the list itself (which is value that can be stored in variable or passed to function like any other value)not the values inside the list value list value looks like this['cat''bat''rat''elephant'just as string values are typed with quote characters to mark where the string begins and endsa list begins with an opening square bracket and ends with closing square bracket[values inside the list are also called items items are separated with commas (that isthey are comma-delimitedfor exampleenter the following into the interactive shell[ [ ['cat''bat''rat''elephant'['cat''bat''rat''elephant'['hello' truenone ['hello' truenone spam ['cat''bat''rat''elephant'spam ['cat''bat''rat''elephant'the spam variable is still assigned only one valuethe list value but the list value itself contains other values the value [is an empty list that contains no valuessimilar to ''the empty string getting individual values in list with indexes say you have the list ['cat''bat''rat''elephant'stored in variable named spam the python code spam[ would evaluate to 'cat'and spam[ would evaluate to 'bat'and so on the integer inside the square brackets that follows the list is called an index the first value in the list is at index the second value is at index the third value is at index and so on figure - shows list value assigned to spamalong with what the index expressions would evaluate to note that because the first index is the last index is one less than the size of the lista list of four items has as its last index spam ["cat""bat""rat""elephant"spam[ spam[ spam[ spam[ figure - list value stored in the variable spamshowing which value each index refers to for exampleenter the following expressions into the interactive shell start by assigning list to the variable spam spam ['cat''bat''rat''elephant'spam[ 'cat
2,565
'batspam[ 'ratspam[ 'elephant['cat''bat''rat''elephant'][ 'elephant'hellospam[ 'hellocat'the spam[ ate the spam[ 'the bat ate the cat notice that the expression 'hellospam[ evaluates to 'hello'catbecause spam[ evaluates to the string 'catthis expression in turn evaluates to the string value 'hellocatpython will give you an indexerror error message if you use an index that exceeds the number of values in your list value spam ['cat''bat''rat''elephant'spam[ traceback (most recent call last)file ""line in spam[ indexerrorlist index out of range indexes can be only integer valuesnot floats the following example will cause typeerror errorspam ['cat''bat''rat''elephant'spam[ 'batspam[ traceback (most recent call last)file ""line in spam[ typeerrorlist indices must be integers or slicesnot float spam[int( )'batlists can also contain other list values the values in these lists of lists can be accessed using multiple indexeslike sospam [['cat''bat'][ ]spam[ ['cat''bat'spam[ ][ 'batspam[ ][ lists
2,566
the value within the list value for examplespam[ ][ prints 'bat'the second value in the first list if you only use one indexthe program will print the full list value at that index negative indexes while indexes start at and go upyou can also use negative integers for the index the integer value - refers to the last index in listthe value - refers to the second-to-last index in listand so on enter the following into the interactive shellspam ['cat''bat''rat''elephant'spam[- 'elephantspam[- 'bat'the spam[- is afraid of the spam[- 'the elephant is afraid of the bat getting list from another list with slices just as an index can get single value from lista slice can get several values from listin the form of new list slice is typed between square bracketslike an indexbut it has two integers separated by colon notice the difference between indexes and slices spam[ is list with an index (one integerspam[ : is list with slice (two integersin slicethe first integer is the index where the slice starts the second integer is the index where the slice ends slice goes up tobut will not includethe value at the second index slice evaluates to new list value enter the following into the interactive shellspam ['cat''bat''rat''elephant'spam[ : ['cat''bat''rat''elephant'spam[ : ['bat''rat'spam[ :- ['cat''bat''rat'as shortcutyou can leave out one or both of the indexes on either side of the colon in the slice leaving out the first index is the same as using or the beginning of the list leaving out the second index is the same as using the length of the listwhich will slice to the end of the list enter the following into the interactive shellspam ['cat''bat''rat''elephant'spam[:
2,567
spam[ :['bat''rat''elephant'spam[:['cat''bat''rat''elephant'getting list' length with the len(function the len(function will return the number of values that are in list value passed to itjust like it can count the number of characters in string value enter the following into the interactive shellspam ['cat''dog''moose'len(spam changing values in list with indexes normallya variable name goes on the left side of an assignment statementlike spam howeveryou can also use an index of list to change the value at that index for examplespam[ 'aardvarkmeans "assign the value at index in the list spam to the string 'aardvarkenter the following into the interactive shellspam ['cat''bat''rat''elephant'spam[ 'aardvarkspam ['cat''aardvark''rat''elephant'spam[ spam[ spam ['cat''aardvark''aardvark''elephant'spam[- spam ['cat''aardvark''aardvark' list concatenation and list replication lists can be concatenated and replicated just like strings the operator combines two lists to create new list value and the operator can be used with list and an integer value to replicate the list enter the following into the interactive shell[ [' '' '' '[ ' '' '' '[' '' '' ' [' '' '' '' '' '' '' '' '' 'spam [ spam spam [' '' '' 'spam [ ' '' '' 'lists
2,568
the del statement will delete values at an index in list all of the values in the list after the deleted value will be moved up one index for exampleenter the following into the interactive shellspam ['cat''bat''rat''elephant'del spam[ spam ['cat''bat''elephant'del spam[ spam ['cat''bat'the del statement can also be used on simple variable to delete itas if it were an "unassignmentstatement if you try to use the variable after deleting ityou will get nameerror error because the variable no longer exists in practiceyou almost never need to delete simple variables the del statement is mostly used to delete values from lists working with lists when you first begin writing programsit' tempting to create many individual variables to store group of similar values for exampleif wanted to store the names of my catsi might be tempted to write code like thiscatname 'zophiecatname 'pookacatname 'simoncatname 'lady macbethcatname 'fat-tailcatname 'miss cleoit turns out that this is bad way to write code (alsoi don' actually own this many catsi swear for one thingif the number of cats changesyour program will never be able to store more cats than you have variables these types of programs also have lot of duplicate or nearly identical code in them consider how much duplicate code is in the following programwhich you should enter into the file editor and save as allmycats pyprint('enter the name of cat :'catname input(print('enter the name of cat :'catname input(print('enter the name of cat :'catname input(print('enter the name of cat :'catname input(print('enter the name of cat :'catname input(print('enter the name of cat :'
2,569
print('the cat names are:'print(catname catname catname catname catname catname instead of using multiplerepetitive variablesyou can use single variable that contains list value for examplehere' new and improved version of the allmycats py program this new version uses single list and can store any number of cats that the user types in in new file editor windowenter the following source code and save it as allmycats pycatnames [while trueprint('enter the name of cat str(len(catnames (or enter nothing to stop ):'name input(if name =''break catnames catnames [namelist concatenation print('the cat names are:'for name in catnamesprint(namewhen you run this programthe output will look something like thisenter the name of cat (or enter nothing to stop )zophie enter the name of cat (or enter nothing to stop )pooka enter the name of cat (or enter nothing to stop )simon enter the name of cat (or enter nothing to stop )lady macbeth enter the name of cat (or enter nothing to stop )fat-tail enter the name of cat (or enter nothing to stop )miss cleo enter the name of cat (or enter nothing to stop )the cat names arezophie pooka simon lady macbeth fat-tail miss cleo you can view the execution of these programs at /allmycats and that your data is now in structureso your program is much more flexible in processing the data than it would be with several repetitive variables lists
2,570
in you learned about using for loops to execute block of code certain number of times technicallya for loop repeats the code block once for each item in list value for exampleif you ran this codefor in range( )print(ithe output of this program would be as follows this is because the return value from range( is sequence value that python considers similar to [ (sequences are described in "sequence data typeson page the following program has the same output as the previous onefor in [ ]print(ithe previous for loop actually loops through its clause with the variable set to successive value in the [ list in each iteration common python technique is to use range(len(somelist)with for loop to iterate over the indexes of list for exampleenter the following into the interactive shellsupplies ['pens''staplers''flamethrowers''binders'for in range(len(supplies))print('index str(iin supplies issupplies[ ]index in supplies ispens index in supplies isstaplers index in supplies isflamethrowers index in supplies isbinders using range(len(supplies)in the previously shown for loop is handy because the code in the loop can access the index (as the variable iand the value at that index (as supplies[ ]best of allrange(len(supplies)will iterate through all the indexes of suppliesno matter how many items it contains the in and not in operators you can determine whether value is or isn' in list with the in and not in operators like other operatorsin and not in are used in expressions and connect two valuesa value to look for in list and the list where it may be
2,571
'howdyin ['hello''hi''howdy''heyas'true spam ['hello''hi''howdy''heyas''catin spam false 'howdynot in spam false 'catnot in spam true for examplethe following program lets the user type in pet name and then checks to see whether the name is in list of pets open new file editor windowenter the following codeand save it as mypets pymypets ['zophie''pooka''fat-tail'print('enter pet name:'name input(if name not in mypetsprint(' do not have pet named nameelseprint(name is my pet 'the output may look something like thisenter pet namefootfoot do not have pet named footfoot you can view the execution of this program at the multiple assignment trick the multiple assignment trick (technically called tuple unpackingis shortcut that lets you assign multiple variables with the values in list in one line of code so instead of doing thiscat ['fat''gray''loud'size cat[ color cat[ disposition cat[ you could type this line of codecat ['fat''gray''loud'sizecolordisposition cat lists
2,572
equalor python will give you valueerrorcat ['fat''gray''loud'sizecolordispositionname cat traceback (most recent call last)file ""line in sizecolordispositionname cat valueerrornot enough values to unpack (expected got using the enumerate(function with lists instead of using the range(len(somelist)technique with for loop to obtain the integer index of the items in the listyou can call the enumerate(function instead on each iteration of the loopenumerate(will return two valuesthe index of the item in the listand the item in the list itself for examplethis code is equivalent to the code in the "using for loops with listson page supplies ['pens''staplers''flamethrowers''binders'for indexitem in enumerate(supplies)print('index str(indexin supplies isitemindex in supplies ispens index in supplies isstaplers index in supplies isflamethrowers index in supplies isbinders the enumerate(function is useful if you need both the item and the item' index in the loop' block using the random choice(and random shuffle(functions with lists the random module has couple functions that accept lists for arguments the random choice(function will return randomly selected item from the list enter the following into the interactive shellimport random pets ['dog''cat''moose'random choice(pets'dograndom choice(pets'catrandom choice(pets'catyou can consider random choice(somelistto be shorter form of somelist[random randint( len(somelist
2,573
following into the interactive shellimport random people ['alice''bob''carol''david'random shuffle(peoplepeople ['carol''david''alice''bob'random shuffle(peoplepeople ['alice''david''bob''carol'augmented assignment operators when assigning value to variableyou will frequently use the variable itself for exampleafter assigning to the variable spamyou would increase the value in spam by with the following codespam spam spam spam as shortcutyou can use the augmented assignment operator +to do the same thingspam spam + spam there are augmented assignment operators for the +-*/and operatorsdescribed in table - table - the augmented assignment operators augmented assignment statement equivalent assignment statement spam + spam spam spam - spam spam spam * spam spam spam / spam spam spam % spam spam lists
2,574
*operator can do string and list replication enter the following into the interactive shellspam 'hello,spam +world!spam 'hello world!bacon ['zophie'bacon * bacon ['zophie''zophie''zophie'methods method is the same thing as functionexcept it is "called ona value for exampleif list value were stored in spamyou would call the index(list method (which 'll explain shortlyon that list like sospam index('hello'the method part comes after the valueseparated by period each data type has its own set of methods the list data typefor examplehas several useful methods for findingaddingremovingand otherwise manipulating values in list finding value in list with the index(method list values have an index(method that can be passed valueand if that value exists in the listthe index of the value is returned if the value isn' in the listthen python produces valueerror error enter the following into the interactive shellspam ['hello''hi''howdy''heyas'spam index('hello' spam index('heyas' spam index('howdy howdy howdy'traceback (most recent call last)file ""line in spam index('howdy howdy howdy'valueerror'howdy howdy howdyis not in list when there are duplicates of the value in the listthe index of its first appearance is returned enter the following into the interactive shelland notice that index(returns not spam ['zophie''pooka''fat-tail''pooka'spam index('pooka'
2,575
to add new values to listuse the append(and insert(methods enter the following into the interactive shell to call the append(method on list value stored in the variable spamspam ['cat''dog''bat'spam append('moose'spam ['cat''dog''bat''moose'the previous append(method call adds the argument to the end of the list the insert(method can insert value at any index in the list the first argument to insert(is the index for the new valueand the second argument is the new value to be inserted enter the following into the interactive shellspam ['cat''dog''bat'spam insert( 'chicken'spam ['cat''chicken''dog''bat'notice that the code is spam append('moose'and spam insert( 'chicken')not spam spam append('moose'and spam spam insert( 'chicken'neither append(nor insert(gives the new value of spam as its return value (in factthe return value of append(and insert(is noneso you definitely wouldn' want to store this as the new variable value ratherthe list is modified in place modifying list in place is covered in more detail later in "mutable and immutable data typeson page methods belong to single data type the append(and insert(methods are list methods and can be called only on list valuesnot on other values such as strings or integers enter the following into the interactive shelland note the attributeerror error messages that show upeggs 'helloeggs append('world'traceback (most recent call last)file ""line in eggs append('world'attributeerror'strobject has no attribute 'appendbacon bacon insert( 'world'traceback (most recent call last)file ""line in bacon insert( 'world'attributeerror'intobject has no attribute 'insertlists
2,576
the remove(method is passed the value to be removed from the list it is called on enter the following into the interactive shellspam ['cat''bat''rat''elephant'spam remove('bat'spam ['cat''rat''elephant'attempting to delete value that does not exist in the list will result in valueerror error for exampleenter the following into the interactive shell and notice the error that is displayedspam ['cat''bat''rat''elephant'spam remove('chicken'traceback (most recent call last)file ""line in spam remove('chicken'valueerrorlist remove( ) not in list if the value appears multiple times in the listonly the first instance of the value will be removed enter the following into the interactive shellspam ['cat''bat''rat''cat''hat''cat'spam remove('cat'spam ['bat''rat''cat''hat''cat'the del statement is good to use when you know the index of the value you want to remove from the list the remove(method is useful when you know the value you want to remove from the list sorting the values in list with the sort(method lists of number values or lists of strings can be sorted with the sort(method for exampleenter the following into the interactive shellspam [ - spam sort(spam [- spam ['ants''cats''dogs''badgers''elephants'spam sort(spam ['ants''badgers''cats''dogs''elephants'
2,577
sort the values in reverse order enter the following into the interactive shellspam sort(reverse=truespam ['elephants''dogs''cats''badgers''ants'there are three things you should note about the sort(method firstthe sort(method sorts the list in placedon' try to capture the return value by writing code like spam spam sort(secondyou cannot sort lists that have both number values and string values in themsince python doesn' know how to compare these values enter the following into the interactive shell and notice the typeerror errorspam [ 'alice''bob'spam sort(traceback (most recent call last)file ""line in spam sort(typeerror'<not supported between instances of 'strand 'intthirdsort(uses "asciibetical orderrather than actual alphabetical order for sorting strings this means uppercase letters come before lowercase letters thereforethe lowercase is sorted so that it comes after the uppercase for an exampleenter the following into the interactive shellspam ['alice''ants''bob''badgers''carol''cats'spam sort(spam ['alice''bob''carol''ants''badgers''cats'if you need to sort the values in regular alphabetical orderpass str lower for the key keyword argument in the sort(method call spam [' '' '' '' 'spam sort(key=str lowerspam [' '' '' '' 'this causes the sort(function to treat all the items in the list as if they were lowercase without actually changing the values in the list reversing the values in list with the reverse(method if you need to quickly reverse the order of the items in listyou can call the reverse(list method enter the following into the interactive shellspam ['cat''dog''moose'spam reverse(spam ['moose''dog''cat'lists
2,578
in most casesthe amount of indentation for line of code tells python what block it is in there are some exceptions to this rulehowever for examplelists can actually span several lines in the source code file the indentation of these lines does not matterpython knows that the list is not finished until it sees the ending square bracket for exampleyou can have code that looks like thisspam ['apples''oranges''bananas''cats'print(spamof coursepractically speakingmost people use python' behavior to make their lists look pretty and readablelike the messages list in the magic ball program you can also split up single instruction across multiple lines using the line continuation character at the end think of as saying"this instruction continues on the next line the indentation on the line after line continuation is not significant for examplethe following is valid python codeprint('four score and seven 'years ago 'these tricks are useful when you want to rearrange long lines of python code to be bit more readable like the sort(list methodreverse(doesn' return list this is why you write spam reverse()instead of spam spam reverse(example programmagic ball with list using listsyou can write much more elegant version of the previous magic ball program instead of several lines of nearly identical elif statementsyou can create single list that the code works with open new file editor window and enter the following code save it as magic ball py import random messages ['it is certain''it is decidedly so''yes definitely''reply hazy try again''ask again later''concentrate and ask again''my reply is no'
2,579
'very doubtful'print(messages[random randint( len(messages )]you can view the execution of this program at /magic ball when you run this programyou'll see that it works the same as the previous magic ball py program notice the expression you use as the index for messagesrandom randint ( len(messages this produces random number to use for the indexregardless of the size of messages that isyou'll get random number between and the value of len(messages the benefit of this approach is that you can easily add and remove strings to the messages list without changing other lines of code if you later update your codethere will be fewer lines you have to change and fewer chances for you to introduce bugs sequence data types lists aren' the only data types that represent ordered sequences of values for examplestrings and lists are actually similar if you consider string to be "listof single text characters the python sequence data types include listsstringsrange objects returned by range()and tuples (explained in the "the tuple data typeon page many of the things you can do with lists can also be done with strings and other values of sequence typesindexingslicingand using them with for loopswith len()and with the in and not in operators to see thisenter the following into the interactive shellname 'zophiename[ 'zname[- 'iname[ : 'zoph'zoin name true 'zin name false 'pnot in name false for in nameprint(' *' lists
2,580
but lists and strings are different in an important way list value is mutable data typeit can have values addedremovedor changed howevera string is immutableit cannot be changed trying to reassign single character in string results in typeerror erroras you can see by entering the following into the interactive shellname 'zophie catname[ 'thetraceback (most recent call last)file ""line in name[ 'thetypeerror'strobject does not support item assignment the proper way to "mutatea string is to use slicing and concatenation to build new string by copying from parts of the old string enter the following into the interactive shellname 'zophie catnewname name[ : 'thename[ : name 'zophie catnewname 'zophie the catwe used [ : and [ : to refer to the characters that we don' wish to replace notice that the original 'zophie catstring is not modifiedbecause strings are immutable although list value is mutablethe second line in the following code does not modify the list eggseggs [ eggs [ eggs [ the list value in eggs isn' being changed hereratheran entirely new and different list value ([ ]is overwriting the old list value ([ ]this is depicted in figure - if you wanted to actually modify the original list in eggs to contain [ ]you would have to do something like thiseggs [ del eggs[ del eggs[ del eggs[ eggs append( eggs append( eggs append( eggs [
2,581
with new list value in the first examplethe list value that eggs ends up with is the same list value it started with it' just that this list has been changedrather than overwritten figure - depicts the seven changes made by the first seven lines in the previous interactive shell example figure - the del statement and the append(method modify the same list value in place changing value of mutable data type (like what the del statement and append(method do in the previous examplechanges the value in placesince the variable' value is not replaced with new list value mutable versus immutable types may seem like meaningless distinctionbut "passing referenceson page will explain the different behavior when calling functions with mutable arguments versus immutable arguments but firstlet' find out about the tuple data typewhich is an immutable form of the list data type lists
2,582
the tuple data type is almost identical to the list data typeexcept in two ways firsttuples are typed with parenthesesand )instead of square bracketsand for exampleenter the following into the interactive shelleggs ('hello' eggs[ 'helloeggs[ : ( len(eggs but the main way that tuples are different from lists is that tupleslike stringsare immutable tuples cannot have their values modifiedappendedor removed enter the following into the interactive shelland look at the typeerror error messageeggs ('hello' eggs[ traceback (most recent call last)file ""line in eggs[ typeerror'tupleobject does not support item assignment if you have only one value in your tupleyou can indicate this by placing trailing comma after the value inside the parentheses otherwisepython will think you've just typed value inside regular parentheses the comma is what lets python know this is tuple value (unlike some other programming languagesit' fine to have trailing comma after the last item in list or tuple in python enter the following type(function calls into the interactive shell to see the distinctiontype(('hello',)type(('hello')you can use tuples to convey to anyone reading your code that you don' intend for that sequence of values to change if you need an ordered sequence of values that never changesuse tuple second benefit of using tuples instead of lists is thatbecause they are immutable and their contents don' changepython can implement some optimizations that make code using tuples slightly faster than code using lists
2,583
just like how str( will return ' 'the string representation of the integer the functions list(and tuple(will return list and tuple versions of the values passed to them enter the following into the interactive shelland notice that the return value is of different data type than the value passedtuple(['cat''dog' ]('cat''dog' list(('cat''dog' )['cat''dog' list('hello'[' '' '' '' '' 'converting tuple to list is handy if you need mutable version of tuple value references as you've seenvariables "storestrings and integer values howeverthis explanation is simplification of what python is actually doing technicallyvariables are storing references to the computer memory locations where the values are stored enter the following into the interactive shellspam cheese spam spam spam cheese when you assign to the spam variableyou are actually creating the value in the computer' memory and storing reference to it in the spam variable when you copy the value in spam and assign it to the variable cheeseyou are actually copying the reference both the spam and cheese variables refer to the value in the computer' memory when you later change the value in spam to you're creating new value and storing reference to it in spam this doesn' affect the value in cheese integers are immutable values that don' changechanging the spam variable is actually making it refer to completely different value in memory but lists don' work this waybecause list values can changethat islists are mutable here is some code that will make this distinction easier to understand enter this into the interactive shellspam [ cheese spam the reference is being copiednot the list cheese[ 'hello!this changes the list value spam lists
2,584
cheese the cheese variable refers to the same list [ 'hello!' this might look odd to you the code touched only the cheese listbut it seems that both the cheese and spam lists have changed when you create the list you assign reference to it in the spam variable but the next line copies only the list reference in spam to cheesenot the list value itself this means the values stored in spam and cheese now both refer to the same list there is only one underlying list because the list itself was never actually copied so when you modify the first element of cheese you are modifying the same list that spam refers to remember that variables are like boxes that contain values the previous figures in this show that lists in boxes aren' exactly accuratebecause list variables don' actually contain lists--they contain references to lists (these references will have id numbers that python uses internallybut you can ignore them using boxes as metaphor for variablesfigure - shows what happens when list is assigned to the spam variable figure - spam [ stores reference to listnot the actual list thenin figure - the reference in spam is copied to cheese only new reference was created and stored in cheesenot new list note how both references refer to the same list figure - spam cheese copies the referencenot the list
2,585
also changedbecause both cheese and spam refer to the same list you can see this in figure - figure - cheese[ 'hello!modifies the list that both variables refer to although python variables technically contain references to valuespeople often casually say that the variable contains the value identity and the id(function you may be wondering why the weird behavior with mutable lists in the previous section doesn' happen with immutable values like integers or strings we can use python' id(function to understand this all values in python have unique identity that can be obtained with the id(function enter the following into the interactive shellid('howdy'the returned number will be different on your machine when python runs id('howdy')it creates the 'howdystring in the computer' memory the numeric memory address where the string is stored is returned by the id(function python picks this address based on which memory bytes happen to be free on your computer at the timeso it'll be different each time you run this code like all strings'howdyis immutable and cannot be changed if you "changethe string in variablea new string object is being made at different place in memoryand the variable refers to this new string for exampleenter the following into the interactive shell and see how the identity of the string referred to by bacon changesbacon 'helloid(bacon bacon +world! new string is made from 'helloand world!id(baconbacon now refers to completely different string lists
2,586
append(method doesn' create new list objectit changes the existing list object we call this "modifying the object in-place eggs ['cat''dog'this creates new list id(eggs eggs append('moose'append(modifies the list "in placeid(eggseggs still refers to the same list as before eggs ['bat''rat''cow'this creates new listwhich has new identity id(eggseggs now refers to completely different list if two variables refer to the same list (like spam and cheese in the previous sectionand the list value itself changesboth variables are affected because they both refer to the same list the append()extend()remove()sort()reverse()and other list methods modify their lists in place python' automatic garbage collector deletes any values not being referred to by any variables to free up memory you don' need to worry about how the garbage collector workswhich is good thingmanual memory management in other programming languages is common source of bugs passing references references are particularly important for understanding how arguments get passed to functions when function is calledthe values of the arguments are copied to the parameter variables for lists (and dictionarieswhich 'll describe in the next this means copy of the reference is used for the parameter to see the consequences of thisopen new file editor windowenter the following codeand save it as passingreference pydef eggs(someparameter)someparameter append('hello'spam [ eggs(spamprint(spamnotice that when eggs(is calleda return value is not used to assign new value to spam insteadit modifies the list in placedirectly when runthis program produces the following output[ 'hello'even though spam and someparameter contain separate referencesthey both refer to the same list this is why the append('hello'method call inside the function affects the list even after the function call has returned
2,587
the copy module' copy(and deepcopy(functions although passing around references is often the handiest way to deal with lists and dictionariesif the function modifies the list or dictionary that is passedyou may not want these changes in the original list or dictionary value for thispython provides module named copy that provides both the copy(and deepcopy(functions the first of thesecopy copy()can be used to make duplicate copy of mutable value like list or dictionarynot just copy of reference enter the following into the interactive shellimport copy spam [' '' '' '' 'id(spam cheese copy copy(spamid(cheesecheese is different list with different identity cheese[ spam [' '' '' '' 'cheese [' ' ' '' 'now the spam and cheese variables refer to separate listswhich is why only the list in cheese is modified when you assign at index as you can see in figure - the reference id numbers are no longer the same for both variables because the variables refer to independent lists figure - cheese copy copy(spamcreates second list that can be modified independently of the first if the list you need to copy contains liststhen use the copy deepcopy(function instead of copy copy(the deepcopy(function will copy these inner lists as well lists
2,588
conway' game of life is an example of cellular automataa set of rules governing the behavior of field made up of discrete cells in practiceit creates pretty animation to look at you can draw out each step on graph paperusing the squares as cells filled-in square will be "aliveand an empty square will be "dead if living square has two or three living neighborsit continues to live on the next step if dead square has exactly three living neighborsit comes alive on the next step every other square dies or remains dead on the next step you can see an example of the progression of steps in figure - figure - four steps in conway' game of life simulation even though the rules are simplethere are many surprising behaviors that emerge patterns in conway' game of life can moveself-replicateor even mimic cpus but at the foundation of all of this complexadvanced behavior is rather simple program we can use list of lists to represent the two-dimensional field the inner list represents each column of squares and stores '#hash string for living squares and space string for dead squares type the following source code into the file editorand save the file as conway py it' fine if you don' quite understand how all of the code worksjust enter it and follow along with comments and explanations provided here as close as you canconway' game of life import randomtimecopy width height create list of list for the cellsnextcells [for in range(width)column [create new column for in range(height)if random randint( = column append('#'add living cell elsecolumn append('add dead cell nextcells append(columnnextcells is list of column lists while truemain program loop print('\ \ \ \ \ 'separate each step with newlines currentcells copy deepcopy(nextcells
2,589
for in range(height)for in range(width)print(currentcells[ ][ ]end=''print the or space print(print newline at the end of the row calculate the next step' cells based on current step' cellsfor in range(width)for in range(height)get neighboring coordinates`widthensures leftcoord is always between and width leftcoord ( width rightcoord ( width abovecoord ( height belowcoord ( height count number of living neighborsnumneighbors if currentcells[leftcoord][abovecoord='#'numneighbors + top-left neighbor is alive if currentcells[ ][abovecoord='#'numneighbors + top neighbor is alive if currentcells[rightcoord][abovecoord='#'numneighbors + top-right neighbor is alive if currentcells[leftcoord][ ='#'numneighbors + left neighbor is alive if currentcells[rightcoord][ ='#'numneighbors + right neighbor is alive if currentcells[leftcoord][belowcoord='#'numneighbors + bottom-left neighbor is alive if currentcells[ ][belowcoord='#'numneighbors + bottom neighbor is alive if currentcells[rightcoord][belowcoord='#'numneighbors + bottom-right neighbor is alive set cell based on conway' game of life rulesif currentcells[ ][ ='#and (numneighbors = or numneighbors = )living cells with or neighbors stay alivenextcells[ ][ '#elif currentcells[ ][ =and numneighbors = dead cells with neighbors become alivenextcells[ ][ '#elseeverything else dies or stays deadnextcells[ ][ytime sleep( add -second pause to reduce flickering let' look at this code line by linestarting at the top conway' game of life import randomtimecopy width height lists
2,590
random randint()time sleep()and copy deepcopy(functions create list of list for the cellsnextcells [for in range(width)column [create new column for in range(height)if random randint( = column append('#'add living cell elsecolumn append('add dead cell nextcells append(columnnextcells is list of column lists the very first step of our cellular automata will be completely random we need to create list of lists data structure to store the '#and strings that represent living or dead celland their place in the list of lists reflects their position on the screen the inner lists each represent column of cells the random randint( call gives an even / chance between the cell starting off alive or dead we put this list of lists in variable called nextcellsbecause the first step in our main program loop will be to copy nextcells into currentcells for our list of lists data structurethe -coordinates start at on the left and increase going rightwhile the -coordinates start at at the top and increase going down so nextcells[ ][ will represent the cell at the top left of the screenwhile nextcells[ ][ represents the cell to the right of that cell and nextcells[ ][ represents the cell beneath it while truemain program loop print('\ \ \ \ \ 'separate each step with newlines currentcells copy deepcopy(nextcellseach iteration of our main program loop will be single step of our cellular automata on each stepwe'll copy nextcells to currentcellsprint currentcells on the screenand then use the cells in currentcells to calculate the cells in nextcells print currentcells on the screenfor in range(height)for in range(width)print(currentcells[ ][ ]end=''print the or space print(print newline at the end of the row these nested for loops ensure that we print full row of cells to the screenfollowed by newline character at the end of the row we repeat this for each row in nextcells calculate the next step' cells based on current step' cellsfor in range(width)for in range(height)get neighboring coordinates
2,591
leftcoord ( width rightcoord ( width abovecoord ( height belowcoord ( height nextwe need to use two nested for loops to calculate each cell for the next step the living or dead state of the cell depends on the neighborsso let' first calculate the index of the cells to the leftrightaboveand below the current xand -coordinates the mod operator performs "wraparound the left neighbor of cell in the leftmost column would be or - to wrap this around to the rightmost column' index we calculate ( width since width is this expression evaluates to this mod-wraparound technique works for the rightaboveand below neighbors as well count number of living neighborsnumneighbors if currentcells[leftcoord][abovecoord='#'numneighbors + top-left neighbor is alive if currentcells[ ][abovecoord='#'numneighbors + top neighbor is alive if currentcells[rightcoord][abovecoord='#'numneighbors + top-right neighbor is alive if currentcells[leftcoord][ ='#'numneighbors + left neighbor is alive if currentcells[rightcoord][ ='#'numneighbors + right neighbor is alive if currentcells[leftcoord][belowcoord='#'numneighbors + bottom-left neighbor is alive if currentcells[ ][belowcoord='#'numneighbors + bottom neighbor is alive if currentcells[rightcoord][belowcoord='#'numneighbors + bottom-right neighbor is alive to decide if the cell at nextcells[ ][yshould be living or deadwe need to count the number of living neighbors currentcells[ ][yhas this series of if statements checks each of the eight neighbors of this celland adds to numneighbors for each living one set cell based on conway' game of life rulesif currentcells[ ][ ='#and (numneighbors = or numneighbors = )living cells with or neighbors stay alivenextcells[ ][ '#elif currentcells[ ][ =and numneighbors = dead cells with neighbors become alivenextcells[ ][ '#elseeverything else dies or stays deadnextcells[ ][ytime sleep( add -second pause to reduce flickering lists
2,592
currentcells[ ][ ]we can set nextcells[ ][yto either '#or after we loop over every possible xand -coordinatethe program takes -second pause by calling time sleep( then the program execution goes back to the start of the main program loop to continue with the next step several patterns have been discovered with names such as "glider,"propeller,or "heavyweight spaceship the glider patternpictured in figure - results in pattern that "movesdiagonally every four steps you can create single glider by replacing this line in our conway py programif random randint( = with this lineif (xyin (( )( )( )( )( ))you can find out more about the intriguing devices made using conway' game of life by searching the web and you can find other shorttext-based python programs like this one at summary lists are useful data types since they allow you to write code that works on modifiable number of values in single variable later in this bookyou will see programs using lists to do things that would be difficult or impossible to do without them lists are sequence data type that is mutablemeaning that their contents can change tuples and stringsthough also sequence data typesare immutable and cannot be changed variable that contains tuple or string value can be overwritten with new tuple or string valuebut this is not the same thing as modifying the existing value in place--likesaythe append(or remove(methods do on lists variables do not store list values directlythey store references to lists this is an important distinction when you are copying variables or passing lists as arguments in function calls because the value that is being copied is the list referencebe aware that any changes you make to the list might impact another variable in your program you can use copy(or deepcopy(if you want to make changes to list in one variable without modifying the original list practice questions what is []how would you assign the value 'helloas the third value in list stored in variable named spam(assume spam contains [
2,593
' '' '' ' what does spam[int(int(' / )evaluate towhat does spam[- evaluate towhat does spam[: evaluate tofor the following three questionslet' say bacon contains the list [ 'cat' 'cat'true what does bacon index('cat'evaluate to what does bacon append( make the list value in bacon look like what does bacon remove('cat'make the list value in bacon look like what are the operators for list concatenation and list replication what is the difference between the append(and insert(list methods what are two ways to remove values from list name few ways that list values are similar to string values what is the difference between lists and tuples how do you type the tuple value that has just the integer value in it how can you get the tuple form of list valuehow can you get the list form of tuple value variables that "containlist values don' actually contain lists directly what do they contain instead what is the difference between copy copy(and copy deepcopy()practice projects for practicewrite programs to do the following tasks comma code say you have list value like thisspam ['apples''bananas''tofu''cats'write function that takes list value as an argument and returns string with all the items separated by comma and spacewith and inserted before the last item for examplepassing the previous spam list to the function would return 'applesbananastofuand catsbut your function should be able to work with any list value passed to it be sure to test the case where an empty list [is passed to your function coin flip streaks for this exercisewe'll try doing an experiment if you flip coin times and write down an "hfor each heads and "tfor each tailsyou'll create list that looks like " if you ask human to make lists
2,594
but isn' mathematically random human will almost never write down streak of six heads or six tails in roweven though it is highly likely to happen in truly random coin flips humans are predictably bad at being random write program to find out how often streak of six heads or streak of six tails comes up in randomly generated list of heads and tails your program breaks up the experiment into two partsthe first part generates list of randomly selected 'headsand 'tailsvaluesand the second part checks if there is streak in it put all of this code in loop that repeats the experiment , times so we can find out what percentage of the coin flips contains streak of six heads or tails in row as hintthe function call random randint( will return value of the time and value the other of the time you can start with the following templateimport random numberofstreaks for experimentnumber in range( )code that creates list of 'headsor 'tailsvalues code that checks if there is streak of heads or tails in row print('chance of streak% %%(numberofstreaks )of coursethis is only an estimatebut , is decent sample size some knowledge of mathematics could give you the exact answer and save you the trouble of writing programbut programmers are notoriously bad at math character picture grid say you have list of lists where each value in the inner lists is one-character stringlike thisgrid [['''''']['' '' ''''][' '' '' '' '''][' '' '' '' '' '']['' '' '' '' '' '][' '' '' '' '' ''][' '' '' '' ''']['' '' '''']['''''']think of grid[ ][yas being the character at the xand -coordinates of "picturedrawn with text characters the ( origin is in the upperleft cornerthe -coordinates increase going rightand the -coordinates increase going down
2,595
the image oo oo ooooooo ooooooo ooooo ooo hintyou will need to use loop in loop in order to print grid[ ][ ]then grid[ ][ ]then grid[ ][ ]and so onup to grid[ ][ this will finish the first rowso then print newline then your program should print grid[ ][ ]then grid[ ][ ]then grid[ ][ ]and so on the last thing your program will print is grid[ ][ alsoremember to pass the end keyword argument to print(if you don' want newline printed automatically after each print(call lists
2,596
dictionaries and ruc ur ing data in this will cover the dictionary data typewhich provides flexible way to access and organize data thencombining dictionaries with your knowledge of lists from the previous you'll learn how to create data structure to model tic-tac-toe board the dictionary data type like lista dictionary is mutable collection of many values but unlike indexes for listsindexes for dictionaries can use many different data typesnot just integers indexes for dictionaries are called keysand key with its associated value is called key-value pair in codea dictionary is typed with braces{enter the following into the interactive shellmycat {'size''fat''color''gray''disposition''loud'
2,597
'size''color'and 'dispositionthe values for these keys are 'fat''gray'and 'loud'respectively you can access these values through their keysmycat['size''fat'my cat has mycat['color'fur 'my cat has gray fur dictionaries can still use integer values as keysjust like lists use integers for indexesbut they do not have to start at and can be any number spam { 'luggage combination' 'the answer'dictionaries vs lists unlike listsitems in dictionaries are unordered the first item in list named spam would be spam[ but there is no "firstitem in dictionary while the order of items matters for determining whether two lists are the sameit does not matter in what order the key-value pairs are typed in dictionary enter the following into the interactive shellspam ['cats''dogs''moose'bacon ['dogs''moose''cats'spam =bacon false eggs {'name''zophie''species''cat''age'' 'ham {'species''cat''age'' ''name''zophie'eggs =ham true because dictionaries are not orderedthey can' be sliced like lists trying to access key that does not exist in dictionary will result in keyerror error messagemuch like list' "out-of-rangeindexerror error message enter the following into the interactive shelland notice the error message that shows up because there is no 'colorkeyspam {'name''zophie''age' spam['color'traceback (most recent call last)file ""line in spam['color'keyerror'color
2,598
values for the keys allows you to organize your data in powerful ways say you wanted your program to store data about your friendsbirthdays you can use dictionary with the names as keys and the birthdays as values open new file editor window and enter the following code save it as birthdays py birthdays {'alice''apr ''bob''dec ''carol''mar 'while trueprint('enter name(blank to quit)'name input(if name =''break if name in birthdaysprint(birthdays[nameis the birthday of nameelseprint(' do not have birthday information for nameprint('what is their birthday?'bday input(birthdays[namebday print('birthday database updated 'you can view the execution of this program at you create an initial dictionary and store it in birthdays you can see if the entered name exists as key in the dictionary with the in keyword just as you did for lists if the name is in the dictionaryyou access the associated value using square brackets if notyou can add it using the same square bracket syntax combined with the assignment operator when you run this programit will look like thisenter name(blank to quitalice apr is the birthday of alice enter name(blank to quiteve do not have birthday information for eve what is their birthdaydec birthday database updated enter name(blank to quiteve dec is the birthday of eve enter name(blank to quitof courseall the data you enter in this program is forgotten when the program terminates you'll learn how to save data to files on the hard drive in dictionaries and structuring data
2,599
while they're still not ordered and have no "firstkey-value pairdictionaries in python and later will remember the insertion order of their key-value pairs if you create sequence value from them for examplenotice the order of items in the lists made from the eggs and ham dictionaries matches the order in which they were enteredeggs {'name''zophie''species''cat''age'' 'list(eggs['name''species''age'ham {'species''cat''age'' ''name''zophie'list(ham['species''age''name'the dictionaries are still unorderedas you can' access items in them using integer indexes like eggs[ or ham[ you shouldn' rely on this behavioras dictionaries in older versions of python don' remember the insertion order of key-value pairs for examplenotice how the list doesn' match the insertion order of the dictionary' key-value pairs when run this code in python spam {spam['first key''valuespam['second key''valuespam['third key''valuelist(spam['first key''third key''second key'the keys()values()and items(methods there are three dictionary methods that will return list-like values of the dictionary' keysvaluesor both keys and valueskeys()values()and items(the values returned by these methods are not true liststhey cannot be modified and do not have an append(method but these data types (dict_keysdict_valuesand dict_itemsrespectivelycan be used in for loops to see how these methods workenter the following into the interactive shellspam {'color''red''age' for in spam values()print(vred