id
int64
0
25.6k
text
stringlengths
0
4.59k
2,500
begins and endsthey are not part of the string value note you can also use this function to put blank line on the screenjust call print(with nothing in between the parentheses when you write function namethe opening and closing parentheses at the end identify it as the name of function this is why in this bookyou'll se...
2,501
len('hello' len('my very energetic monster just scarfed nachos ' len('' just like those exampleslen(mynameevaluates to an integer it is then passed to print(to be displayed on the screen the print(function allows you to pass it either integer values or string valuesbut notice the error that shows up when you type the f...
2,502
years old evaluates to ' am ' years old 'which in turn evaluates to ' am years old this is the value that is passed to the print(function the str()int()and float(functions will evaluate to the stringintegerand floating-point forms of the value you passrespectively try converting some values in the interactive shell wit...
2,503
note that if you pass value to int(that it cannot evaluate as an integerpython will display an error message int(' 'traceback (most recent call last)file ""line in int(' 'valueerrorinvalid literal for int(with base ' int('twelve'traceback (most recent call last)file ""line in int('twelve'valueerrorinvalid literal for i...
2,504
input(function always returns string (even if the user typed in number)you can use the int(myagecode to return an integer value of the string in myage this integer value is then added to in the expression int(myage the result of this addition is passed to the str(functionstr(int(myage the string value returned is then ...
2,505
to repeat based on the values it has this is known as flow controland it allows you to write programs that make intelligent decisions practice questions which of the following are operatorsand which are values'hello- which of the following is variableand which is stringspam 'spam name three data types what is an expres...
2,506
' have eaten burritos extra creditsearch online for the python documentation for the len(function it will be on web page titled "built-in functions skim the list of other functions python haslook up what the round(function doesand experiment with it in the interactive shell
2,507
flow control soyou know the basics of individual instructions and that program is just series of instructions but programming' real strength isn' just running one instruction after another like weekend errand list based on how expressions evaluatea program can decide to skip instructionsrepeat themor choose one of seve...
2,508
is rainingno go outside yes have umbrellano wait while yes no is rainingyes end figure - flowchart to tell you what to do if it is raining in flowchartthere is usually more than one way to go from the start to the end the same is true for lines of code in computer program flowcharts represent these branching points wit...
2,509
spam true true traceback (most recent call last)file ""line in true nameerrorname 'trueis not defined true syntaxerrorcan' assign to keyword like any other valueboolean values are used in expressions and can be stored in variables if you don' use the proper case or you try to use true and false for variable names pytho...
2,510
true 'hello='hellofalse 'dog!'cattrue true =true true true !false true = true =' false note that an integer or floating-point value will always be unequal to string value the expression =' evaluates to false because python considers the integer to be different from the string ' the operatorson the other handwork proper...
2,511
some other valuelike in the eggcount examples (after allinstead of entering 'dog!'catin your codeyou could have just entered true you'll see more examples of this later when you learn about flow control statements boolean operators the three boolean operators (andorand notare used to compare boolean values like compari...
2,512
expression evaluates to true or true true true or false true false or true true false or false false the not operator unlike and and orthe not operator operates on only one boolean value (or expressionthis makes it unary operator the not operator simply evaluates to the opposite boolean value not true false not not not...
2,513
you can think of the computer' evaluation process for ( and ( as the following( and ( true and ( true and true true you can also use multiple boolean operators in an expressionalong with the comparison operators = and not = and = true the boolean operators have an order of operations just like the math operators do aft...
2,514
let' find the blocks in part of small game programshown herename 'marypassword 'swordfishif name ='mary'print('hellomary'if password ='swordfish'print('access granted 'elseprint('wrong password 'you can view the execution of this program at the first block of code starts at the line print('hellomary'and contains all th...
2,515
colon starting on the next linean indented block of code (called the if clausefor examplelet' say you have some code that checks to see whether someone' name is alice (pretend name was assigned some value earlier if name ='alice'print('hialice 'all flow control statements end with colon and are followed by new block of...
2,516
else statement to offer different greeting if the person' name isn' alice if name ='alice'print('hialice 'elseprint('hellostranger 'figure - shows what flowchart of this code would look like start name ='alicetrue print('hialice 'false print('hellostranger 'end figure - the flowchart for an else statement elif statemen...
2,517
print('you are not alicekiddo 'this timeyou check the person' ageand the program will tell them something different if they're younger than you can see the flowchart for this in figure - start name ='alicetrue print('hialice 'true print('you are not alicekiddo 'false age false end figure - the flowchart for an elif sta...
2,518
elif age print('you are not alicegrannie 'you can view the execution of this program at herei've added two more elif statements to make the name checker greet person with different answers based on age figure - shows the flowchart for this start name ='alicetrue print('hialice 'true print('you are not alicekiddo 'true ...
2,519
them to introduce bug remember that the rest of the elif clauses are automatically skipped once true condition has been foundso if you swap around some of the clauses in vampire pyyou run into problem change the code to look like the followingand save it as vampire pyname 'carolage if name ='alice'print('hialice 'elif ...
2,520
to be sure that at least one clause is executedclose the structure with an else statement start name ='alicetrue print('hialice 'true print('you are not alicekiddo 'true print('you are not alicegrannie ' print('unlike youalice is not an undeadimmortal vampire 'false age false age false age true false end figure - the f...
2,521
name ='alicetrue print('hialice 'true print('you are not alicekiddo 'false age false print('you are neither alice nor little kid 'end figure - flowchart for the previous littlekid py program while loop statements you can make block of code execute over and over again using while statement the code in while clause will ...
2,522
difference is in how they behave at the end of an if clausethe program execution continues after the if statement but at the end of while clausethe program execution jumps back to the start of the while statement the while clause is often called the while loop or just the loop let' look at an if statement and while loo...
2,523
true spam print('helloworld 'spam spam false end figure - the flowchart for the while statement code the code with the if statement checks the conditionand it prints helloworld only once if that condition is true the code with the while loopon the other handwill print it five times the loop stops after five prints beca...
2,524
execution will enter the while loop' clause the code inside this clause asks the user to type their namewhich is assigned to the name variable since this is the last line of the blockthe execution moves back to the start of the while loop and reevaluates the condition if the value in name is not equal to the string 'yo...
2,525
your name thank youif you never enter your namethen the while loop' condition will never be falseand the program will just keep asking forever herethe input(call lets the user enter the right string to make the program move on in other programsthe condition might never actually changeand that can be problem let' look a...
2,526
true true print('please type your name 'name input( false name ='your nametrue break false print('thank you!'end figure - the flowchart for the yourname py program with an infinite loop note that the path will logically never happenbecause the loop condition is always true continue statements like break statementsconti...
2,527
if you ever run program that has bug causing it to get stuck in an infinite looppress ctrl- or select shell restart shell from idle' menu this will send keyboardinterrupt error to your program and cause it to stop immediately try stopping program by creating simple infinite loop in the file editorand save the program a...
2,528
true true print('who are you?'name input( false true continue name !'joefalse print('hellojoe what is the password(it is fish )'password input(false break password ='swordfishtrue print('access granted 'end figure - flowchart for swordfish py the path will logically never happenbecause the loop condition is always true
2,529
conditions will consider some values in other data types equivalent to true and false when used in conditions and '(the empty stringare considered falsewhile all other values are considered true for examplelook at the following programname 'while not nameprint('enter your name:'name input(print('how many guests will yo...
2,530
the while loop keeps looping while its condition is true (which is the reason for its name)but what if you want to execute block of code only certain number of timesyou can do this with for loop statement and the range(function in codea for statement looks something like for in range( )and includes the followingthe for...
2,531
print('my name is'looping for in range ( print('jimmy five times (str( ')'done looping end figure - the flowchart for fivetimes py as another for loop exampleconsider this story about the mathematician carl friedrich gauss when gauss was boya teacher wanted to give the class some busywork the teacher told them to add u...
2,532
you can actually use while loop to do the same thing as for loopfor loops are just more concise let' rewrite fivetimes py to use while loop equivalent of for loop print('my name is' while print('jimmy five times (str( ')' you can view the execution of this program at /fivetimeswhileif you run this programthe output sho...
2,533
for for loops for example ( never apologize for my puns)you can even use negative number for the step argument to make the for loop count down instead of up for in range( - - )print(ithis for loop would have the following output running for loop to print with range( - - should print from five down to zero importing mod...
2,534
when you save your python scriptstake care not to give them name that is used by one of python' modulessuch as random pysys pyos pyor math py if you accidentally name one of your programssayrandom pyand use an import random statement in another programyour program would import your random py file instead of python' ran...
2,535
the last flow control concept to cover is how to terminate the program programs always terminate if the program execution reaches the bottom of the instructions howeveryou can cause the program to terminateor exitbefore the last instruction by calling the sys exit(function since this function is in the sys moduleyou ha...
2,536
guessthenumber pythis is guess the number game import random secretnumber random randint( print(' am thinking of number between and 'ask the player to guess times for guessestaken in range( )print('take guess 'guess int(input()if guess secretnumberprint('your guess is too low 'elif guess secretnumberprint('your guess i...
2,537
variable named guess if guess secretnumberprint('your guess is too low 'elif guess secretnumberprint('your guess is too high 'these few lines of code check to see whether the guess is less than or greater than the secret number in either casea hint is printed to the screen elsebreak this condition is the correct guessi...
2,538
enter your move( )ock ( )aper ( )cissors or ( )uit type the following source code into the file editorand save the file as rpsgame pyimport randomsys print('rockpaperscissors'these variables keep track of the number of winslossesand ties wins losses ties while truethe main game loop print('% wins% losses% ties(winsloss...
2,539
print('you win!'wins wins elif playermove ='sand computermove =' 'print('you win!'wins wins elif playermove ='rand computermove =' 'print('you lose!'losses losses elif playermove ='pand computermove =' 'print('you lose!'losses losses elif playermove ='sand computermove =' 'print('you lose!'losses losses let' look at th...
2,540
if playermove =' 'print('rock versus 'elif playermove =' 'print('paper versus 'elif playermove =' 'print('scissors versus 'the player' move is displayed on the screen display what the computer choserandomnumber random randint( if randomnumber = computermove 'rprint('rock'elif randomnumber = computermove 'pprint('paper'...
2,541
and displays the results on the screen it also increments the winslossesor ties variable appropriately once the execution reaches the endit jumps back to the start of the main program loop to begin another game summary by using expressions that evaluate to true or false (also called conditions)you can write programs th...
2,542
print('ham'print('spam'print('spam' write code that prints hello if is stored in spamprints howdy if is stored in spamand prints greetingsif anything else is stored in spam what keys can you press if your program is stuck in an infinite loop what is the difference between break and continue what is the difference betwe...
2,543
functions you're already familiar with the print()input()and len(functions from the previous python provides several builtin functions like thesebut you can also write your own functions function is like miniprogram within program to better understand how functions worklet' create one enter this program into the file e...
2,544
/hellofuncthe first line is def statement which defines function named hello(the code in the block that follows the def statement is the body of the function this code is executed when the function is callednot when the function is first defined the hello(lines after the function are function calls in codea function ca...
2,545
when you call the print(or len(functionyou pass them valuescalled argumentsby typing them between the parentheses you can also define your own functions that accept arguments type this example into the file editor and save it as hellofunc pydef hello(name)print('hellonamehello('alice'hello('bob'when you run this progra...
2,546
is assigned to local variable named name variables that have arguments assigned to them are parameters it' easy to mix up these termsbut keeping them straight will ensure that you know precisely what the text in this means return values and return statements when you call the len(function and pass it an argument such a...
2,547
/magic ballwhen this program startspython first imports the random module then the getanswer(function is defined because the function is being defined (and not called)the execution skips over the code in it nextthe random randint(function is called with two arguments and it evaluates to random integer between and (incl...
2,548
definition with no return statement this is similar to how while or for loop implicitly ends with continue statement alsoif you use return statement without value (that isjust the return keyword by itself)then none is returned keyword arguments and the print(function most arguments are identified by their position in t...
2,549
will automatically separate them with single space enter the following into the interactive shellprint('cats''dogs''mice'cats dogs mice but you could replace the default separating string by passing the sep keyword argument different string enter the following into the interactive shellprint('cats''dogs''mice'sep=','ca...
2,550
abcdcallstack pydef ()print(' (starts' ( (print(' (returns'def ()print(' (starts' (print(' (returns'def ()print(' (starts'print(' (returns'def ()print(' (starts'print(' (returns' (if you run this programthe output will look like thisa(starts (starts (starts (returns (returns (starts (returns (returns you can view the e...
2,551
remember where to return if another function call is madepython puts another frame object on the call stack above the other one when function call returnspython removes frame object from the top of the stack and moves the execution to the line number stored in it note that frame objects are always added and removed fro...
2,552
code in the global scopeoutside of all functionscannot use any local variables howevercode in local scope can access global variables code in function' local scope cannot use variables in any other local scope you can use the same name for different variables if they are in different scopes that isthere can be local va...
2,553
new local scope is created whenever function is calledincluding when function is called from another function consider this programdef spam()eggs bacon(print(eggsdef bacon()ham eggs spam(you can view the execution of this program at /otherlocalscopeswhen the program startsthe spam(function is called and local scope is ...
2,554
technicallyit' perfectly acceptable to use the same variable name for global variable and local variables in different scopes in python butto simplify your lifeavoid doing this to see what happensenter the following code into the file editor and save it as localglobalsamename pydef spam()eggs 'spam localprint(eggsprint...
2,555
spam(print(eggswhen you run this programthe final print(call will output thisspam you can view the execution of this program at /globalstatementbecause eggs is declared global at the top of spam(when eggs is set to 'spamthis assignment is done to the globally scoped eggs no local eggs variable is created there are four...
2,556
/samenamelocalglobalin functiona variable will either always be global or always be local the code in function can' use local variable named eggs and then use the global eggs variable later in that same function note if you ever want to modify the value stored in global variable from in functionyou must use global stat...
2,557
right nowgetting an erroror exceptionin your python program means the entire program will crash you don' want this to happen in real-world programs insteadyou want the program to detect errorshandle themand then continue to run for exampleconsider the following programwhich has divide-byzero error open file editor wind...
2,558
immediately moves to the code in the except clause after running that codethe execution continues as normal the output of the previous program is as follows errorinvalid argument none you can view the execution of this program at /tryexceptzerodividenote that any errors that occur in function calls in try block will al...
2,559
***********************************type the following source code into the file editorand save the file as zigzag pyimport timesys indent how many spaces to indent indentincreasing true whether the indentation is increasing or not trywhile truethe main program loop print(indentend=''print('********'time sleep( pause fo...
2,560
user presses ctrl- while python program is runningpython raises the keyboardinterrupt exception if there is no tryexcept statement to catch this exceptionthe program crashes with an ugly error message howeverfor our programwe want it to cleanly handle the keyboardinterrupt exception by calling sys exit((the code for th...
2,561
functions are the primary way to compartmentalize your code into logical groups since the variables in functions exist in their own local scopesthe code in one function cannot directly affect the values of variables in other functions this limits what code could be changing the values of your variableswhich can be help...
2,562
for practicewrite programs to do the following tasks the collatz sequence write function named collatz(that has one parameter named number if number is eventhen collatz(should print number / and return this value if number is oddthen collatz(should print and return number then write program that lets the user type in a...
2,563
lists one more topic you'll need to understand before you can begin writing programs in earnest is the list data type and its cousinthe tuple lists and tuples can contain multiple valueswhich makes writing programs that handle large amounts of data easier and since lists themselves can contain other listsyou can use th...
2,564
list is value that contains multiple values in an ordered sequence the term list value refers to the list itself (which is value that can be stored in variable or passed to function like any other value)not the values inside the list value list value looks like this['cat''bat''rat''elephant'just as string values are ty...
2,565
'batspam[ 'ratspam[ 'elephant['cat''bat''rat''elephant'][ 'elephant'hellospam[ 'hellocat'the spam[ ate the spam[ 'the bat ate the cat notice that the expression 'hellospam[ evaluates to 'hello'catbecause spam[ evaluates to the string 'catthis expression in turn evaluates to the string value 'hellocatpython will give yo...
2,566
the value within the list value for examplespam[ ][ prints 'bat'the second value in the first list if you only use one indexthe program will print the full list value at that index negative indexes while indexes start at and go upyou can also use negative integers for the index the integer value - refers to the last in...
2,567
spam[ :['bat''rat''elephant'spam[:['cat''bat''rat''elephant'getting list' length with the len(function the len(function will return the number of values that are in list value passed to itjust like it can count the number of characters in string value enter the following into the interactive shellspam ['cat''dog''moose...
2,568
the del statement will delete values at an index in list all of the values in the list after the deleted value will be moved up one index for exampleenter the following into the interactive shellspam ['cat''bat''rat''elephant'del spam[ spam ['cat''bat''elephant'del spam[ spam ['cat''bat'the del statement can also be us...
2,569
print('the cat names are:'print(catname catname catname catname catname catname instead of using multiplerepetitive variablesyou can use single variable that contains list value for examplehere' new and improved version of the allmycats py program this new version uses single list and can store any number of cats that ...
2,570
in you learned about using for loops to execute block of code certain number of times technicallya for loop repeats the code block once for each item in list value for exampleif you ran this codefor in range( )print(ithe output of this program would be as follows this is because the return value from range( is sequence...
2,571
'howdyin ['hello''hi''howdy''heyas'true spam ['hello''hi''howdy''heyas''catin spam false 'howdynot in spam false 'catnot in spam true for examplethe following program lets the user type in pet name and then checks to see whether the name is in list of pets open new file editor windowenter the following codeand save it ...
2,572
equalor python will give you valueerrorcat ['fat''gray''loud'sizecolordispositionname cat traceback (most recent call last)file ""line in sizecolordispositionname cat valueerrornot enough values to unpack (expected got using the enumerate(function with lists instead of using the range(len(somelist)technique with for lo...
2,573
following into the interactive shellimport random people ['alice''bob''carol''david'random shuffle(peoplepeople ['carol''david''alice''bob'random shuffle(peoplepeople ['alice''david''bob''carol'augmented assignment operators when assigning value to variableyou will frequently use the variable itself for exampleafter as...
2,574
*operator can do string and list replication enter the following into the interactive shellspam 'hello,spam +world!spam 'hello world!bacon ['zophie'bacon * bacon ['zophie''zophie''zophie'methods method is the same thing as functionexcept it is "called ona value for exampleif list value were stored in spamyou would call...
2,575
to add new values to listuse the append(and insert(methods enter the following into the interactive shell to call the append(method on list value stored in the variable spamspam ['cat''dog''bat'spam append('moose'spam ['cat''dog''bat''moose'the previous append(method call adds the argument to the end of the list the in...
2,576
the remove(method is passed the value to be removed from the list it is called on enter the following into the interactive shellspam ['cat''bat''rat''elephant'spam remove('bat'spam ['cat''rat''elephant'attempting to delete value that does not exist in the list will result in valueerror error for exampleenter the follow...
2,577
sort the values in reverse order enter the following into the interactive shellspam sort(reverse=truespam ['elephants''dogs''cats''badgers''ants'there are three things you should note about the sort(method firstthe sort(method sorts the list in placedon' try to capture the return value by writing code like spam spam so...
2,578
in most casesthe amount of indentation for line of code tells python what block it is in there are some exceptions to this rulehowever for examplelists can actually span several lines in the source code file the indentation of these lines does not matterpython knows that the list is not finished until it sees the endin...
2,579
'very doubtful'print(messages[random randint( len(messages )]you can view the execution of this program at /magic ball when you run this programyou'll see that it works the same as the previous magic ball py program notice the expression you use as the index for messagesrandom randint ( len(messages this produces rando...
2,580
but lists and strings are different in an important way list value is mutable data typeit can have values addedremovedor changed howevera string is immutableit cannot be changed trying to reassign single character in string results in typeerror erroras you can see by entering the following into the interactive shellnam...
2,581
with new list value in the first examplethe list value that eggs ends up with is the same list value it started with it' just that this list has been changedrather than overwritten figure - depicts the seven changes made by the first seven lines in the previous interactive shell example figure - the del statement and t...
2,582
the tuple data type is almost identical to the list data typeexcept in two ways firsttuples are typed with parenthesesand )instead of square bracketsand for exampleenter the following into the interactive shelleggs ('hello' eggs[ 'helloeggs[ : ( len(eggs but the main way that tuples are different from lists is that tup...
2,583
just like how str( will return ' 'the string representation of the integer the functions list(and tuple(will return list and tuple versions of the values passed to them enter the following into the interactive shelland notice that the return value is of different data type than the value passedtuple(['cat''dog' ]('cat'...
2,584
cheese the cheese variable refers to the same list [ 'hello!' this might look odd to you the code touched only the cheese listbut it seems that both the cheese and spam lists have changed when you create the list you assign reference to it in the spam variable but the next line copies only the list reference in spam to...
2,585
also changedbecause both cheese and spam refer to the same list you can see this in figure - figure - cheese[ 'hello!modifies the list that both variables refer to although python variables technically contain references to valuespeople often casually say that the variable contains the value identity and the id(functio...
2,586
append(method doesn' create new list objectit changes the existing list object we call this "modifying the object in-place eggs ['cat''dog'this creates new list id(eggs eggs append('moose'append(modifies the list "in placeid(eggseggs still refers to the same list as before eggs ['bat''rat''cow'this creates new listwhic...
2,587
the copy module' copy(and deepcopy(functions although passing around references is often the handiest way to deal with lists and dictionariesif the function modifies the list or dictionary that is passedyou may not want these changes in the original list or dictionary value for thispython provides module named copy tha...
2,588
conway' game of life is an example of cellular automataa set of rules governing the behavior of field made up of discrete cells in practiceit creates pretty animation to look at you can draw out each step on graph paperusing the squares as cells filled-in square will be "aliveand an empty square will be "dead if living...
2,589
for in range(height)for in range(width)print(currentcells[ ][ ]end=''print the or space print(print newline at the end of the row calculate the next step' cells based on current step' cellsfor in range(width)for in range(height)get neighboring coordinates`widthensures leftcoord is always between and width leftcoord ( w...
2,590
random randint()time sleep()and copy deepcopy(functions create list of list for the cellsnextcells [for in range(width)column [create new column for in range(height)if random randint( = column append('#'add living cell elsecolumn append('add dead cell nextcells append(columnnextcells is list of column lists the very fi...
2,591
leftcoord ( width rightcoord ( width abovecoord ( height belowcoord ( height nextwe need to use two nested for loops to calculate each cell for the next step the living or dead state of the cell depends on the neighborsso let' first calculate the index of the cells to the leftrightaboveand below the current xand -coord...
2,592
currentcells[ ][ ]we can set nextcells[ ][yto either '#or after we loop over every possible xand -coordinatethe program takes -second pause by calling time sleep( then the program execution goes back to the start of the main program loop to continue with the next step several patterns have been discovered with names su...
2,593
' '' '' ' what does spam[int(int(' / )evaluate towhat does spam[- evaluate towhat does spam[: evaluate tofor the following three questionslet' say bacon contains the list [ 'cat' 'cat'true what does bacon index('cat'evaluate to what does bacon append( make the list value in bacon look like what does bacon remove('cat'm...
2,594
but isn' mathematically random human will almost never write down streak of six heads or six tails in roweven though it is highly likely to happen in truly random coin flips humans are predictably bad at being random write program to find out how often streak of six heads or streak of six tails comes up in randomly gen...
2,595
the image oo oo ooooooo ooooooo ooooo ooo hintyou will need to use loop in loop in order to print grid[ ][ ]then grid[ ][ ]then grid[ ][ ]and so onup to grid[ ][ this will finish the first rowso then print newline then your program should print grid[ ][ ]then grid[ ][ ]then grid[ ][ ]and so on the last thing your progr...
2,596
dictionaries and ruc ur ing data in this will cover the dictionary data typewhich provides flexible way to access and organize data thencombining dictionaries with your knowledge of lists from the previous you'll learn how to create data structure to model tic-tac-toe board the dictionary data type like lista dictionar...
2,597
'size''color'and 'dispositionthe values for these keys are 'fat''gray'and 'loud'respectively you can access these values through their keysmycat['size''fat'my cat has mycat['color'fur 'my cat has gray fur dictionaries can still use integer values as keysjust like lists use integers for indexesbut they do not have to st...
2,598
values for the keys allows you to organize your data in powerful ways say you wanted your program to store data about your friendsbirthdays you can use dictionary with the names as keys and the birthdays as values open new file editor window and enter the following code save it as birthdays py birthdays {'alice''apr ''...
2,599
while they're still not ordered and have no "firstkey-value pairdictionaries in python and later will remember the insertion order of their key-value pairs if you create sequence value from them for examplenotice the order of items in the lists made from the eggs and ham dictionaries matches the order in which they wer...