id
int64
0
25.6k
text
stringlengths
0
4.59k
100
as you've seen many times already the line at checks whether the value of car is 'bmwusing double equal sign (==this equality operator returns true if the values on the left and right side of the operator matchand false if they don' match the values in this example matchso python returns true when the value of car is anything other than 'bmw'this test returns falseu car 'audiv car ='bmwfalse single equal sign is really statementyou might read the code at as "set the value of car equal to 'audion the other handa double equal signlike the one at vasks question"is the value of car equal to 'bmw'?most programming languages use equal signs in this way ignoring case when checking for equality testing for equality is case sensitive in python for exampletwo values with different capitalization are not considered equalcar 'audicar ='audifalse if case mattersthis behavior is advantageous but if case doesn' matter and instead you just want to test the value of variableyou can convert the variable' value to lowercase before doing the comparisoncar 'audicar lower(='auditrue this test would return true no matter how the value 'audiis formatted because the test is now case insensitive the lower(function doesn' change the value that was originally stored in carso you can do this kind of comparison without affecting the original variableu car 'audiv car lower(='auditrue car 'audiat we store the capitalized string 'audiin the variable car at we convert the value of car to lowercase and compare the lowercase value if statements
101
we can see that the value stored in car has not been affected by the conditional test websites enforce certain rules for the data that users enter in manner similar to this for examplea site might use conditional test like this to ensure that every user has truly unique usernamenot just variation on the capitalization of another person' username when someone submits new usernamethat new username is converted to lowercase and compared to the lowercase versions of all existing usernames during this checka username like 'johnwill be rejected if any variation of 'johnis already in use checking for inequality when you want to determine whether two values are not equalyou can combine an exclamation point and an equal sign (!=the exclamation point represents notas it does in many programming languages let' use another if statement to examine how to use the inequality operator we'll store requested pizza topping in variable and then print message if the person did not order anchoviestoppings py requested_topping 'mushroomsu if requested_topping !'anchovies'print("hold the anchovies!"the line at compares the value of requested_topping to the value 'anchoviesif these two values do not matchpython returns true and executes the code following the if statement if the two values matchpython returns false and does not run the code following the if statement because the value of requested_topping is not 'anchovies'the print statement is executedhold the anchoviesmost of the conditional expressions you write will test for equalitybut sometimes you'll find it more efficient to test for inequality numerical comparisons testing numerical values is pretty straightforward for examplethe following code checks whether person is years oldage age = true
102
following code prints message if the given answer is not correctmagic_ number py answer if answer ! print("that is not the correct answer please try again!"the conditional test at passesbecause the value of answer ( is not equal to because the test passesthe indented code block is executedthat is not the correct answer please try againyou can include various mathematical comparisons in your conditional statements as wellsuch as less thanless than or equal togreater thanand greater than or equal toage age true age < true age false age > false each mathematical comparison can be used as part of an if statementwhich can help you detect the exact conditions of interest checking multiple conditions you may want to check multiple conditions at the same time for examplesometimes you might need two conditions to be true to take an action other times you might be satisfied with just one condition being true the keywords and and or can help you in these situations using and to check multiple conditions to check whether two conditions are both true simultaneouslyuse the keyword and to combine the two conditional testsif each test passesthe overall expression evaluates to true if either test fails or if both tests failthe expression evaluates to false for exampleyou can check whether two people are both over using the following testu age_ age_ age_ > and age_ > false if statements
103
age_ > and age_ > true at we define two agesage_ and age_ at we check whether both ages are or older the test on the left passesbut the test on the right failsso the overall conditional expression evaluates to false at we change age_ to the value of age_ is now greater than so both individual tests passcausing the overall conditional expression to evaluate as true to improve readabilityyou can use parentheses around the individual testsbut they are not required if you use parenthesesyour test would look like this(age_ > and (age_ > using or to check multiple conditions the keyword or allows you to check multiple conditions as wellbut it passes when either or both of the individual tests pass an or expression fails only when both individual tests fail let' consider two ages againbut this time we'll look for only one person to be over age_ age_ age_ > or age_ > true age_ age_ > or age_ > false we start with two age variables again at because the test for age_ at passesthe overall expression evaluates to true we then lower age_ to in the test at wboth tests now fail and the overall expression evaluates to false checking whether value is in list sometimes it' important to check whether list contains certain value before taking an action for exampleyou might want to check whether new username already exists in list of current usernames before completing someone' registration on website in mapping projectyou might want to check whether submitted location already exists in list of known locations to find out whether particular value is already in listuse the keyword in let' consider some code you might write for pizzeria we'll make list of toppings customer has requested for pizza and then check whether certain toppings are in the list
104
'mushroomsin requested_toppings true 'pepperoniin requested_toppings false at and vthe keyword in tells python to check for the existence of 'mushroomsand 'pepperoniin the list requested_toppings this technique is quite powerful because you can create list of essential valuesand then easily check whether the value you're testing matches one of the values in the list checking whether value is not in list other timesit' important to know if value does not appear in list you can use the keyword not in this situation for exampleconsider list of users who are banned from commenting in forum you can check whether user has been banned before allowing that person to submit commentbanned_ users py banned_users ['andrew''carolina''david'user 'marieu if user not in banned_usersprint(user title("you can post response if you wish "the line at reads quite clearly if the value of user is not in the list banned_userspython returns true and executes the indented line the user 'marieis not in the list banned_usersso she sees message inviting her to post responsemarieyou can post response if you wish boolean expressions as you learn more about programmingyou'll hear the term boolean expression at some point boolean expression is just another name for conditional test boolean value is either true or falsejust like the value of conditional expression after it has been evaluated boolean values are often used to keep track of certain conditionssuch as whether game is running or whether user can edit certain content on websitegame_active true can_edit false boolean values provide an efficient way to track the state of program or particular condition that is important in your program if statements
105
- conditional testswrite series of conditional tests print statement describing each test and your prediction for the results of each test your code should look something like thiscar 'subaruprint("is car ='subaru' predict true "print(car ='subaru'print("\nis car ='audi' predict false "print(car ='audi'look closely at your resultsand make sure you understand why each line evaluates to true or false create at least tests have at least tests evaluate to true and another tests evaluate to false - more conditional testsyou don' have to limit the number of tests you create to if you want to try more comparisonswrite more tests and add them to conditional_tests py have at least one true and one false result for each of the followingtests for equality and inequality with strings tests using the lower(function numerical tests involving equality and inequalitygreater than and less thangreater than or equal toand less than or equal to tests using the and keyword and the or keyword test whether an item is in list test whether an item is not in list if statements when you understand conditional testsyou can start writing if statements several different kinds of if statements existand your choice of which to use depends on the number of conditions you need to test you saw several examples of if statements in the discussion about conditional testsbut now let' dig deeper into the topic simple if statements the simplest kind of if statement has one test and one actionif conditional_testdo something
106
action in the indented block following the test if the conditional test evaluates to truepython executes the code following the if statement if the test evaluates to falsepython ignores the code following the if statement let' say we have variable representing person' ageand we want to know if that person is old enough to vote the following code tests whether the person can votevoting py age if age > print("you are old enough to vote!"at python checks to see whether the value in age is greater than or equal to it isso python executes the indented print statement at vyou are old enough to voteindentation plays the same role in if statements as it did in for loops all indented lines after an if statement will be executed if the test passesand the entire block of indented lines will be ignored if the test does not pass you can have as many lines of code as you want in the block following the if statement let' add another line of output if the person is old enough to voteasking if the individual has registered to vote yetage if age > print("you are old enough to vote!"print("have you registered to vote yet?"the conditional test passesand both print statements are indentedso both lines are printedyou are old enough to votehave you registered to vote yetif the value of age is less than this program would produce no output if-else statements oftenyou'll want to take one action when conditional test passes and different action in all other cases python' ifelse syntax makes this possible an ifelse block is similar to simple if statementbut the else statement allows you to define an action or set of actions that are executed when the conditional test fails if statements
107
enough to votebut this time we'll add message for anyone who is not old enough to voteage if age > print("you are old enough to vote!"print("have you registered to vote yet?" elseprint("sorryyou are too young to vote "print("please register to vote as soon as you turn !"if the conditional test at passesthe first block of indented print statements is executed if the test evaluates to falsethe else block at is executed because age is less than this timethe conditional test fails and the code in the else block is executedsorryyou are too young to vote please register to vote as soon as you turn this code works because it has only two possible situations to evaluatea person is either old enough to vote or not old enough to vote the ifelse structure works well in situations in which you want python to always execute one of two possible actions in simple if-else chain like thisone of the two actions will always be executed the if-elif-else chain oftenyou'll need to test more than two possible situationsand to evaluate these you can use python' ifelifelse syntax python executes only one block in an ifelifelse chain it runs each conditional test in order until one passes when test passesthe code following that test is executed and python skips the rest of the tests many real-world situations involve more than two possible conditions for exampleconsider an amusement park that charges different rates for different age groupsadmission for anyone under age is free admission for anyone between the ages of and is $ admission for anyone age or older is $ how can we use an if statement to determine person' admission ratethe following code tests for the age group of person and then prints an admission price messageamusement_ park py age if age print("your admission cost is $ "
108
print("your admission cost is $ " elseprint("your admission cost is $ "the if test at tests whether person is under years old if the test passesan appropriate message is printed and python skips the rest of the tests the elif line at is really another if testwhich runs only if the previous test failed at this point in the chainwe know the person is at least years old because the first test failed if the person is less than an appropriate message is printed and python skips the else block if both the if and elif tests failpython runs the code in the else block at in this example the test at evaluates to falseso its code block is not executed howeverthe second test evaluates to true ( is less than so its code is executed the output is one sentenceinforming the user of the admission costyour admission cost is $ any age greater than would cause the first two tests to fail in these situationsthe else block would be executed and the admission price would be $ rather than printing the admission price within the ifelifelse blockit would be more concise to set just the price inside the ifelifelse chain and then have simple print statement that runs after the chain has been evaluatedage if age price elif age price elsew price print("your admission cost is $str(price"the lines at uvand set the value of price according to the person' ageas in the previous example after the price is set by the ifelifelse chaina separate unindented print statement uses this value to display message reporting the person' admission price this code produces the same output as the previous examplebut the purpose of the ifelifelse chain is narrower instead of determining price and displaying messageit simply determines the admission price in addition to being more efficientthis revised code is easier to modify than the original approach to change the text of the output messageyou would need to change only one print statement rather than three separate print statements if statements
109
you can use as many elif blocks in your code as you like for exampleif the amusement park were to implement discount for seniorsyou could add one more conditional test to the code to determine whether someone qualified for the senior discount let' say that anyone or older pays half the regular admissionor $ age if age price elif age price elif age price elseprice print("your admission cost is $str(price"most of this code is unchanged the second elif block at now checks to make sure person is less than age before assigning them the full admission rate of $ notice that the value assigned in the else block at needs to be changed to $ because the only ages that make it to this block are people or older omitting the else block python does not require an else block at the end of an ifelif chain some times an else block is usefulsometimes it is clearer to use an additional elif statement that catches the specific condition of interestage if age price elif age price elif age price elif age > price print("your admission cost is $str(price"the extra elif block at assigns price of $ when the person is or olderwhich is bit clearer than the general else block with this changeevery block of code must pass specific test in order to be executed
110
wasn' matched by specific if or elif testand that can sometimes include invalid or even malicious data if you have specific final condition you are testing forconsider using final elif block and omit the else block as resultyou'll gain extra confidence that your code will run only under the correct conditions testing multiple conditions the ifelifelse chain is powerfulbut it' only appropriate to use when you just need one test to pass as soon as python finds one test that passesit skips the rest of the tests this behavior is beneficialbecause it' efficient and allows you to test for one specific condition howeversometimes it' important to check all of the conditions of interest in this caseyou should use series of simple if statements with no elif or else blocks this technique makes sense when more than one condition could be trueand you want to act on every condition that is true let' reconsider the pizzeria example if someone requests two-topping pizzayou'll need to be sure to include both toppings on their pizzatoppings py requested_toppings ['mushrooms''extra cheese' if 'mushroomsin requested_toppingsprint("adding mushrooms " if 'pepperoniin requested_toppingsprint("adding pepperoni " if 'extra cheesein requested_toppingsprint("adding extra cheese "print("\nfinished making your pizza!"we start at with list containing the requested toppings the if statement at checks to see whether the person requested mushrooms on their pizza if soa message is printed confirming that topping the test for pepperoni at is another simple if statementnot an elif or else statementso this test is run regardless of whether the previous test passed or not the code at checks whether extra cheese was requested regardless of the results from the first two tests these three independent tests are executed every time this program is run because every condition in this example is evaluatedboth mushrooms and extra cheese are added to the pizzaadding mushrooms adding extra cheese finished making your pizzaif statements
111
because the code would stop running after only one test passes here' what that would look likerequested_toppings ['mushrooms''extra cheese'if 'mushroomsin requested_toppingsprint("adding mushrooms "elif 'pepperoniin requested_toppingsprint("adding pepperoni "elif 'extra cheesein requested_toppingsprint("adding extra cheese "print("\nfinished making your pizza!"the test for 'mushroomsis the first test to passso mushrooms are added to the pizza howeverthe values 'extra cheeseand 'pepperoniare never checkedbecause python doesn' run any tests beyond the first test that passes in an if-elif-else chain the customer' first topping will be addedbut all of their other toppings will be missedadding mushrooms finished making your pizzain summaryif you want only one block of code to runuse an ifelifelse chain if more than one block of code needs to runuse series of independent if statements try it yourse lf - alien colors # imagine an alien was just shot down in game create variable called alien_color and assign it value of 'green''yellow'or 'redwrite an if statement to test whether the alien' color is green if it isprint message that the player just earned points write one version of this program that passes the if test and another that fails (the version that fails will have no output - alien colors # choose color for an alien as you did in exercise - and write an ifelse chain if the alien' color is greenprint statement that the player just earned points for shooting the alien if the alien' color isn' greenprint statement that the player just earned points write one version of this program that runs the if block and another that runs the else block
112
if the alien is greenprint message that the player earned points if the alien is yellowprint message that the player earned points if the alien is redprint message that the player earned points write three versions of this programmaking sure each message is printed for the appropriate color alien - stages of lifewrite an ifelifelse chain that determines person' stage of life set value for the variable ageand thenif the person is less than years oldprint message that the person is baby if the person is at least years old but less than print message that the person is toddler if the person is at least years old but less than print message that the person is kid if the person is at least years old but less than print message that the person is teenager if the person is at least years old but less than print message that the person is an adult if the person is age or olderprint message that the person is an elder - favorite fruitmake list of your favorite fruitsand then write series of independent if statements that check for certain fruits in your list make list of your three favorite fruits and call it favorite_fruits write five if statements each should check whether certain kind of fruit is in your list if the fruit is in your listthe if block should print statementsuch as you really like bananasusing if statements with lists you can do some interesting work when you combine lists and if statements you can watch for special values that need to be treated differently than other values in the list you can manage changing conditions efficientlysuch as the availability of certain items in restaurant throughout shift you can also begin to prove that your code works as you expect it to in all possible situations if statements
113
this began with simple example that showed how to handle special value like 'bmw'which needed to be printed in different format than other values in the list now that you have basic understanding of conditional tests and if statementslet' take closer look at how you can watch for special values in list and handle those values appropriately let' continue with the pizzeria example the pizzeria displays message whenever topping is added to your pizzaas it' being made the code for this action can be written very efficiently by making list of toppings the customer has requested and using loop to announce each topping as it' added to the pizzatoppings py requested_toppings ['mushrooms''green peppers''extra cheese'for requested_topping in requested_toppingsprint("adding requested_topping "print("\nfinished making your pizza!"the output is straightforward because this code is just simple for loopadding mushrooms adding green peppers adding extra cheese finished making your pizzabut what if the pizzeria runs out of green peppersan if statement inside the for loop can handle this situation appropriatelyrequested_toppings ['mushrooms''green peppers''extra cheese'for requested_topping in requested_toppingsif requested_topping ='green peppers'print("sorrywe are out of green peppers right now " elseprint("adding requested_topping " print("\nfinished making your pizza!"this time we check each requested item before adding it to the pizza the code at checks to see if the person requested green peppers if sowe display message informing them why they can' have green peppers the else block at ensures that all other toppings will be added to the pizza
114
adding mushrooms sorrywe are out of green peppers right now adding extra cheese finished making your pizzachecking that list is not empty we've made simple assumption about every list we've worked with so farwe've assumed that each list has at least one item in it soon we'll let users provide the information that' stored in listso we won' be able to assume that list has any items in it each time loop is run in this situationit' useful to check whether list is empty before running for loop as an examplelet' check whether the list of requested toppings is empty before building the pizza if the list is emptywe'll prompt the user and make sure they want plain pizza if the list is not emptywe'll build the pizza just as we did in the previous examplesu requested_toppings [ if requested_toppingsfor requested_topping in requested_toppingsprint("adding requested_topping "print("\nfinished making your pizza!" elseprint("are you sure you want plain pizza?"this time we start out with an empty list of requested toppings at instead of jumping right into for loopwe do quick check at when the name of list is used in an if statementpython returns true if the list contains at least one iteman empty list evaluates to false if requested_toppings passes the conditional testwe run the same for loop we used in the previous example if the conditional test failswe print message asking the customer if they really want plain pizza with no toppings the list is empty in this caseso the output asks if the user really wants plain pizzaare you sure you want plain pizzaif the list is not emptythe output will show each requested topping being added to the pizza if statements
115
people will ask for just about anythingespecially when it comes to pizza toppings what if customer actually wants french fries on their pizzayou can use lists and if statements to make sure your input makes sense before you act on it let' watch out for unusual topping requests before we build pizza the following example defines two lists the first is list of available toppings at the pizzeriaand the second is the list of toppings that the user has requested this timeeach item in requested_toppings is checked against the list of available toppings before it' added to the pizzau available_toppings ['mushrooms''olives''green peppers''pepperoni''pineapple''extra cheese' requested_toppings ['mushrooms''french fries''extra cheese' for requested_topping in requested_toppingsx if requested_topping in available_toppingsprint("adding requested_topping " elseprint("sorrywe don' have requested_topping "print("\nfinished making your pizza!"at we define list of available toppings at this pizzeria note that this could be tuple if the pizzeria has stable selection of toppings at vwe make list of toppings that customer has requested note the unusual request'french friesat we loop through the list of requested toppings inside the loopwe first check to see if each requested topping is actually in the list of available toppings if it iswe add that topping to the pizza if the requested topping is not in the list of available toppingsthe else block will run the else block prints message telling the user which toppings are unavailable this code syntax produces cleaninformative outputadding mushrooms sorrywe don' have french fries adding extra cheese finished making your pizzain just few lines of codewe've managed real-world situation pretty effectively
116
- hello adminmake list of five or more usernamesincluding the name 'adminimagine you are writing code that will print greeting to each user after they log in to website loop through the listand print greeting to each userif the username is 'admin'print special greetingsuch as hello adminwould you like to see status reportotherwiseprint generic greetingsuch as hello ericthank you for logging in again - no usersadd an if test to hello_admin py to make sure the list of users is not empty if the list is emptyprint the message we need to find some usersremove all of the usernames from your listand make sure the correct message is printed - checking usernamesdo the following to create program that simulates how websites ensure that everyone has unique username make list of five or more usernames called current_users make another list of five usernames called new_users make sure one or two of the new usernames are also in the current_users list loop through the new_users list to see if each new username has already been used if it hasprint message that the person will need to enter new username if username has not been usedprint message saying that the username is available make sure your comparison is case insensitive if 'johnhas been used'johnshould not be accepted - ordinal numbersordinal numbers indicate their position in listsuch as st or nd most ordinal numbers end in thexcept and store the numbers through in list loop through the list use an ifelifelse chain inside the loop to print the proper ordinal ending for each number your output should read " st nd rd th th th th th th"and each result should be on separate line if statements
117
in every example in this you've seen good styling habits the only recommendation pep provides for styling conditional tests is to use single space around comparison operatorssuch as ==>=<for exampleif age is better thanif age< such spacing does not affect the way python interprets your codeit just makes your code easier for you and others to read try it yourse lf - styling if statementsreview the programs you wrote in this and make sure you styled your conditional tests appropriately - your ideasat this pointyou're more capable programmer than you were when you started this book now that you have better sense of how real-world situations are modeled in programsyou might be thinking of some problems you could solve with your own programs record any new ideas you have about problems you might want to solve as your programming skills continue to improve consider games you might want to writedata sets you might want to exploreand web applications you' like to create summary in this you learned how to write conditional testswhich always evaluate to true or false you learned to write simple if statementsifelse chainsand ifelifelse chains you began using these structures to identify particular conditions you needed to test and to know when those conditions have been met in your programs you learned to handle certain items in list differently than all other items while continuing to utilize the efficiency of for loop you also revisited python' style recommendations to ensure that your increasingly complex programs are still relatively easy to read and understand in you'll learn about python' dictionaries dictionary is similar to listbut it allows you to connect pieces of information you'll learn to build dictionariesloop through themand use them in combination with lists and if statements learning about dictionaries will enable you to model an even wider variety of real-world situations
118
ic in this you'll learn how to use python' dictionarieswhich allow you to connect pieces of related information you'll learn how to access the information once it' in dictionary and how to modify that information because dictionaries can store an almost limitless amount of informationi'll show you how to loop through the data in dictionary additionallyyou'll learn to nest dictionaries inside listslists inside dictionariesand even dictionaries inside other dictionaries understanding dictionaries allows you to model variety of real-world objects more accurately you'll be able to create dictionary representing person and then store as much information as you want about that person you can store their nameagelocationprofessionand any other aspect of person you can describe you'll be able to store any two kinds of information that can be matched upsuch as list of words and their meaningsa list of people' names and their favorite numbersa list of mountains and their elevationsand so forth
119
consider game featuring aliens that can have different colors and point values this simple dictionary stores information about particular alienalien py alien_ {'color''green''points' print(alien_ ['color']print(alien_ ['points']the dictionary alien_ stores the alien' color and point value the two print statements access and display that informationas shown heregreen as with most new programming conceptsusing dictionaries takes practice once you've worked with dictionaries for bit you'll soon see how effectively they can model real-world situations working with dictionaries dictionary in python is collection of key-value pairs each key is connected to valueand you can use key to access the value associated with that key key' value can be numbera stringa listor even another dictionary in factyou can use any object that you can create in python as value in dictionary in pythona dictionary is wrapped in braces{}with series of keyvalue pairs inside the bracesas shown in the earlier examplealien_ {'color''green''points' key-value pair is set of values associated with each other when you provide keypython returns the value associated with that key every key is connected to its value by colonand individual key-value pairs are separated by commas you can store as many key-value pairs as you want in dictionary the simplest dictionary has exactly one key-value pairas shown in this modified version of the alien_ dictionaryalien_ {'color''green'this dictionary stores one piece of information about alien_ namely the alien' color the string 'coloris key in this dictionaryand its associated value is 'green
120
to get the value associated with keygive the name of the dictionary and then place the key inside set of square bracketsas shown herealien_ {'color''green'print(alien_ ['color']this returns the value associated with the key 'colorfrom the dictionary alien_ green you can have an unlimited number of key-value pairs in dictionary for examplehere' the original alien_ dictionary with two key-value pairsalien_ {'color''green''points' now you can access either the color or the point value of alien_ if player shoots down this alienyou can look up how many points they should earn using code like thisalien_ {'color''green''points' new_points alien_ ['points' print("you just earned str(new_pointspoints!"once the dictionary has been definedthe code at pulls the value associated with the key 'pointsfrom the dictionary this value is then stored in the variable new_points the line at converts this integer value to string and prints statement about how many points the player just earnedyou just earned pointsif you run this code every time an alien is shot downthe alien' point value will be retrieved adding new key-value pairs dictionaries are dynamic structuresand you can add new key-value pairs to dictionary at any time for exampleto add new key-value pairyou would give the name of the dictionary followed by the new key in square brackets along with the new value let' add two new pieces of information to the alien_ dictionarythe alien' xand -coordinateswhich will help us display the alien in particular position on the screen let' place the alien on the left edge of the screen pixels down from the top because screen coordinates usually start at the upper-left corner of the screenwe'll place the alien on the left dictionaries
121
top by setting its -coordinate to positive as shown herealien_ {'color''green''points' print(alien_ alien_ ['x_position' alien_ ['y_position' print(alien_ we start by defining the same dictionary that we've been working with we then print this dictionarydisplaying snapshot of its information at we add new key-value pair to the dictionarykey 'x_positionand value we do the same for key 'y_positionat when we print the modified dictionarywe see the two additional key-value pairs{'color''green''points' {'color''green''points' 'y_position' 'x_position' the final version of the dictionary contains four key-value pairs the original two specify color and point valueand two more specify the alien' position notice that the order of the key-value pairs does not match the order in which we added them python doesn' care about the order in which you store each key-value pairit cares only about the connection between each key and its value starting with an empty dictionary it' sometimes convenientor even necessaryto start with an empty dictionary and then add each new item to it to start filling an empty dictionarydefine dictionary with an empty set of braces and then add each key-value pair on its own line for examplehere' how to build the alien_ dictionary using this approachalien_ {alien_ ['color''greenalien_ ['points' print(alien_ here we define an empty alien_ dictionaryand then add color and point values to it the result is the dictionary we've been using in previous examples{'color''green''points' typicallyyou'll use empty dictionaries when storing user-supplied data in dictionary or when you write code that generates large number of key-value pairs automatically
122
to modify value in dictionarygive the name of the dictionary with the key in square brackets and then the new value you want associated with that key for exampleconsider an alien that changes from green to yellow as game progressesalien_ {'color''green'print("the alien is alien_ ['color'"alien_ ['color''yellowprint("the alien is now alien_ ['color'"we first define dictionary for alien_ that contains only the alien' colorthen we change the value associated with the key 'colorto 'yellowthe output shows that the alien has indeed changed from green to yellowthe alien is green the alien is now yellow for more interesting examplelet' track the position of an alien that can move at different speeds we'll store value representing the alien' current speed and then use it to determine how far to the right the alien should movealien_ {'x_position' 'y_position' 'speed''medium'print("original -positionstr(alien_ ['x_position'])move the alien to the right determine how far to move the alien based on its current speed if alien_ ['speed'='slow'x_increment elif alien_ ['speed'='medium'x_increment elsethis must be fast alien x_increment the new position is the old position plus the increment alien_ ['x_position'alien_ ['x_position'x_increment print("new -positionstr(alien_ ['x_position'])we start by defining an alien with an initial position and positionand speed of 'mediumwe've omitted the color and point values for the sake of simplicitybut this example would work the same way if you included those key-value pairs as well we also print the original value of x_position to see how far the alien moves to the right at uan ifelifelse chain determines how far the alien should move to the right and stores this value in the variable x_increment if the alien' speed is 'slow'it moves one unit to the rightif the speed is 'medium'it moves two dictionaries
123
the increment has been calculatedit' added to the value of x_position at vand the result is stored in the dictionary' x_position because this is medium-speed alienits position shifts two units to the rightoriginal -position new -position this technique is pretty coolby changing one value in the alien' dictionaryyou can change the overall behavior of the alien for exampleto turn this medium-speed alien into fast alienyou would add the linealien_ ['speed'fast the ifelifelse block would then assign larger value to x_increment the next time the code runs removing key-value pairs when you no longer need piece of information that' stored in dictionaryyou can use the del statement to completely remove key-value pair all del needs is the name of the dictionary and the key that you want to remove for examplelet' remove the key 'pointsfrom the alien_ dictionary along with its valuealien_ {'color''green''points' print(alien_ del alien_ ['points'print(alien_ the line at tells python to delete the key 'pointsfrom the dictionary alien_ and to remove the value associated with that key as well the output shows that the key 'pointsand its value of are deleted from the dictionarybut the rest of the dictionary is unaffected{'color''green''points' {'color''green'note be aware that the deleted key-value pair is removed permanently dictionary of similar objects the previous example involved storing different kinds of information about one objectan alien in game you can also use dictionary to store one kind of information about many objects for examplesay you want to poll
124
is dictionary is useful for storing the results of simple polllike thisfavorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python'as you can seewe've broken larger dictionary into several lines each key is the name of person who responded to the polland each value is their language choice when you know you'll need more than one line to define dictionarypress enter after the opening brace then indent the next line one level (four spaces)and write the first key-value pairfollowed by comma from this point forward when you press enteryour text editor should automatically indent all subsequent key-value pairs to match the first key-value pair once you've finished defining the dictionaryadd closing brace on new line after the last key-value pair and indent it one level so it aligns with the keys in the dictionary it' good practice to include comma after the last key-value pair as wellso you're ready to add new key-value pair on the next line note most editors have some functionality that helps you format extended lists and dictionaries in similar manner to this example other acceptable ways to format long dictionaries are available as wellso you may see slightly different formatting in your editoror in other sources to use this dictionarygiven the name of person who took the pollyou can easily look up their favorite languagefavorite_ languages py favorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python' print("sarah' favorite language is favorite_languages['sarah'title( "to see which language sarah chosewe ask for the value atfavorite_languages['sarah'this syntax is used in the print statement at vand the output shows sarah' favorite languagesarah' favorite language is dictionaries
125
over several lines the word print is shorter than most dictionary namesso it makes sense to include the first part of what you want to print right after the opening parenthesis choose an appropriate point at which to break what' being printedand add concatenation operator (+at the end of the first line press enter and then press tab to align all subsequent lines at one indentation level under the print statement when you've finished composing your outputyou can place the closing parenthesis on the last line of the print block try it yourse lf - personuse dictionary to store information about person you know store their first namelast nameageand the city in which they live you should have keys such as first_namelast_nameageand city print each piece of information stored in your dictionary - favorite numbersuse dictionary to store people' favorite numbers think of five namesand use them as keys in your dictionary think of favorite number for each personand store each as value in your dictionary print each person' name and their favorite number for even more funpoll few friends and get some actual data for your program - glossarya python dictionary can be used to model an actual dictionary howeverto avoid confusionlet' call it glossary think of five programming words you've learned about in the previous use these words as the keys in your glossaryand store their meanings as values print each word and its meaning as neatly formatted output you might print the word followed by colon and then its meaningor print the word on one line and then print its meaning indented on second line use the newline character (\nto insert blank line between each word-meaning pair in your output looping through dictionary single python dictionary can contain just few key-value pairs or millions of pairs because dictionary can contain large amounts of datapython lets you loop through dictionary dictionaries can be used to store information in variety of waysthereforeseveral different ways exist to loop through them you can loop through all of dictionary' key-value pairsthrough its keysor through its values
126
before we explore the different approaches to loopinglet' consider new dictionary designed to store information about user on website the following dictionary would store one person' usernamefirst nameand last nameuser_ 'username''efermi''first''enrico''last''fermi'you can access any single piece of information about user_ based on what you've already learned in this but what if you wanted to see everything stored in this user' dictionaryto do soyou could loop through the dictionary using for loopuser py user_ 'username''efermi''first''enrico''last''fermi' for keyvalue in user_ items() print("\nkeykeyw print("valuevalueas shown at uto write for loop for dictionaryyou create names for the two variables that will hold the key and value in each key-value pair you can choose any names you want for these two variables this code would work just as well if you had used abbreviations for the variable nameslike thisfor kv in user_ items(the second half of the for statement at includes the name of the dictionary followed by the method items()which returns list of key-value pairs the for loop then stores each of these pairs in the two variables provided in the preceding examplewe use the variables to print each key vfollowed by the associated value the "\nin the first print statement ensures that blank line is inserted before each key-value pair in the outputkeylast valuefermi keyfirst valueenrico keyusername valueefermi dictionaries
127
which they were storedeven when looping through dictionary python doesn' care about the order in which key-value pairs are storedit tracks only the connections between individual keys and their values looping through all key-value pairs works particularly well for dictionaries like the favorite_languages py example on page which stores the same kind of information for many different keys if you loop through the favorite_languages dictionaryyou get the name of each person in the dictionary and their favorite programming language because the keys always refer to person' name and the value is always languagewe'll use the variables name and language in the loop instead of key and value this will make it easier to follow what' happening inside the loopfavorite_ languages py favorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python' for namelanguage in favorite_languages items() print(name title("' favorite language is language title("the code at tells python to loop through each key-value pair in the dictionary as it works through each pair the key is stored in the variable nameand the value is stored in the variable language these descriptive names make it much easier to see what the print statement at is doing nowin just few lines of codewe can display all of the information from the polljen' favorite language is python sarah' favorite language is phil' favorite language is python edward' favorite language is ruby this type of looping would work just as well if our dictionary stored the results from polling thousand or even million people looping through all the keys in dictionary the keys(method is useful when you don' need to work with all of the values in dictionary let' loop through the favorite_languages dictionary and print the names of everyone who took the pollfavorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python'
128
print(name title()the line at tells python to pull all the keys from the dictionary favorite_languages and store them one at time in the variable name the output shows the names of everyone who took the polljen sarah phil edward looping through the keys is actually the default behavior when looping through dictionaryso this code would have exactly the same output if you wrote for name in favorite_languagesrather than for name in favorite_languages keys()you can choose to use the keys(method explicitly if it makes your code easier to reador you can omit it if you wish you can access the value associated with any key you care about inside the loop by using the current key let' print message to couple of friends about the languages they chose we'll loop through the names in the dictionary as we did previouslybut when the name matches one of our friendswe'll display message about their favorite languagefavorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python' friends ['phil''sarah'for name in favorite_languages keys()print(name title() if name in friendsprint(hi name title(" see your favorite language is favorite_languages[nametitle("!"at we make list of friends that we want to print message to inside the loopwe print each person' name then at we check to see whether the name we are working with is in the list friends if it iswe print special greetingincluding reference to their language choice to access dictionaries
129
receive special messageedward phil hi phili see your favorite language is pythonsarah hi sarahi see your favorite language is cjen you can also use the keys(method to find out if particular person was polled this timelet' find out if erin took the pollfavorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python' if 'erinnot in favorite_languages keys()print("erinplease take our poll!"the keys(method isn' just for loopingit actually returns list of all the keysand the line at simply checks if 'erinis in this list because she' nota message is printed inviting her to take the pollerinplease take our polllooping through dictionary' keys in order dictionary always maintains clear connection between each key and its associated valuebut you never get the items from dictionary in any predictable order that' not problembecause you'll usually just want to obtain the correct value associated with each key one way to return items in certain order is to sort the keys as they're returned in the for loop you can use the sorted(function to get copy of the keys in orderfavorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python'for name in sorted(favorite_languages keys())print(name title("thank you for taking the poll "
130
the sorted(function around the dictionary keys(method this tells python to list all keys in the dictionary and sort that list before looping through it the output shows everyone who took the poll with the names displayed in orderedwardthank you for taking the poll jenthank you for taking the poll philthank you for taking the poll sarahthank you for taking the poll looping through all values in dictionary if you are primarily interested in the values that dictionary containsyou can use the values(method to return list of values without any keys for examplesay we simply want list of all languages chosen in our programming language poll without the name of the person who chose each languagefavorite_languages 'jen''python''sarah'' ''edward''ruby''phil''python'print("the following languages have been mentioned:"for language in favorite_languages values()print(language title()the for statement here pulls each value from the dictionary and stores it in the variable language when these values are printedwe get list of all chosen languagesthe following languages have been mentionedpython python ruby this approach pulls all the values from the dictionary without checking for repeats that might work fine with small number of valuesbut in poll with large number of respondentsthis would result in very repetitive list to see each language chosen without repetitionwe can use set set is similar to list except that each item in the set must be uniquefavorite_languages 'jen''python''sarah'' ''edward''ruby'dictionaries
131
print("the following languages have been mentioned:" for language in set(favorite_languages values())print(language title()when you wrap set(around list that contains duplicate itemspython identifies the unique items in the list and builds set from those items at we use set(to pull out the unique languages in favorite_languages values(the result is nonrepetitive list of languages that have been mentioned by people taking the pollthe following languages have been mentionedpython ruby as you continue learning about pythonyou'll often find built-in feature of the language that helps you do exactly what you want with your data try it yourse lf - glossary now that you know how to loop through dictionaryclean up the code from exercise - (page by replacing your series of print statements with loop that runs through the dictionary' keys and values when you're sure that your loop worksadd five more python terms to your glossary when you run your program againthese new words and meanings should automatically be included in the output - riversmake dictionary containing three major rivers and the country each river runs through one key-value pair might be 'nile''egyptuse loop to print sentence about each riversuch as the nile runs through egypt use loop to print the name of each river included in the dictionary use loop to print the name of each country included in the dictionary - pollinguse the code in favorite_languages py (page make list of people who should take the favorite languages poll include some names that are already in the dictionary and some that are not loop through the list of people who should take the poll if they have already taken the pollprint message thanking them for responding if they have not yet taken the pollprint message inviting them to take the poll
132
sometimes you'll want to store set of dictionaries in list or list of items as value in dictionary this is called nesting you can nest set of dictionaries inside lista list of items inside dictionaryor even dictionary inside another dictionary nesting is powerful featureas the following examples will demonstrate list of dictionaries the alien_ dictionary contains variety of information about one alienbut it has no room to store information about second alienmuch less screen full of aliens how can you manage fleet of aliensone way is to make list of aliens in which each alien is dictionary of information about that alien for examplethe following code builds list of three aliensaliens py alien_ {'color''green''points' alien_ {'color''yellow''points' alien_ {'color''red''points' aliens [alien_ alien_ alien_ for alien in aliensprint(alienwe first create three dictionarieseach representing different alien at we pack each of these dictionaries into list called aliens finallywe loop through the list and print out each alien{'color''green''points' {'color''yellow''points' {'color''red''points' more realistic example would involve more than three aliens with code that automatically generates each alien in the following example we use range(to create fleet of aliensmake an empty list for storing aliens aliens [make green aliens for alien_number in range( ) new_alien {'color''green''points' 'speed''slow' aliens append(new_alienshow the first aliensx for alien in aliens[: ]print(alienprint("show how many aliens have been created print("total number of aliensstr(len(aliens))dictionaries
133
will be created at range(returns set of numberswhich just tells python how many times we want the loop to repeat each time the loop runs we create new alien and then append each new alien to the list aliens at we use slice to print the first five aliensand then at we print the length of the list to prove we've actually generated the full fleet of aliens{'speed''slow''color''green''points' {'speed''slow''color''green''points' {'speed''slow''color''green''points' {'speed''slow''color''green''points' {'speed''slow''color''green''points' total number of aliens these aliens all have the same characteristicsbut python considers each one separate objectwhich allows us to modify each alien individually how might you work with set of aliens like thisimagine that one aspect of game has some aliens changing color and moving faster as the game progresses when it' time to change colorswe can use for loop and an if statement to change the color of aliens for exampleto change the first three aliens to yellowmedium-speed aliens worth points eachwe could do thismake an empty list for storing aliens aliens [make green aliens for alien_number in range ( , )new_alien {'color''green''points' 'speed''slow'aliens append(new_alienfor alien in aliens[ : ]if alien['color'='green'alien['color''yellowalien['speed''mediumalien['points' show the first aliensfor alien in aliens[ : ]print(alienprint("because we want to modify the first three alienswe loop through slice that includes only the first three aliens all of the aliens are green now but that won' always be the caseso we write an if statement to make sure
134
to 'yellow'the speed to 'medium'and the point value to as shown in the following output{'speed''medium''color''yellow''points' {'speed''medium''color''yellow''points' {'speed''medium''color''yellow''points' {'speed''slow''color''green''points' {'speed''slow''color''green''points' you could expand this loop by adding an elif block that turns yellow aliens into redfast-moving ones worth points each without showing the entire program againthat loop would look like thisfor alien in aliens[ : ]if alien['color'='green'alien['color''yellowalien['speed''mediumalien['points' elif alien['color'='yellow'alien['color''redalien['speed''fastalien['points' it' common to store number of dictionaries in list when each dictionary contains many kinds of information about one object for exampleyou might create dictionary for each user on websiteas we did in user py on page and store the individual dictionaries in list called users all of the dictionaries in the list should have an identical structure so you can loop through the list and work with each dictionary object in the same way list in dictionary rather than putting dictionary inside listit' sometimes useful to put list inside dictionary for exampleconsider how you might describe pizza that someone is ordering if you were to use only listall you could really store is list of the pizza' toppings with dictionarya list of toppings can be just one aspect of the pizza you're describing in the following exampletwo kinds of information are stored for each pizzaa type of crust and list of toppings the list of toppings is value associated with the key 'toppingsto use the items in the listwe give the name of the dictionary and the key 'toppings'as we would any value in the dictionary instead of returning single valuewe get list of toppingspizza py store information about pizza being ordered pizza 'crust''thick''toppings'['mushrooms''extra cheese']dictionaries
135
print("you ordered pizza['crust'"-crust pizza "with the following toppings:" for topping in pizza['toppings']print("\ttoppingwe begin at with dictionary that holds information about pizza that has been ordered one key in the dictionary is 'crust'and the associated value is the string 'thickthe next key'toppings'has list as its value that stores all requested toppings at we summarize the order before building the pizza to print the toppingswe write for loop to access the list of toppingswe use the key 'toppings'and python grabs the list of toppings from the dictionary the following output summarizes the pizza that we plan to buildyou ordered thick-crust pizza with the following toppingsmushrooms extra cheese you can nest list inside dictionary any time you want more than one value to be associated with single key in dictionary in the earlier example of favorite programming languagesif we were to store each person' responses in listpeople could choose more than one favorite language when we loop through the dictionarythe value associated with each person would be list of languages rather than single language inside the dictionary' for loopwe use another for loop to run through the list of languages associated with each personfavorite_ favorite_languages languages py 'jen'['python''ruby']'sarah'[' ']'edward'['ruby''go']'phil'['python''haskell'] for namelanguages in favorite_languages items()print("\nname title("' favorite languages are:" for language in languagesprint("\tlanguage title()as you can see at the value associated with each name is now list notice that some people have one favorite language and others have multiple favorites when we loop through the dictionary at vwe use the variable name languages to hold each value from the dictionarybecause we know that each value will be list inside the main dictionary loopwe use
136
now each person can list as many favorite languages as they likejen' favorite languages arepython ruby sarah' favorite languages arec phil' favorite languages arepython haskell edward' favorite languages areruby go to refine this program even furtheryou could include an if statement at the beginning of the dictionary' for loop to see whether each person has more than one favorite language by examining the value of len(languagesif person has more than one favoritethe output would stay the same if the person has only one favorite languageyou could change the wording to reflect that for exampleyou could say sarah' favorite language is note you should not nest lists and dictionaries too deeply if you're nesting items much deeper than what you see in the preceding examples or you're working with someone else' code with significant levels of nestingmost likely simpler way to solve the problem exists dictionary in dictionary you can nest dictionary inside another dictionarybut your code can get complicated quickly when you do for exampleif you have several users for websiteeach with unique usernameyou can use the usernames as the keys in dictionary you can then store information about each user by using dictionary as the value associated with their username in the following listingwe store three pieces of information about each usertheir first namelast nameand location we'll access this information by looping through the usernames and the dictionary of information associated with each usernamemany_users py users 'aeinstein''first''albert''last''einstein''location''princeton'}dictionaries
137
'first''marie''last''curie''location''paris'} for usernameuser_info in users items() print("\nusernameusernamew full_name user_info['first'user_info['last'location user_info['location' print("\tfull namefull_name title()print("\tlocationlocation title()we first define dictionary called users with two keysone each for the usernames 'aeinsteinand 'mcuriethe value associated with each key is dictionary that includes each user' first namelast nameand location at we loop through the users dictionary python stores each key in the variable usernameand the dictionary associated with each username goes into the variable user_info once inside the main dictionary loopwe print the username at at we start accessing the inner dictionary the variable user_infowhich contains the dictionary of user informationhas three keys'first''last'and 'locationwe use each key to generate neatly formatted full name and location for each personand then print summary of what we know about each user xusernameaeinstein full namealbert einstein locationprinceton usernamemcurie full namemarie curie locationparis notice that the structure of each user' dictionary is identical although not required by pythonthis structure makes nested dictionaries easier to work with if each user' dictionary had different keysthe code inside the for loop would be more complicated try it yourse lf - peoplestart with the program you wrote for exercise - (page make two new dictionaries representing different peopleand store all three dictionaries in list called people loop through your list of people as you loop through the listprint everything you know about each person
138
name of pet in each dictionaryinclude the kind of animal and the owner' name store these dictionaries in list called pets nextloop through your list and as you do print everything you know about each pet - favorite placesmake dictionary called favorite_places think of three names to use as keys in the dictionaryand store one to three favorite places for each person to make this exercise bit more interestingask some friends to name few of their favorite places loop through the dictionaryand print each person' name and their favorite places - favorite numbersmodify your program from exercise - (page so each person can have more than one favorite number then print each person' name along with their favorite numbers - citiesmake dictionary called cities use the names of three cities as keys in your dictionary create dictionary of information about each city and include the country that the city is inits approximate populationand one fact about that city the keys for each city' dictionary should be something like countrypopulationand fact print the name of each city and all of the information you have stored about it - extensionswe're now working with examples that are complex enough that they can be extended in any number of ways use one of the example programs from this and extend it by adding new keys and valueschanging the context of the program or improving the formatting of the output summary in this you learned how to define dictionary and how to work with the information stored in dictionary you learned how to access and modify individual elements in dictionaryand how to loop through all of the information in dictionary you learned to loop through dictionary' key-value pairsits keysand its values you also learned how to nest multiple dictionaries in listnest lists in dictionaryand nest dictionary inside dictionary in the next you'll learn about while loops and how to accept input from people who are using your programs this will be an exciting because you'll learn to make all of your programs interactivethey'll be able to respond to user input dictionaries
139
user input and while loops most programs are written to solve an end user' problem to do soyou usually need to get some information from the user for simple examplelet' say someone wants to find out whether they're old enough to vote if you write program to answer this questionyou need to know the user' age before you can provide an answer the program will need to ask the user to enteror inputtheir ageonce the program has this inputit can compare it to the voting age to determine if the user is old enough and then report the result in this you'll learn how to accept user input so your program can then work with it when your program needs nameyou'll be able to prompt the user for name when your program needs list of namesyou'll be able to prompt the user for series of names to do thisyou'll use the input(function you'll also learn how to keep programs running as long as users want them toso they can enter as much information as they need tothenyour program can work with that information you'll use python' while loop to keep programs running as long as certain conditions remain true
140
long your programs runyou'll be able to write fully interactive programs how the input(function works the input(function pauses your program and waits for the user to enter some text once python receives the user' inputit stores it in variable to make it convenient for you to work with for examplethe following program asks the user to enter some textthen displays that message back to the userparrot py message input("tell me somethingand will repeat it back to you"print(messagethe input(function takes one argumentthe promptor instructionsthat we want to display to the user so they know what to do in this examplewhen python runs the first linethe user sees the prompt tell me somethingand will repeat it back to youthe program waits while the user enters their response and continues after the user presses enter the response is stored in the variable messagethen print(messagedisplays the input back to the usertell me somethingand will repeat it back to youhello everyonehello everyonenote sublime text doesn' run programs that prompt the user for input you can use sublime text to write programs that prompt for inputbut you'll need to run these programs from terminal see "running python programs from terminalon page writing clear prompts each time you use the input(functionyou should include cleareasy-tofollow prompt that tells the user exactly what kind of information you're looking for any statement that tells the user what to enter should work for examplegreeter py name input("please enter your name"print("helloname "!"add space at the end of your prompts (after the colon in the preceding exampleto separate the prompt from the user' response and to make it clear to your user where to enter their text for exampleplease enter your nameeric helloericsometimes you'll want to write prompt that' longer than one line for exampleyou might want to tell the user why you're asking for certain input
141
function this allows you to build your prompt over several linesthen write clean input(statement greeter py prompt "if you tell us who you arewe can personalize the messages you see prompt +"\nwhat is your first namename input(promptprint("\nhelloname "!"this example shows one way to build multi-line string the first line stores the first part of the message in the variable prompt in the second linethe operator +takes the string that was stored in prompt and adds the new string onto the end the prompt now spans two linesagain with space after the question mark for clarityif you tell us who you arewe can personalize the messages you see what is your first nameeric helloericusing int(to accept numerical input when you use the input(functionpython interprets everything the user enters as string consider the following interpreter sessionwhich asks for the user' ageage input("how old are you"how old are you age ' the user enters the number but when we ask python for the value of ageit returns ' 'the string representation of the numerical value entered we know python interpreted the input as string because the number is now enclosed in quotes if all you want to do is print the inputthis works well but if you try to use the input as numberyou'll get an errorage input("how old are you"how old are you age > traceback (most recent call last)file ""line in typeerrorunorderable typesstr(>int(when you try to use the input to do numerical comparison upython produces an error because it can' compare string to an integerthe string ' that' stored in age can' be compared to the numerical value user input and while loops
142
python to treat the input as numerical value the int(function converts string representation of number to numerical representationas shown hereage input("how old are you"how old are you age int(ageage > true in this examplewhen we enter at the promptpython interprets the number as stringbut the value is then converted to numerical representation by int( now python can run the conditional testit compares age (which now contains the numerical value and to see if age is greater than or equal to this test evaluates to true how do you use the int(function in an actual programconsider program that determines whether people are tall enough to ride roller coasterrollercoaster py height input("how tall are youin inches"height int(heightif height > print("\nyou're tall enough to ride!"elseprint("\nyou'll be able to ride when you're little older "the program can compare height to because height int(heightconverts the input value to numerical representation before the comparison is made if the number entered is greater than or equal to we tell the user that they're tall enoughhow tall are youin inches you're tall enough to ridewhen you use numerical input to do calculations and comparisonsbe sure to convert the input value to numerical representation first the modulo operator useful tool for working with numerical information is the modulo operator (%)which divides one number by another number and returns the remainder
143
the modulo operator doesn' tell you how many times one number fits into anotherit just tells you what the remainder is when one number is divisible by another numberthe remainder is so the modulo operator always returns you can use this fact to determine if number is even or oddeven_or_odd py number input("enter numberand 'll tell you if it' even or odd"number int(numberif number = print("\nthe number str(numberis even "elseprint("\nthe number str(numberis odd "even numbers are always divisible by twoso if the modulo of number and two is zero (hereif number = the number is even otherwiseit' odd enter numberand 'll tell you if it' even or odd the number is even accepting input in python if you're using python you should use the raw_input(function when prompting for user input this function interprets all input as stringjust as input(does in python python has an input(function as wellbut this function interprets the user' input as python code and attempts to run the input at best you'll get an error that python doesn' understand the inputat worst you'll run code that you didn' intend to run if you're using python use raw_input(instead of input(try it yourse lf - rental carwrite program that asks the user what kind of rental car they would like print message about that carsuch as "let me see if can find you subaru - restaurant seatingwrite program that asks the user how many people are in their dinner group if the answer is more than eightprint message saying they'll have to wait for table otherwisereport that their table is ready - multiples of tenask the user for numberand then report whether the number is multiple of or not user input and while loops
144
the for loop takes collection of items and executes block of code once for each item in the collection in contrastthe while loop runs as long asor whilea certain condition is true the while loop in action you can use while loop to count up through series of numbers for examplethe following while loop counts from to counting py current_number while current_number < print(current_numbercurrent_number + in the first linewe start counting from by setting the value of current_number to the while loop is then set to keep running as long as the value of current_number is less than or equal to the code inside the loop prints the value of current_number and then adds to that value with current_number + (the +operator is shorthand for current_number current_number python repeats the loop as long as the condition current_number < is true because is less than python prints and then adds making the current number because is less than python prints and adds againmaking the current number and so on once the value of current_number is greater than the loop stops running and the program ends the programs you use every day most likely contain while loops for examplea game needs while loop to keep running as long as you want to keep playingand so it can stop running as soon as you ask it to quit programs wouldn' be fun to use if they stopped running before we told them to or kept running even after we wanted to quitso while loops are quite useful letting the user choose when to quit we can make the parrot py program run as long as the user wants by putting most of the program inside while loop we'll define quit value and then keep the program running as long as the user has not entered the quit valueparrot py prompt "\ntell me somethingand will repeat it back to you:prompt +"\nenter 'quitto end the program
145
while message !'quit'message input(promptprint(messageat uwe define prompt that tells the user their two optionsentering message or entering the quit value (in this case'quit'then we set up variable message to store whatever value the user enters we define message as an empty string""so python has something to check the first time it reaches the while line the first time the program runs and python reaches the while statementit needs to compare the value of message to 'quit'but no user input has been entered yet if python has nothing to compareit won' be able to continue running the program to solve this problemwe make sure to give message an initial value although it' just an empty stringit will make sense to python and allow it to perform the comparison that makes the while loop work this while loop runs as long as the value of message is not 'quitthe first time through the loopmessage is just an empty stringso python enters the loop at message input(prompt)python displays the prompt and waits for the user to enter their input whatever they enter is stored in message and printedthenpython reevaluates the condition in the while statement as long as the user has not entered the word 'quit'the prompt is displayed again and python waits for more input when the user finally enters 'quit'python stops executing the while loop and the program endstell me somethingand will repeat it back to youenter 'quitto end the program hello everyonehello everyonetell me somethingand will repeat it back to youenter 'quitto end the program hello again hello again tell me somethingand will repeat it back to youenter 'quitto end the program quit quit this program works wellexcept that it prints the word 'quitas if it were an actual message simple if test fixes thisprompt "\ntell me somethingand will repeat it back to you:prompt +"\nenter 'quitto end the program message "while message !'quit'message input(promptif message !'quit'print(messageuser input and while loops
146
and only prints the message if it does not match the quit valuetell me somethingand will repeat it back to youenter 'quitto end the program hello everyonehello everyonetell me somethingand will repeat it back to youenter 'quitto end the program hello again hello again tell me somethingand will repeat it back to youenter 'quitto end the program quit using flag in the previous examplewe had the program perform certain tasks while given condition was true but what about more complicated programs in which many different events could cause the program to stop runningfor examplein gameseveral different events can end the game when the player runs out of shipstheir time runs outor the cities they were supposed to protect are all destroyedthe game should end it needs to end if any one of these events happens if many possible events might occur to stop the programtrying to test all these conditions in one while statement becomes complicated and difficult for program that should run only as long as many conditions are trueyou can define one variable that determines whether or not the entire program is active this variablecalled flagacts as signal to the program we can write our programs so they run while the flag is set to true and stop running when any of several events sets the value of the flag to false as resultour overall while statement needs to check only one conditionwhether or not the flag is currently true thenall our other tests (to see if an event has occurred that should set the flag to falsecan be neatly organized in the rest of the program let' add flag to parrot py from the previous section this flagwhich we'll call active (though you can call it anything)will monitor whether or not the program should continue runningprompt "\ntell me somethingand will repeat it back to you:prompt +"\nenter 'quitto end the program active true while activemessage input(promptw if message ='quit'active false elseprint(message
147
state doing so makes the while statement simpler because no comparison is made in the while statement itselfthe logic is taken care of in other parts of the program as long as the active variable remains truethe loop will continue running in the if statement inside the while loopwe check the value of message once the user enters their input if the user enters 'quitwwe set active to falseand the while loop stops if the user enters anything other than 'quitxwe print their input as message this program has the same output as the previous example where we placed the conditional test directly in the while statement but now that we have flag to indicate whether the overall program is in an active stateit would be easy to add more tests (such as elif statementsfor events that should cause active to become false this is useful in complicated programs like games in which there may be many events that should each make the program stop running when any of these events causes the active flag to become falsethe main game loop will exita game over message can be displayedand the player can be given the option to play again using break to exit loop to exit while loop immediately without running any remaining code in the loopregardless of the results of any conditional testuse the break statement the break statement directs the flow of your programyou can use it to control which lines of code are executed and which aren'tso the program only executes code that you want it towhen you want it to for exampleconsider program that asks the user about places they've visited we can stop the while loop in this program by calling break as soon as the user enters the 'quitvaluecities py prompt "\nplease enter the name of city you have visited:prompt +"\ (enter 'quitwhen you are finished while truecity input(promptif city ='quit'break elseprint(" ' love to go to city title("!" loop that starts with while true will run forever unless it reaches break statement the loop in this program continues asking the user to enter the names of cities they've been to until they enter 'quitwhen they enter 'quit'the break statement runscausing python to exit the loopplease enter the name of city you have visited(enter 'quitwhen you are finished new york ' love to go to new yorkuser input and while loops
148
(enter 'quitwhen you are finished san francisco ' love to go to san franciscoplease enter the name of city you have visited(enter 'quitwhen you are finished quit note you can use the break statement in any of python' loops for exampleyou could use break to quit for loop that' working through list or dictionary using continue in loop rather than breaking out of loop entirely without executing the rest of its codeyou can use the continue statement to return to the beginning of the loop based on the result of conditional test for exampleconsider loop that counts from to but prints only the odd numbers in that rangecounting py current_number while current_number current_number + if current_number = continue print(current_numberfirst we set current_number to because it' less than python enters the while loop once inside the loopwe increment the count by at uso current_number is the if statement then checks the modulo of current_number and if the modulo is (which means current_number is divisible by )the continue statement tells python to ignore the rest of the loop and return to the beginning if the current number is not divisible by the rest of the loop is executed and python prints the current number avoiding infinite loops every while loop needs way to stop running so it won' continue to run forever for examplethis counting loop should count from to counting py while < print(xx +
149
will run foreverthis loop runs foreverx while < print(xnow the value of will start at but never change as resultthe conditional test < will always evaluate to true and the while loop will run foreverprinting series of slike this --snip-every programmer accidentally writes an infinite while loop from time to timeespecially when program' loops have subtle exit conditions if your program gets stuck in an infinite looppress ctrl- or just close the terminal window displaying your program' output to avoid writing infinite loopstest every while loop and make sure the loop stops when you expect it to if you want your program to end when the user enters certain input valuerun the program and enter that value if the program doesn' endscrutinize the way your program handles the value that should cause the loop to exit make sure at least one part of the program can make the loop' condition false or cause it to reach break statement note some editorssuch as sublime texthave an embedded output window this can make it difficult to stop an infinite loopand you might have to close the editor to end the loop try it yourse lf - pizza toppingswrite loop that prompts the user to enter series of pizza toppings until they enter 'quitvalue as they enter each toppingprint message saying you'll add that topping to their pizza - movie ticketsa movie theater charges different ticket prices depending on person' age if person is under the age of the ticket is freeif they are between and the ticket is $ and if they are over age the ticket is $ write loop in which you ask users their ageand then tell them the cost of their movie ticket (continueduser input and while loops
150
that do each of the following at least onceuse conditional test in the while statement to stop the loop use an active variable to control how long the loop runs use break statement to exit the loop when the user enters 'quitvalue - infinitywrite loop that never endsand run it (to end the looppress ctrl- or close the window displaying the output using while loop with lists and dictionaries so farwe've worked with only one piece of user information at time we received the user' input and then printed the input or response to it the next time through the while loopwe' receive another input value and respond to that but to keep track of many users and pieces of informationwe'll need to use lists and dictionaries with our while loops for loop is effective for looping through listbut you shouldn' modify list inside for loop because python will have trouble keeping track of the items in the list to modify list as you work through ituse while loop using while loops with lists and dictionaries allows you to collectstoreand organize lots of input to examine and report on later moving items from one list to another consider list of newly registered but unverified users of website after we verify these usershow can we move them to separate list of confirmed usersone way would be to use while loop to pull users from the list of unconfirmed users as we verify them and then add them to separate list of confirmed users here' what that code might look likeconfirmed_ users py start with users that need to be verifiedand an empty list to hold confirmed users unconfirmed_users ['alice''brian''candace'confirmed_users [verify each user until there are no more unconfirmed users move each verified user into the list of confirmed users while unconfirmed_usersw current_user unconfirmed_users pop( print("verifying usercurrent_user title()confirmed_users append(current_user
151
print("\nthe following users have been confirmed:"for confirmed_user in confirmed_usersprint(confirmed_user title()we begin with list of unconfirmed users at (alicebrianand candaceand an empty list to hold confirmed users the while loop at runs as long as the list unconfirmed_users is not empty within this loopthe pop(function at removes unverified users one at time from the end of unconfirmed_users herebecause candace is last in the unconfirmed_users listher name will be the first to be removedstored in current_userand added to the confirmed_users list at next is brianthen alice we simulate confirming each user by printing verification message and then adding them to the list of confirmed users as the list of unconfirmed users shrinksthe list of confirmed users grows when the list of unconfirmed users is emptythe loop stops and the list of confirmed users is printedverifying usercandace verifying userbrian verifying useralice the following users have been confirmedcandace brian alice removing all instances of specific values from list in we used remove(to remove specific value from list the remove(function worked because the value we were interested in appeared only once in the list but what if you want to remove all instances of value from listsay you have list of pets with the value 'catrepeated several times to remove all instances of that valueyou can run while loop until 'catis no longer in the listas shown herepets py pets ['dog''cat''dog''goldfish''cat''rabbit''cat'print(petswhile 'catin petspets remove('cat'print(petswe start with list containing multiple instances of 'catafter printing the listpython enters the while loop because it finds the value 'catin the list user input and while loops
152
returns to the while lineand then reenters the loop when it finds that 'catis still in the list it removes each instance of 'catuntil the value is no longer in the listat which point python exits the loop and prints the list again['dog''cat''dog''goldfish''cat''rabbit''cat'['dog''dog''goldfish''rabbit'filling dictionary with user input you can prompt for as much input as you need in each pass through while loop let' make polling program in which each pass through the loop prompts for the participant' name and response we'll store the data we gather in dictionarybecause we want to connect each response with particular usermountain_ poll py responses {set flag to indicate that polling is active polling_active true while polling_activeprompt for the person' name and response name input("\nwhat is your name"response input("which mountain would you like to climb someday" store the response in the dictionaryresponses[nameresponse find out if anyone else is going to take the poll repeat input("would you like to let another person respond(yesno"if repeat ='no'polling_active false polling is complete show the results print("\ --poll results ---" for nameresponse in responses items()print(name would like to climb response "the program first defines an empty dictionary (responsesand sets flag (polling_activeto indicate that polling is active as long as polling_active is truepython will run the code in the while loop within the loopthe user is prompted to enter their username and mountain they' like to climb that information is stored in the responses dictionary vand the user is asked whether or not to keep the poll running if they enter yesthe program enters the while loop again if they enter nothe polling_active flag is set to falsethe while loop stops runningand the final code block at displays the results of the poll
153
output like thiswhat is your nameeric which mountain would you like to climb somedaydenali would you like to let another person respond(yesnoyes what is your namelynn which mountain would you like to climb somedaydevil' thumb would you like to let another person respond(yesnono --poll results --lynn would like to climb devil' thumb eric would like to climb denali try it yourse lf - delimake list called sandwich_orders and fill it with the names of various sandwiches then make an empty list called finished_sandwiches loop through the list of sandwich orders and print message for each ordersuch as made your tuna sandwich as each sandwich is mademove it to the list of finished sandwiches after all the sandwiches have been madeprint message listing each sandwich that was made - no pastramiusing the list sandwich_orders from exercise - make sure the sandwich 'pastramiappears in the list at least three times add code near the beginning of your program to print message saying the deli has run out of pastramiand then use while loop to remove all occurrences of 'pastramifrom sandwich_orders make sure no pastrami sandwiches end up in finished_sandwiches - dream vacationwrite program that polls users about their dream vacation write prompt similar to if you could visit one place in the worldwhere would you goinclude block of code that prints the results of the poll summary in this you learned how to use input(to allow users to provide their own information in your programs you learned to work with both text and numerical input and how to use while loops to make your programs run as long as your users want them to you saw several ways to control the flow of while loop by setting an active flagusing the break statementand user input and while loops
154
items from one list to another and how to remove all instances of value from list you also learned how while loops can be used with dictionaries in you'll learn about functions functions allow you to break your programs into small partseach of which does one specific job you can call function as many times as you wantand you can store your functions in separate files by using functionsyou'll be able to write more efficient code that' easier to troubleshoot and maintain and that can be reused in many different programs
155
functions in this you'll learn to write functionswhich are named blocks of code that are designed to do one specific job when you want to perform particular task that you've defined in functionyou call the name of the function responsible for it if you need to perform that task multiple times throughout your programyou don' need to type all the code for the same task again and againyou just call the function dedicated to handling that taskand the call tells python to run the code inside the function you'll find that using functions makes your programs easier to writereadtestand fix in this you'll also learn ways to pass information to functions you'll learn how to write certain functions whose primary job is to display information and other functions designed to process data and return value or set of values finallyyou'll learn to store functions in separate files called modules to help organize your main program files
156
here' simple function named greet_user(that prints greetinggreeter py def greet_user() """display simple greeting "" print("hello!" greet_user(this example shows the simplest structure of function the line at uses the keyword def to inform python that you're defining function this is the function definitionwhich tells python the name of the function andif applicablewhat kind of information the function needs to do its job the parentheses hold that information in this casethe name of the function is greet_user()and it needs no information to do its jobso its parentheses are empty (even sothe parentheses are required finallythe definition ends in colon any indented lines that follow def greet_user()make up the body of the function the text at is comment called docstringwhich describes what the function does docstrings are enclosed in triple quoteswhich python looks for when it generates documentation for the functions in your programs the line print("hello!"is the only line of actual code in the body of this functionso greet_user(has just one jobprint("hello!"when you want to use this functionyou call it function call tells python to execute the code in the function to call functionyou write the name of the functionfollowed by any necessary information in parenthesesas shown at because no information is needed herecalling our function is as simple as entering greet_user(as expectedit prints hello!hellopassing information to function modified slightlythe function greet_user(can not only tell the user hellobut also greet them by name for the function to do thisyou enter username in the parentheses of the function' definition at def greet_user(by adding username here you allow the function to accept any value of username you specify the function now expects you to provide value for username each time you call it when you call greet_user()you can pass it namesuch as 'jesse'inside the parenthesesdef greet_user(username)"""display simple greeting ""print("hellousername title("!"greet_user('jesse'
157
information it needs to execute the print statement the function accepts the name you passed it and displays the greeting for that namehellojesselikewiseentering greet_user('sarah'calls greet_user()passes it 'sarah'and prints hellosarahyou can call greet_user(as often as you want and pass it any name you want to produce predictable output every time arguments and parameters in the preceding greet_user(functionwe defined greet_user(to require value for the variable username once we called the function and gave it the information ( person' name)it printed the right greeting the variable username in the definition of greet_user(is an example of parametera piece of information the function needs to do its job the value 'jessein greet_user('jesse'is an example of an argument an argument is piece of information that is passed from function call to function when we call the functionwe place the value we want the function to work with in parentheses in this case the argument 'jessewas passed to the function greet_user()and the value was stored in the parameter username note people sometimes speak of arguments and parameters interchangeably don' be surprised if you see the variables in function definition referred to as arguments or the variables in function call referred to as parameters try it yourse lf - messagewrite function called display_message(that prints one sentence telling everyone what you are learning about in this call the functionand make sure the message displays correctly - favorite bookwrite function called favorite_book(that accepts one parametertitle the function should print messagesuch as one of my favorite books is alice in wonderland call the functionmaking sure to include book title as an argument in the function call passing arguments because function definition can have multiple parametersa function call may need multiple arguments you can pass arguments to your functions in number of ways you can use positional argumentswhich need to be in functions
158
argument consists of variable name and valueand lists and dictionaries of values let' look at each of these in turn positional arguments when you call functionpython must match each argument in the function call with parameter in the function definition the simplest way to do this is based on the order of the arguments provided values matched up this way are called positional arguments to see how this worksconsider function that displays information about pets the function tells us what kind of animal each pet is and the pet' nameas shown herepets py def describe_pet(animal_typepet_name)"""display information about pet ""print("\ni have animal_type "print("my animal_type "' name is pet_name title(" describe_pet('hamster''harry'the definition shows that this function needs type of animal and the animal' name when we call describe_pet()we need to provide an animal type and namein that order for examplein the function callthe argument 'hamsteris stored in the parameter animal_type and the argument 'harryis stored in the parameter pet_name in the function bodythese two parameters are used to display information about the pet being described the output describes hamster named harryi have hamster my hamster' name is harry multiple function calls you can call function as many times as needed describing seconddifferent pet requires just one more call to describe_pet()def describe_pet(animal_typepet_name)"""display information about pet ""print("\ni have animal_type "print("my animal_type "' name is pet_name title("describe_pet('hamster''harry'describe_pet('dog''willie'in this second function callwe pass describe_pet(the arguments 'dogand 'willieas with the previous set of arguments we usedpython matches 'dogwith the parameter animal_type and 'williewith the parameter pet_name
159
named willie now we have hamster named harry and dog named williei have hamster my hamster' name is harry have dog my dog' name is willie calling function multiple times is very efficient way to work the code describing pet is written once in the function thenanytime you want to describe new petyou call the function with the new pet' information even if the code for describing pet were to expand to ten linesyou could still describe new pet in just one line by calling the function again you can use as many positional arguments as you need in your functions python works through the arguments you provide when calling the function and matches each one with the corresponding parameter in the function' definition order matters in positional arguments you can get unexpected results if you mix up the order of the arguments in function call when using positional argumentsdef describe_pet(animal_typepet_name)"""display information about pet ""print("\ni have animal_type "print("my animal_type "' name is pet_name title("describe_pet('harry''hamster'in this function call we list the name first and the type of animal second because the argument 'harryis listed first this timethat value is stored in the parameter animal_type likewise'hamsteris stored in pet_name now we have "harrynamed "hamster" have harry my harry' name is hamster if you get funny results like thischeck to make sure the order of the arguments in your function call matches the order of the parameters in the function' definition keyword arguments keyword argument is name-value pair that you pass to function you directly associate the name and the value within the argumentso when you pass the argument to the functionthere' no confusion (you won' end up functions
160
to worry about correctly ordering your arguments in the function calland they clarify the role of each value in the function call let' rewrite pets py using keyword arguments to call describe_pet()def describe_pet(animal_typepet_name)"""display information about pet ""print("\ni have animal_type "print("my animal_type "' name is pet_name title("describe_pet(animal_type='hamster'pet_name='harry'the function describe_pet(hasn' changed but when we call the functionwe explicitly tell python which parameter each argument should be matched with when python reads the function callit knows to store the argument 'hamsterin the parameter animal_type and the argument 'harryin pet_name the output correctly shows that we have hamster named harry the order of keyword arguments doesn' matter because python knows where each value should go the following two function calls are equivalentdescribe_pet(animal_type='hamster'pet_name='harry'describe_pet(pet_name='harry'animal_type='hamster'note when you use keyword argumentsbe sure to use the exact names of the parameters in the function' definition default values when writing functionyou can define default value for each parameter if an argument for parameter is provided in the function callpython uses the argument value if notit uses the parameter' default value so when you define default value for parameteryou can exclude the corresponding argument you' usually write in the function call using default values can simplify your function calls and clarify the ways in which your functions are typically used for exampleif you notice that most of the calls to describe_pet(are being used to describe dogsyou can set the default value of animal_type to 'dognow anyone calling describe_pet(for dog can omit that informationdef describe_pet(pet_nameanimal_type='dog')"""display information about pet ""print("\ni have animal_type "print("my animal_type "' name is pet_name title("describe_pet(pet_name='willie'
161
'dog'for animal_type now when the function is called with no animal_type specifiedpython knows to use the value 'dogfor this parameteri have dog my dog' name is willie note that the order of the parameters in the function definition had to be changed because the default value makes it unnecessary to specify type of animal as an argumentthe only argument left in the function call is the pet' name python still interprets this as positional argumentso if the function is called with just pet' namethat argument will match up with the first parameter listed in the function' definition this is the reason the first parameter needs to be pet_name the simplest way to use this function now is to provide just dog' name in the function calldescribe_pet('willie'this function call would have the same output as the previous example the only argument provided is 'willie'so it is matched up with the first parameter in the definitionpet_name because no argument is provided for animal_typepython uses the default value 'dogto describe an animal other than dogyou could use function call like thisdescribe_pet(pet_name='harry'animal_type='hamster'because an explicit argument for animal_type is providedpython will ignore the parameter' default value note when you use default valuesany parameter with default value needs to be listed after all the parameters that don' have default values this allows python to continue interpreting positional arguments correctly equivalent function calls because positional argumentskeyword argumentsand default values can all be used togetheroften you'll have several equivalent ways to call function consider the following definition for describe_pets(with one default value provideddef describe_pet(pet_nameanimal_type='dog')with this definitionan argument always needs to be provided for pet_nameand this value can be provided using the positional or keyword functions
162
animal_type must be included in the calland this argument can also be specified using the positional or keyword format all of the following calls would work for this functiona dog named willie describe_pet('willie'describe_pet(pet_name='willie' hamster named harry describe_pet('harry''hamster'describe_pet(pet_name='harry'animal_type='hamster'describe_pet(animal_type='hamster'pet_name='harry'each of these function calls would have the same output as the previous examples note it doesn' really matter which calling style you use as long as your function calls produce the output you wantjust use the style you find easiest to understand avoiding argument errors when you start to use functionsdon' be surprised if you encounter errors about unmatched arguments unmatched arguments occur when you provide fewer or more arguments than function needs to do its work for examplehere' what happens if we try to call describe_pet(with no argumentsdef describe_pet(animal_typepet_name)"""display information about pet ""print("\ni have animal_type "print("my animal_type "' name is pet_name title("describe_pet(python recognizes that some information is missing from the function calland the traceback tells us thattraceback (most recent call last) file "pets py"line in describe_pet( typeerrordescribe_pet(missing required positional arguments'animal_ typeand 'pet_nameat the traceback tells us the location of the problemallowing us to look back and see that something went wrong in our function call at the offending function call is written out for us to see at the traceback
163
rewrite the call correctly without having to open that file and read the function code python is helpful in that it reads the function' code for us and tells us the names of the arguments we need to provide this is another motivation for giving your variables and functions descriptive names if you dopython' error messages will be more useful to you and anyone else who might use your code if you provide too many argumentsyou should get similar traceback that can help you correctly match your function call to the function definition try it yourse lf - -shirtwrite function called make_shirt(that accepts size and the text of message that should be printed on the shirt the function should print sentence summarizing the size of the shirt and the message printed on it call the function once using positional arguments to make shirt call the function second time using keyword arguments - large shirtsmodify the make_shirt(function so that shirts are large by default with message that reads love python make large shirt and medium shirt with the default messageand shirt of any size with different message - citieswrite function called describe_city(that accepts the name of city and its country the function should print simple sentencesuch as reykjavik is in iceland give the parameter for the country default value call your function for three different citiesat least one of which is not in the default country return values function doesn' always have to display its output directly insteadit can process some data and then return value or set of values the value the function returns is called return value the return statement takes value from inside function and sends it back to the line that called the function return values allow you to move much of your program' grunt work into functionswhich can simplify the body of your program functions
164
let' look at function that takes first and last nameand returns neatly formatted full nameformatted_ def get_formatted_name(first_namelast_name)name py """return full nameneatly formatted "" full_name first_name last_name return full_name title( musician get_formatted_name('jimi''hendrix'print(musicianthe definition of get_formatted_name(takes as parameters first and last name the function combines these two namesadds space between themand stores the result in full_name the value of full_name is converted to title caseand then returned to the calling line at when you call function that returns valueyou need to provide variable where the return value can be stored in this casethe returned value is stored in the variable musician at the output shows neatly formatted name made up of the parts of person' namejimi hendrix this might seem like lot of work to get neatly formatted name when we could have just writtenprint("jimi hendrix"but when you consider working with large program that needs to store many first and last names separatelyfunctions like get_formatted_name(become very useful you store first and last names separately and then call this function whenever you want to display full name making an argument optional sometimes it makes sense to make an argument optional so that people using the function can choose to provide extra information only if they want to you can use default values to make an argument optional for examplesay we want to expand get_formatted_name(to handle middle names as well first attempt to include middle names might look like thisdef get_formatted_name(first_namemiddle_namelast_name)"""return full nameneatly formatted ""full_name first_name middle_name last_name return full_name title(musician get_formatted_name('john''lee''hooker'print(musician
165
function takes in all three parts of name and then builds string out of them the function adds spaces where appropriate and converts the full name to title casejohn lee hooker but middle names aren' always neededand this function as written would not work if you tried to call it with only first name and last name to make the middle name optionalwe can give the middle_name argument an empty default value and ignore the argument unless the user provides value to make get_formatted_name(work without middle namewe set the default value of middle_name to an empty string and move it to the end of the list of parametersu def get_formatted_name(first_namelast_namemiddle_name='')"""return full nameneatly formatted "" if middle_namefull_name first_name middle_name last_name elsefull_name first_name last_name return full_name title(musician get_formatted_name('jimi''hendrix'print(musicianx musician get_formatted_name('john''hooker''lee'print(musicianin this examplethe name is built from three possible parts because there' always first and last namethese parameters are listed first in the function' definition the middle name is optionalso it' listed last in the definitionand its default value is an empty string in the body of the functionwe check to see if middle name has been provided python interprets non-empty strings as trueso if middle_name evaluates to true if middle name argument is in the function call if middle name is providedthe firstmiddleand last names are combined to form full name this name is then changed to title case and returned to the function call line where it' stored in the variable musician and printed if no middle name is providedthe empty string fails the if test and the else block runs the full name is made with just first and last nameand the formatted name is returned to the calling line where it' stored in musician and printed calling this function with first and last name is straightforward if we're using middle namehoweverwe have to make sure the middle name is the last argument passed so python will match up the positional arguments correctly functions
166
and last nameand it works for people who have middle name as welljimi hendrix john lee hooker optional values allow functions to handle wide range of use cases while letting function calls remain as simple as possible returning dictionary function can return any kind of value you need it toincluding more complicated data structures like lists and dictionaries for examplethe following function takes in parts of name and returns dictionary representing personperson py def build_person(first_namelast_name)"""return dictionary of information about person "" person {'first'first_name'last'last_namev return person musician build_person('jimi''hendrix' print(musicianthe function build_person(takes in first and last nameand packs these values into dictionary at the value of first_name is stored with the key 'first'and the value of last_name is stored with the key 'lastthe entire dictionary representing the person is returned at the return value is printed at with the original two pieces of textual information now stored in dictionary{'first''jimi''last''hendrix'this function takes in simple textual information and puts it into more meaningful data structure that lets you work with the information beyond just printing it the strings 'jimiand 'hendrixare now labeled as first name and last name you can easily extend this function to accept optional values like middle namean agean occupationor any other information you want to store about person for examplethe following change allows you to store person' age as welldef build_person(first_namelast_nameage='')"""return dictionary of information about person ""person {'first'first_name'last'last_nameif ageperson['age'age return person musician build_person('jimi''hendrix'age= print(musician
167
assign the parameter an empty default value if the function call includes value for this parameterthe value is stored in the dictionary this function always stores person' namebut it can also be modified to store any other information you want about person using function with while loop you can use functions with all the python structures you've learned about so far for examplelet' use the get_formatted_name(function with while loop to greet users more formally here' first attempt at greeting people using their first and last namesgreeter py def get_formatted_name(first_namelast_name)"""return full nameneatly formatted ""full_name first_name last_name return full_name title(this is an infinite loopwhile trueu print("\nplease tell me your name:"f_name input("first name"l_name input("last name"formatted_name get_formatted_name(f_namel_nameprint("\nhelloformatted_name "!"for this examplewe use simple version of get_formatted_name(that doesn' involve middle names the while loop asks the user to enter their nameand we prompt for their first and last name separately but there' one problem with this while loopwe haven' defined quit condition where do you put quit condition when you ask for series of inputswe want the user to be able to quit as easily as possibleso each prompt should offer way to quit the break statement offers straight forward way to exit the loop at either promptdef get_formatted_name(first_namelast_name)"""return full nameneatly formatted ""full_name first_name last_name return full_name title(while trueprint("\nplease tell me your name:"print("(enter 'qat any time to quit)"f_name input("first name"if f_name =' 'break l_name input("last name"if l_name =' 'break functions
168
print("\nhelloformatted_name "!"we add message that informs the user how to quitand then we break out of the loop if the user enters the quit value at either prompt now the program will continue greeting people until someone enters 'qfor either nameplease tell me your name(enter 'qat any time to quitfirst nameeric last namematthes helloeric matthesplease tell me your name(enter 'qat any time to quitfirst nameq try it yourse lf - city nameswrite function called city_country(that takes in the name of city and its country the function should return string formatted like this"santiagochilecall your function with at least three city-country pairsand print the value that' returned - albumwrite function called make_album(that builds dictionary describing music album the function should take in an artist name and an album titleand it should return dictionary containing these two pieces of information use the function to make three dictionaries representing different albums print each return value to show that the dictionaries are storing the album information correctly add an optional parameter to make_album(that allows you to store the number of tracks on an album if the calling line includes value for the number of tracksadd that value to the album' dictionary make at least one new function call that includes the number of tracks on an album - user albumsstart with your program from exercise - write while loop that allows users to enter an album' artist and title once you have that informationcall make_album(with the user' input and print the dictionary that' created be sure to include quit value in the while loop
169
you'll often find it useful to pass list to functionwhether it' list of namesnumbersor more complex objectssuch as dictionaries when you pass list to functionthe function gets direct access to the contents of the list let' use functions to make working with lists more efficient say we have list of users and want to print greeting to each the following example sends list of names to function called greet_users()which greets each person in the list individuallygreet_users py def greet_users(names)"""print simple greeting to each user in the list ""for name in namesmsg "helloname title("!print(msgu usernames ['hannah''ty''margot'greet_users(usernameswe define greet_users(so it expects list of nameswhich it stores in the parameter names the function loops through the list it receives and prints greeting to each user at we define list of users and then pass the list usernames to greet_users()in our function callhellohannahhellotyhellomargotthis is the output we wanted every user sees personalized greetingand you can call the function any time you want to greet specific set of users modifying list in function when you pass list to functionthe function can modify the list any changes made to the list inside the function' body are permanentallowing you to work efficiently even when you're dealing with large amounts of data consider company that creates printed models of designs that users submit designs that need to be printed are stored in listand after being printed they're moved to separate list the following code does this without using functionsprinting_ models py start with some designs that need to be printed unprinted_designs ['iphone case''robot pendant''dodecahedron'completed_models [simulate printing each designuntil none are left move each design to completed_models after printing while unprinted_designscurrent_design unprinted_designs pop(functions
170
print("printing modelcurrent_designcompleted_models append(current_designdisplay all completed models print("\nthe following models have been printed:"for completed_model in completed_modelsprint(completed_modelthis program starts with list of designs that need to be printed and an empty list called completed_models that each design will be moved to after it has been printed as long as designs remain in unprinted_designsthe while loop simulates printing each design by removing design from the end of the liststoring it in current_designand displaying message that the current design is being printed it then adds the design to the list of completed models when the loop is finished runninga list of the designs that have been printed is displayedprinting modeldodecahedron printing modelrobot pendant printing modeliphone case the following models have been printeddodecahedron robot pendant iphone case we can reorganize this code by writing two functionseach of which does one specific job most of the code won' changewe're just making it more efficient the first function will handle printing the designsand the second will summarize the prints that have been madeu def print_models(unprinted_designscompleted_models)""simulate printing each designuntil none are left move each design to completed_models after printing ""while unprinted_designscurrent_design unprinted_designs pop(simulate creating print from the design print("printing modelcurrent_designcompleted_models append(current_designv def show_completed_models(completed_models)"""show all the models that were printed ""print("\nthe following models have been printed:"for completed_model in completed_modelsprint(completed_modelunprinted_designs ['iphone case''robot pendant''dodecahedron'completed_models [
171
show_completed_models(completed_modelsat we define the function print_models(with two parametersa list of designs that need to be printed and list of completed models given these two liststhe function simulates printing each design by emptying the list of unprinted designs and filling up the list of completed models at we define the function show_completed_models(with one parameterthe list of completed models given this listshow_completed_models(displays the name of each model that was printed this program has the same output as the version without functionsbut the code is much more organized the code that does most of the work has been moved to two separate functionswhich makes the main part of the program easier to understand look at the body of the program to see how much easier it is to understand what this program is doingunprinted_designs ['iphone case''robot pendant''dodecahedron'completed_models [print_models(unprinted_designscompleted_modelsshow_completed_models(completed_modelswe set up list of unprinted designs and an empty list that will hold the completed models thenbecause we've already defined our two functionsall we have to do is call them and pass them the right arguments we call print_models(and pass it the two lists it needsas expectedprint_models(simulates printing the designs then we call show_completed_models(and pass it the list of completed models so it can report the models that have been printed the descriptive function names allow others to read this code and understand iteven without comments this program is easier to extend and maintain than the version without functions if we need to print more designs later onwe can simply call print_models(again if we realize the printing code needs to be modifiedwe can change the code onceand our changes will take place everywhere the function is called this technique is more efficient than having to update code separately in several places in the program this example also demonstrates the idea that every function should have one specific job the first function prints each designand the second displays the completed models this is more beneficial than using one function to do both jobs if you're writing function and notice the function is doing too many different taskstry to split the code into two functions remember that you can always call function from another functionwhich can be helpful when splitting complex task into series of steps preventing function from modifying list sometimes you'll want to prevent function from modifying list for examplesay that you start with list of unprinted designs and write functions
172
example you may decide that even though you've printed all the designsyou want to keep the original list of unprinted designs for your records but because you moved all the design names out of unprinted_designsthe list is now emptyand the empty list is the only version you havethe original is gone in this caseyou can address this issue by passing the function copy of the listnot the original any changes the function makes to the list will affect only the copyleaving the original list intact you can send copy of list to function like thisfunction_name(list_name[:]the slice notation [:makes copy of the list to send to the function if we didn' want to empty the list of unprinted designs in print_models pywe could call print_models(like thisprint_models(unprinted_designs[:]completed_modelsthe function print_models(can do its work because it still receives the names of all unprinted designs but this time it uses copy of the original unprinted designs listnot the actual unprinted_designs list the list completed_models will fill up with the names of printed models like it did beforebut the original list of unprinted designs will be unaffected by the function even though you can preserve the contents of list by passing copy of it to your functionsyou should pass the original list to functions unless you have specific reason to pass copy it' more efficient for function to work with an existing list to avoid using the time and memory needed to make separate copyespecially when you're working with large lists try it yourse lf - magiciansmake list of magician' names pass the list to function called show_magicians()which prints the name of each magician in the list - great magiciansstart with copy of your program from exercise - write function called make_great(that modifies the list of magicians by adding the phrase the great to each magician' name call show_magicians(to see that the list has actually been modified - unchanged magiciansstart with your work from exercise - call the function make_great(with copy of the list of magiciansnames because the original list will be unchangedreturn the new list and store it in separate list call show_magicians(with each list to show that you have one list of the original names and one list with the great added to each magician' name
173
sometimes you won' know ahead of time how many arguments function needs to accept fortunatelypython allows function to collect an arbitrary number of arguments from the calling statement for exampleconsider function that builds pizza it needs to accept number of toppingsbut you can' know ahead of time how many toppings person will want the function in the following example has one parameter*toppingsbut this parameter collects as many arguments as the calling line providespizza py def make_pizza(*toppings)"""print the list of toppings that have been requested ""print(toppingsmake_pizza('pepperoni'make_pizza('mushrooms''green peppers''extra cheese'the asterisk in the parameter name *toppings tells python to make an empty tuple called toppings and pack whatever values it receives into this tuple the print statement in the function body produces output showing that python can handle function call with one value and call with three values it treats the different calls similarly note that python packs the arguments into tupleeven if the function receives only one value('pepperoni',('mushrooms''green peppers''extra cheese'now we can replace the print statement with loop that runs through the list of toppings and describes the pizza being ordereddef make_pizza(*toppings)"""summarize the pizza we are about to make ""print("\nmaking pizza with the following toppings:"for topping in toppingsprint("toppingmake_pizza('pepperoni'make_pizza('mushrooms''green peppers''extra cheese'the function responds appropriatelywhether it receives one value or three valuesmaking pizza with the following toppingspepperoni making pizza with the following toppingsmushrooms green peppers extra cheese functions
174
receives mixing positional and arbitrary arguments if you want function to accept several different kinds of argumentsthe parameter that accepts an arbitrary number of arguments must be placed last in the function definition python matches positional and keyword arguments first and then collects any remaining arguments in the final parameter for exampleif the function needs to take in size for the pizzathat parameter must come before the parameter *toppingsdef make_pizza(size*toppings)"""summarize the pizza we are about to make ""print("\nmaking str(size"-inch pizza with the following toppings:"for topping in toppingsprint("toppingmake_pizza( 'pepperoni'make_pizza( 'mushrooms''green peppers''extra cheese'in the function definitionpython stores the first value it receives in the parameter size all other values that come after are stored in the tuple toppings the function calls include an argument for the size firstfollowed by as many toppings as needed now each pizza has size and number of toppingsand each piece of information is printed in the proper placeshowing size first and toppings aftermaking -inch pizza with the following toppingspepperoni making -inch pizza with the following toppingsmushrooms green peppers extra cheese using arbitrary keyword arguments sometimes you'll want to accept an arbitrary number of argumentsbut you won' know ahead of time what kind of information will be passed to the function in this caseyou can write functions that accept as many key-value pairs as the calling statement provides one example involves building user profilesyou know you'll get information about userbut you're not sure what kind of information you'll receive the function build_profile(in the
175
arbitrary number of keyword arguments as welluser_profile py def build_profile(firstlast**user_info)"""build dictionary containing everything we know about user ""profile { profile['first_name'first profile['last_name'last for keyvalue in user_info items()profile[keyvalue return profile user_profile build_profile('albert''einstein'location='princeton'field='physics'print(user_profilethe definition of build_profile(expects first and last nameand then it allows the user to pass in as many name-value pairs as they want the double asterisks before the parameter **user_info cause python to create an empty dictionary called user_info and pack whatever name-value pairs it receives into this dictionary within the functionyou can access the namevalue pairs in user_info just as you would for any dictionary in the body of build_profile()we make an empty dictionary called profile to hold the user' profile at we add the first and last names to this dictionary because we'll always receive these two pieces of information from the user at we loop through the additional key-value pairs in the dictionary user_info and add each pair to the profile dictionary finallywe return the profile dictionary to the function call line we call build_profile()passing it the first name 'albert'the last name 'einstein'and the two key-value pairs location='princetonand field='physicswe store the returned profile in user_profile and print user_profile{'first_name''albert''last_name''einstein''location''princeton''field''physics'the returned dictionary contains the user' first and last names andin this casethe location and field of study as well the function would work no matter how many additional key-value pairs are provided in the function call you can mix positionalkeywordand arbitrary values in many different ways when writing your own functions it' useful to know that all these argument types exist because you'll see them often when you start reading other people' code it takes practice to learn to use the different types correctly and to know when to use each type for nowremember to use the simplest approach that gets the job done as you progress you'll learn to use the most efficient approach each time functions
176
- sandwicheswrite function that accepts list of items person wants on sandwich the function should have one parameter that collects as many items as the function call providesand it should print summary of the sandwich that is being ordered call the function three timesusing different number of arguments each time - user profilestart with copy of user_profile py from page build profile of yourself by calling build_profile()using your first and last names and three other key-value pairs that describe you - carswrite function that stores information about car in dictionary the function should always receive manufacturer and model name it should then accept an arbitrary number of keyword arguments call the function with the required information and two other name-value pairssuch as color or an optional feature your function should work for call like this onecar make_car('subaru''outback'color='blue'tow_package=trueprint the dictionary that' returned to make sure all the information was stored correctly storing your functions in modules one advantage of functions is the way they separate blocks of code from your main program by using descriptive names for your functionsyour main program will be much easier to follow you can go step further by storing your functions in separate file called module and then importing that module into your main program an import statement tells python to make the code in module available in the currently running program file storing your functions in separate file allows you to hide the details of your program' code and focus on its higher-level logic it also allows you to reuse functions in many different programs when you store your functions in separate filesyou can share those files with other programmers without having to share your entire program knowing how to import functions also allows you to use libraries of functions that other programmers have written there are several ways to import moduleand 'll show you each of these briefly importing an entire module to start importing functionswe first need to create module module is file ending in py that contains the code you want to import into your
177
make this modulewe'll remove everything from the file pizza py except the function make_pizza()pizza py def make_pizza(size*toppings)"""summarize the pizza we are about to make ""print("\nmaking str(size"-inch pizza with the following toppings:"for topping in toppingsprint("toppingnow we'll make separate file called making_pizzas py in the same directory as pizza py this file imports the module we just created and then makes two calls to make_pizza()making_ pizzas py import pizza pizza make_pizza( 'pepperoni'pizza make_pizza( 'mushrooms''green peppers''extra cheese'when python reads this filethe line import pizza tells python to open the file pizza py and copy all the functions from it into this program you don' actually see code being copied between files because python copies the code behind the scenes as the program runs all you need to know is that any function defined in pizza py will now be available in making_pizzas py to call function from an imported moduleenter the name of the module you importedpizzafollowed by the name of the functionmake_pizza()separated by dot this code produces the same output as the original program that didn' import modulemaking -inch pizza with the following toppingspepperoni making -inch pizza with the following toppingsmushrooms green peppers extra cheese this first approach to importingin which you simply write import followed by the name of the modulemakes every function from the module available in your program if you use this kind of import statement to import an entire module named module_name pyeach function in the module is available through the following syntaxmodule_name function_name(functions
178
you can also import specific function from module here' the general syntax for this approachfrom module_name import function_name you can import as many functions as you want from module by separating each function' name with commafrom module_name import function_ function_ function_ the making_pizzas py example would look like this if we want to import just the function we're going to usefrom pizza import make_pizza make_pizza( 'pepperoni'make_pizza( 'mushrooms''green peppers''extra cheese'with this syntaxyou don' need to use the dot notation when you call function because we've explicitly imported the function make_pizza(in the import statementwe can call it by name when we use the function using as to give function an alias if the name of function you're importing might conflict with an existing name in your program or if the function name is longyou can use shortunique alias--an alternate name similar to nickname for the function you'll give the function this special nickname when you import the function here we give the function make_pizza(an aliasmp()by importing make_pizza as mp the as keyword renames function using the alias you providefrom pizza import make_pizza as mp mp( 'pepperoni'mp( 'mushrooms''green peppers''extra cheese'the import statement shown here renames the function make_pizza(to mp(in this program any time we want to call make_pizza(we can simply write mp(insteadand python will run the code in make_pizza(while avoiding any confusion with another make_pizza(function you might have written in this program file the general syntax for providing an alias isfrom module_name import function_name as fn
179
you can also provide an alias for module name giving module short aliaslike for pizzaallows you to call the module' functions more quickly calling make_pizza(is more concise than calling pizza make_pizza()import pizza as make_pizza( 'pepperoni' make_pizza( 'mushrooms''green peppers''extra cheese'the module pizza is given the alias in the import statementbut all of the module' functions retain their original names calling the functions by writing make_pizza(is not only more concise than writing pizza make_pizza()but also redirects your attention from the module name and allows you to focus on the descriptive names of its functions these function nameswhich clearly tell you what each function doesare more important to the readability of your code than using the full module name the general syntax for this approach isimport module_name as mn importing all functions in module you can tell python to import every function in module by using the asterisk (*operatorfrom pizza import make_pizza( 'pepperoni'make_pizza( 'mushrooms''green peppers''extra cheese'the asterisk in the import statement tells python to copy every function from the module pizza into this program file because every function is importedyou can call each function by name without using the dot notation howeverit' best not to use this approach when you're working with larger modules that you didn' writeif the module has function name that matches an existing name in your projectyou can get some unexpected results python may see several functions or variables with the same nameand instead of importing all the functions separatelyit will overwrite the functions the best approach is to import the function or functions you wantor import the entire module and use the dot notation this leads to clear code that' easy to read and understand include this section so you'll recognize import statements like the following when you see them in other people' codefrom module_name import functions
180
you need to keep few details in mind when you're styling functions functions should have descriptive namesand these names should use lowercase letters and underscores descriptive names help you and others understand what your code is trying to do module names should use these conventions as well every function should have comment that explains concisely what the function does this comment should appear immediately after the function definition and use the docstring format in well-documented functionother programmers can use the function by reading only the description in the docstring they should be able to trust that the code works as describedand as long as they know the name of the functionthe arguments it needsand the kind of value it returnsthey should be able to use it in their programs if you specify default value for parameterno spaces should be used on either side of the equal signdef function_name(parameter_ parameter_ ='default value'the same convention should be used for keyword arguments in function callsfunction_name(value_ parameter_ ='value'pep (you limit lines of code to characters so every line is visible in reasonably sized editor window if set of parameters causes function' definition to be longer than characterspress enter after the opening parenthesis on the definition line on the next linepress tab twice to separate the list of arguments from the body of the functionwhich will only be indented one level most editors automatically line up any additional lines of parameters to match the indentation you have established on the first linedef function_nameparameter_ parameter_ parameter_ parameter_ parameter_ parameter_ )function body if your program or module has more than one functionyou can separate each by two blank lines to make it easier to see where one function ends and the next one begins all import statements should be written at the beginning of file the only exception is if you use comments at the beginning of your file to describe the overall program
181
- printing modelsput the functions for the example print_models py in separate file called printing_functions py write an import statement at the top of print_models pyand modify the file to use the imported functions - importsusing program you wrote that has one function in itstore that function in separate file import the function into your main program fileand call the function using each of these approachesimport module_name from module_name import function_name from module_name import function_name as fn import module_name as mn from module_name import - styling functionschoose any three programs you wrote for this and make sure they follow the styling guidelines described in this section summary in this you learned how to write functions and to pass arguments so that your functions have access to the information they need to do their work you learned how to use positional and keyword argumentsand how to accept an arbitrary number of arguments you saw functions that display output and functions that return values you learned how to use functions with listsdictionariesif statementsand while loops you also saw how to store your functions in separate files called modulesso your program files will be simpler and easier to understand finallyyou learned to style your functions so your programs will continue to be well-structured and as easy as possible for you and others to read one of your goals as programmer should be to write simple code that does what you want it toand functions help you do this they allow you to write blocks of code and leave them alone once you know they work when you know function does its job correctlyyou can trust that it will continue to work and move on to your next coding task functions allow you to write code once and then reuse that code as many times as you want when you need to run the code in functionall you need to do is write one-line call and the function does its job when you need to modify function' behavioryou only have to modify one block of codeand your change takes effect everywhere you've made call to that function using functions makes your programs easier to readand good function names summarize what each part of program does reading series of function calls gives you much quicker sense of what program does than reading long series of code blocks functions
182
of your program' work is done by set of functionseach of which has specific jobit' much easier to test and maintain the code you've written you can write separate program that calls each function and tests whether each function works in all the situations it may encounter when you do thisyou can be confident that your functions will work properly each time you call them in you'll learn to write classes classes combine functions and data into one neat package that can be used in flexible and efficient ways
183
cl asses object-oriented programming is one of the most effective approaches to writing software in object-oriented programming you write classes that represent real-world things and situationsand you create objects based on these classes when you write classyou define the general behavior that whole category of objects can have when you create individual objects from the classeach object is automatically equipped with the general behavioryou can then give each object whatever unique traits you desire you'll be amazed how well real-world situations can be modeled with object-oriented programming making an object from class is called instantiationand you work with instances of class in this you'll write classes and create instances of those classes you'll specify the kind of information that can be stored in instancesand you'll define actions that can be taken with these instances you'll also write classes that extend the functionality of existing classesso
184
understanding object-oriented programming will help you see the world as programmer does it'll help you really know your codenot just what' happening line by linebut also the bigger concepts behind it knowing the logic behind classes will train you to think logically so you can write programs that effectively address almost any problem you encounter classes also make life easier for you and the other programmers you'll need to work with as you take on increasingly complex challenges when you and other programmers write code based on the same kind of logicyou'll be able to understand each other' work your programs will make sense to many collaboratorsallowing everyone to accomplish more creating and using class you can model almost anything using classes let' start by writing simple classdogthat represents dog--not one dog in particularbut any dog what do we know about most pet dogswellthey all have name and age we also know that most dogs sit and roll over those two pieces of information (name and ageand those two behaviors (sit and roll overwill go in our dog class because they're common to most dogs this class will tell python how to make an object representing dog after our class is writtenwe'll use it to make individual instanceseach of which represents one specific dog creating the dog class each instance created from the dog class will store name and an ageand we'll give each dog the ability to sit(and roll_over()dog py class dog() """ simple attempt to model dog "" def __init__(selfnameage)"""initialize name and age attributes ""self name name self age age def sit(self)"""simulate dog sitting in response to command ""print(self name title(is now sitting "def roll_over(self)"""simulate rolling over in response to command ""print(self name title(rolled over!"
185
throughout this and have lots of time to get used to it at we define class called dog by conventioncapitalized names refer to classes in python the parentheses in the class definition are empty because we're creating this class from scratch at we write docstring describing what this class does the __init__(method function that' part of class is method everything you learned about functions applies to methods as wellthe only practical difference for now is the way we'll call methods the __init__(method at is special method python runs automatically whenever we create new instance based on the dog class this method has two leading underscores and two trailing underscoresa convention that helps prevent python' default method names from conflicting with your method names we define the __init__(method to have three parametersselfnameand age the self parameter is required in the method definitionand it must come first before the other parameters it must be included in the definition because when python calls this __init__(method later (to create an instance of dog)the method call will automatically pass the self argument every method call associated with class automatically passes selfwhich is reference to the instance itselfit gives the individual instance access to the attributes and methods in the class when we make an instance of dogpython will call the __init__(method from the dog class we'll pass dog( name and an age as argumentsself is passed automaticallyso we don' need to pass it whenever we want to make an instance from the dog classwe'll provide values for only the last two parametersname and age the two variables defined at each have the prefix self any variable prefixed with self is available to every method in the classand we'll also be able to access these variables through any instance created from the class self name name takes the value stored in the parameter name and stores it in the variable namewhich is then attached to the instance being created the same process happens with self age age variables that are accessible through instances like this are called attributes the dog class has two other methods definedsit(and roll_over( because these methods don' need additional information like name or agewe just define them to have one parameterself the instances we create later will have access to these methods in other wordsthey'll be able to sit and roll over for nowsit(and roll_over(don' do much they simply print message saying the dog is sitting or rolling over but the concept can be extended to realistic situationsif this class were part of an actual computer gamethese methods would contain code to make an animated dog sit and roll over if this class was written to control robotthese methods would direct movements that cause dog robot to sit and roll over classes
186
when you create class in python you need to make one minor change you include the term object in parentheses when you create classclass classname(object)--snip-this makes python classes behave more like python classeswhich makes your work easier overall the dog class would be defined like this in python class dog(object)--snip-making an instance from class think of class as set of instructions for how to make an instance the class dog is set of instructions that tells python how to make individual instances representing specific dogs let' make an instance representing specific dogclass dog()--snip- my_dog dog('willie' print("my dog' name is my_dog name title(" print("my dog is str(my_dog ageyears old "the dog class we're using here is the one we just wrote in the previous example at we tell python to create dog whose name is 'willieand whose age is when python reads this lineit calls the __init__(method in dog with the arguments 'willieand the __init__(method creates an instance representing this particular dog and sets the name and age attributes using the values we provided the __init__(method has no explicit return statementbut python automatically returns an instance representing this dog we store that instance in the variable my_dog the naming convention is helpful herewe can usually assume that capitalized name like dog refers to classand lowercase name like my_dog refers to single instance created from class accessing attributes to access the attributes of an instanceyou use dot notation at we access the value of my_dog' attribute name by writingmy_dog name dot notation is used often in python this syntax demonstrates how python finds an attribute' value here python looks at the instance my_dog
187
to work with the attribute age in our first print statementmy_dog name title(makes 'willie'the value of my_dog' name attributestart with capital letter in the second print statementstr(my_dog ageconverts the value of my_dog' age attributeto string the output is summary of what we know about my_dogmy dog' name is willie my dog is years old calling methods after we create an instance from the class dogwe can use dot notation to call any method defined in dog let' make our dog sit and roll overclass dog()--snip-my_dog dog('willie' my_dog sit(my_dog roll_over(to call methodgive the name of the instance (in this casemy_dogand the method you want to callseparated by dot when python reads my_dog sit()it looks for the method sit(in the class dog and runs that code python interprets the line my_dog roll_over(in the same way now willie does what we tell him towillie is now sitting willie rolled overthis syntax is quite useful when attributes and methods have been given appropriately descriptive names like nameagesit()and roll_over()we can easily infer what block of codeeven one we've never seen beforeis supposed to do creating multiple instances you can create as many instances from class as you need let' create second dog called your_dogclass dog()--snip-my_dog dog('willie' your_dog dog('lucy' print("my dog' name is my_dog name title("print("my dog is str(my_dog ageyears old "my_dog sit(classes
188
print("your dog is str(your_dog ageyears old "your_dog sit(in this example we create dog named willie and dog named lucy each dog is separate instance with its own set of attributescapable of the same set of actionsmy dog' name is willie my dog is years old willie is now sitting your dog' name is lucy your dog is years old lucy is now sitting even if we used the same name and age for the second dogpython would still create separate instance from the dog class you can make as many instances from one class as you needas long as you give each instance unique variable name or it occupies unique spot in list or dictionary try it yourse lf - restaurantmake class called restaurant the __init__(method for restaurant should store two attributesa restaurant_name and cuisine_type make method called describe_restaurant(that prints these two pieces of informationand method called open_restaurant(that prints message indicating that the restaurant is open make an instance called restaurant from your class print the two attributes individuallyand then call both methods - three restaurantsstart with your class from exercise - create three different instances from the classand call describe_restaurant(for each instance - usersmake class called user create two attributes called first_name and last_nameand then create several other attributes that are typically stored in user profile make method called describe_user(that prints summary of the user' information make another method called greet_user(that prints personalized greeting to the user create several instances representing different usersand call both methods for each user
189
you can use classes to represent many real-world situations once you write classyou'll spend most of your time working with instances created from that class one of the first tasks you'll want to do is modify the attributes associated with particular instance you can modify the attributes of an instance directly or write methods that update attributes in specific ways the car class let' write new class representing car our class will store information about the kind of car we're working withand it will have method that summarizes this informationcar py class car()""" simple attempt to represent car "" def __init__(selfmakemodelyear)"""initialize attributes to describe car ""self make make self model model self year year def get_descriptive_name(self)"""return neatly formatted descriptive name ""long_name str(self yearself make self model return long_name title( my_new_car car('audi'' ' print(my_new_car get_descriptive_name()at in the car classwe define the __init__(method with the self parameter firstjust like we did before with our dog class we also give it three other parametersmakemodeland year the __init__(method takes in these parameters and stores them in the attributes that will be associated with instances made from this class when we make new car instancewe'll need to specify makemodeland year for our instance at we define method called get_descriptive_name(that puts car' yearmakeand model into one string neatly describing the car this will spare us from having to print each attribute' value individually to work with the attribute values in this methodwe use self makeself modeland self year at we make an instance from the car class and store it in the variable my_new_car then we call get_descriptive_name(to show what kind of car we have audi to make the class more interestinglet' add an attribute that changes over time we'll add an attribute that stores the car' overall mileage classes
190
every attribute in class needs an initial valueeven if that value is or an empty string in some casessuch as when setting default valueit makes sense to specify this initial value in the body of the __init__(methodif you do this for an attributeyou don' have to include parameter for that attribute let' add an attribute called odometer_reading that always starts with value of we'll also add method read_odometer(that helps us read each car' odometerclass car() def __init__(selfmakemodelyear)"""initialize attributes to describe car ""self make make self model model self year year self odometer_reading def get_descriptive_name(self)--snip- def read_odometer(self)"""print statement showing the car' mileage ""print("this car has str(self odometer_readingmiles on it "my_new_car car('audi'' ' print(my_new_car get_descriptive_name()my_new_car read_odometer(this time when python calls the __init__(method to create new instanceit stores the makemodeland year values as attributes like it did in the previous example then python creates new attribute called odometer_reading and sets its initial value to we also have new method called read_odometer(at that makes it easy to read car' mileage our car starts with mileage of audi this car has miles on it not many cars are sold with exactly miles on the odometerso we need way to change the value of this attribute modifying attribute values you can change an attribute' value in three waysyou can change the value directly through an instanceset the value through methodor increment the value (add certain amount to itthrough method let' look at each of these approaches
191
the simplest way to modify the value of an attribute is to access the attribute directly through an instance here we set the odometer reading to directlyclass car()--snip-my_new_car car('audi'' ' print(my_new_car get_descriptive_name() my_new_car odometer_reading my_new_car read_odometer(at we use dot notation to access the car' odometer_reading attribute and set its value directly this line tells python to take the instance my_new_carfind the attribute odometer_reading associated with itand set the value of that attribute to audi this car has miles on it sometimes you'll want to access attributes directly like thisbut other times you'll want to write method that updates the value for you modifying an attribute' value through method it can be helpful to have methods that update certain attributes for you instead of accessing the attribute directlyyou pass the new value to method that handles the updating internally here' an example showing method called update_odometer()class car()--snip- def update_odometer(selfmileage)"""set the odometer reading to the given value ""self odometer_reading mileage my_new_car car('audi'' ' print(my_new_car get_descriptive_name() my_new_car update_odometer( my_new_car read_odometer(the only modification to car is the addition of update_odometer(at this method takes in mileage value and stores it in self odometer_reading at we call update_odometer(and give it as an argument (corresponding classes
192
reading to and read_odometer(prints the reading audi this car has miles on it we can extend the method update_odometer(to do additional work every time the odometer reading is modified let' add little logic to make sure no one tries to roll back the odometer readingclass car()--snip- def update_odometer(selfmileage)""set the odometer reading to the given value reject the change if it attempts to roll the odometer back ""if mileage >self odometer_readingself odometer_reading mileage elseprint("you can' roll back an odometer!"now update_odometer(checks that the new reading makes sense before modifying the attribute if the new mileagemileageis greater than or equal to the existing mileageself odometer_readingyou can update the odometer reading to the new mileage if the new mileage is less than the existing mileageyou'll get warning that you can' roll back an odometer incrementing an attribute' value through method sometimes you'll want to increment an attribute' value by certain amount rather than set an entirely new value say we buy used car and put miles on it between the time we buy it and the time we register it here' method that allows us to pass this incremental amount and add that value to the odometer readingclass car()--snip-def update_odometer(selfmileage)--snip- def increment_odometer(selfmiles)"""add the given amount to the odometer reading ""self odometer_reading +miles my_used_car car('subaru''outback' print(my_used_car get_descriptive_name() my_used_car update_odometer( my_used_car read_odometer(
193
my_used_car read_odometer(the new method increment_odometer(at takes in number of milesand adds this value to self odometer_reading at we create used carmy_used_car we set its odometer to , by calling update_odometer(and passing it at at we call increment_odometer(and pass it to add the miles that we drove between buying the car and registering it subaru outback this car has miles on it this car has miles on it you can easily modify this method to reject negative increments so no one uses this function to roll back an odometer note you can use methods like this to control how users of your program update values such as an odometer readingbut anyone with access to the program can set the odometer reading to any value by accessing the attribute directly effective security takes extreme attention to detail in addition to basic checks like those shown here try it yourse lf - number servedstart with your program from exercise - (page add an attribute called number_served with default value of create an instance called restaurant from this class print the number of customers the restaurant has servedand then change this value and print it again add method called set_number_served(that lets you set the number of customers that have been served call this method with new number and print the value again add method called increment_number_served(that lets you increment the number of customers who've been served call this method with any number you like that could represent how many customers were served insaya day of business - login attemptsadd an attribute called login_attempts to your user class from exercise - (page write method called increment_ login_attempts(that increments the value of login_attempts by write another method called reset_login_attempts(that resets the value of login_ attempts to make an instance of the user class and call increment_login_attempts(several times print the value of login_attempts to make sure it was incremented properlyand then call reset_login_attempts(print login_attempts again to make sure it was reset to classes
194
you don' always have to start from scratch when writing class if the class you're writing is specialized version of another class you wroteyou can use inheritance when one class inherits from anotherit automatically takes on all the attributes and methods of the first class the original class is called the parent classand the new class is the child class the child class inherits every attribute and method from its parent class but is also free to define new attributes and methods of its own the __init__(method for child class the first task python has when creating an instance from child class is to assign values to all attributes in the parent class to do thisthe __init__(method for child class needs help from its parent class as an examplelet' model an electric car an electric car is just specific kind of carso we can base our new electriccar class on the car class we wrote earlier then we'll only have to write code for the attributes and behavior specific to electric cars let' start by making simple version of the electriccar classwhich does everything the car class doeselectric_car py class car()""" simple attempt to represent car ""def __init__(selfmakemodelyear)self make make self model model self year year self odometer_reading def get_descriptive_name(self)long_name str(self yearself make self model return long_name title(def read_odometer(self)print("this car has str(self odometer_readingmiles on it "def update_odometer(selfmileage)if mileage >self odometer_readingself odometer_reading mileage elseprint("you can' roll back an odometer!"def increment_odometer(selfmiles)self odometer_reading +miles class electriccar(car)"""represent aspects of carspecific to electric vehicles ""
195
def __init__(selfmakemodelyear)"""initialize attributes of the parent class ""super(__init__(makemodelyeary my_tesla electriccar('tesla''model ' print(my_tesla get_descriptive_name()at we start with car when you create child classthe parent class must be part of the current file and must appear before the child class in the file at we define the child classelectriccar the name of the parent class must be included in parentheses in the definition of the child class the __init__(method at takes in the information required to make car instance the super(function at is special function that helps python make connections between the parent and child class this line tells python to call the __init__(method from electriccar' parent classwhich gives an electriccar instance all the attributes of its parent class the name super comes from convention of calling the parent class superclass and the child class subclass we test whether inheritance is working properly by trying to create an electric car with the same kind of information we' provide when making regular car at we make an instance of the electriccar classand store it in my_tesla this line calls the __init__(method defined in electriccarwhich in turn tells python to call the __init__(method defined in the parent class car we provide the arguments 'tesla''model 'and aside from __init__()there are no attributes or methods yet that are particular to an electric car at this point we're just making sure the electric car has the appropriate car behaviors tesla model the electriccar instance works just like an instance of carso now we can begin defining attributes and methods specific to electric cars inheritance in python in python inheritance is slightly different the electriccar class would look like thisclass car(object)def __init__(selfmakemodelyear)--snip-class electriccar(car)def __init__(selfmakemodelyear)super(electriccarself__init__(makemodelyear--snip-classes
196
class and the self object these arguments are necessary to help python make proper connections between the parent and child classes when you use inheritance in python make sure you define the parent class using the object syntax as well defining attributes and methods for the child class once you have child class that inherits from parent classyou can add any new attributes and methods necessary to differentiate the child class from the parent class let' add an attribute that' specific to electric cars ( batteryfor exampleand method to report on this attribute we'll store the battery size and write method that prints description of the batteryclass car()--snip-class electriccar(car)"""represent aspects of carspecific to electric vehicles "" def __init__(selfmakemodelyear)""initialize attributes of the parent class then initialize attributes specific to an electric car ""super(__init__(makemodelyearself battery_size def describe_battery(self)"""print statement describing the battery size ""print("this car has str(self battery_size"-kwh battery "my_tesla electriccar('tesla''model ' print(my_tesla get_descriptive_name()my_tesla describe_battery(at we add new attribute self battery_size and set its initial value tosay this attribute will be associated with all instances created from the electriccar class but won' be associated with any instances of car we also add method called describe_battery(that prints information about the battery at when we call this methodwe get description that is clearly specific to an electric car tesla model this car has -kwh battery there' no limit to how much you can specialize the electriccar class you can add as many attributes and methods as you need to model an electric car to whatever degree of accuracy you need an attribute or method that could belong to any carrather than one that' specific to an electric
197
anyone who uses the car class will have that functionality available as welland the electriccar class will only contain code for the information and behavior specific to electric vehicles overriding methods from the parent class you can override any method from the parent class that doesn' fit what you're trying to model with the child class to do thisyou define method in the child class with the same name as the method you want to override in the parent class python will disregard the parent class method and only pay attention to the method you define in the child class say the class car had method called fill_gas_tank(this method is meaningless for an all-electric vehicleso you might want to override this method here' one way to do thatdef electriccar(car)--snip-def fill_gas_tank()"""electric cars don' have gas tanks ""print("this car doesn' need gas tank!"now if someone tries to call fill_gas_tank(with an electric carpython will ignore the method fill_gas_tank(in car and run this code instead when you use inheritanceyou can make your child classes retain what you need and override anything you don' need from the parent class instances as attributes when modeling something from the real world in codeyou may find that you're adding more and more detail to class you'll find that you have growing list of attributes and methods and that your files are becoming lengthy in these situationsyou might recognize that part of one class can be written as separate class you can break your large class into smaller classes that work together for exampleif we continue adding detail to the electriccar classwe might notice that we're adding many attributes and methods specific to the car' battery when we see this happeningwe can stop and move those attributes and methods to separate class called battery then we can use battery instance as an attribute in the electriccar classclass car()--snip- class battery()""" simple attempt to model battery for an electric car "" def __init__(selfbattery_size= )"""initialize the battery' attributes ""self battery_size battery_size classes
198
def describe_battery(self)"""print statement describing the battery size ""print("this car has str(self battery_size"-kwh battery "class electriccar(car)"""represent aspects of carspecific to electric vehicles "" def __init__(selfmakemodelyear)""initialize attributes of the parent class then initialize attributes specific to an electric car ""super(__init__(makemodelyearself battery battery(my_tesla electriccar('tesla''model ' print(my_tesla get_descriptive_name()my_tesla battery describe_battery(at we define new class called battery that doesn' inherit from any other class the __init__(method at has one parameterbattery_sizein addition to self this is an optional parameter that sets the battery' size to if no value is provided the method describe_battery(has been moved to this class as well in the electriccar classwe now add an attribute called self battery this line tells python to create new instance of battery (with default size of because we're not specifying valueand store that instance in the attribute self battery this will happen every time the __init__(method is calledany electriccar instance will now have battery instance created automatically we create an electric car and store it in the variable my_tesla when we want to describe the batterywe need to work through the car' battery attributemy_tesla battery describe_battery(this line tells python to look at the instance my_teslafind its battery attributeand call the method describe_battery(that' associated with the battery instance stored in the attribute the output is identical to what we saw previously tesla model this car has -kwh battery
199
in as much detail as we want without cluttering the electriccar class let' add another method to battery that reports the range of the car based on the battery sizeclass car()--snip-class battery()--snip- def get_range(self)"""print statement about the range this battery provides ""if self battery_size = range elif self battery_size = range message "this car can go approximately str(rangemessage +miles on full charge print(messageclass electriccar(car)--snip-my_tesla electriccar('tesla''model ' print(my_tesla get_descriptive_name()my_tesla battery describe_battery( my_tesla battery get_range(the new method get_range(at performs some simple analysis if the battery' capacity is kwhget_range(sets the range to milesand if the capacity is kwhit sets the range to miles it then reports this value when we want to use this methodwe again have to call it through the car' battery attribute at the output tells us the range of the car based on its battery size tesla model this car has -kwh battery this car can go approximately miles on full charge modeling real-world objects as you begin to model more complicated items like electric carsyou'll wrestle with interesting questions is the range of an electric car property of the battery or of the carif we're only describing one carit' probably fine to maintain the association of the method get_range(with the battery class but if we're describing manufacturer' entire line of carswe probably want to move get_range(to the electriccar class the get_range(method classes