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 a...
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 ...
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...
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 over...
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'...
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 ...
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...
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 ...
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 ...
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 ...
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 m...
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 ch...
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 ...
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...
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' stor...
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 exampl...
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 rep...
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 easie...
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 t...
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 acces...
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 di...
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 pai...
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("th...
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...
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'l...
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 ...
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 u...
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 ...
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...
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''pytho...
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 taki...
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_...
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 o...
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...
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...
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 lis...
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' ...
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 t...
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 sto...
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 ...
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 ...
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 l...
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 ...
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 number...
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 cou...
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 th...
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 youente...
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 u...
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 co...
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 timeespecia...
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 wi...
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(...
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 dictionar...
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...
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 wanta...
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...
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 ...
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 produc...
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...
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 wi...
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 ...
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 ani...
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='har...
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 messa...
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...
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 ma...
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 da...
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 t...
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...
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 pri...
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 th...
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...
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 a...
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...
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...
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('albe...
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 - us...
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 ma...
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 ...
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 giv...
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 h...
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 impor...
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 ...
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 object...
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 a...
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 funct...
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(objec...
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...
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...
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 wri...
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...
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 acces...
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)""s...
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 buyi...
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 class...
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 i...
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 ...
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 mod...
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 speci...
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 sel...