id
int64
0
25.6k
text
stringlengths
0
4.59k
7,400
join multiple sequences to one list of tuplesuseful when iterating on multiple sequences in parallel list zip abc )[' ' '' ' '' ' )list zip ([ abc xyz )[( ' ' '( ' ' '( ' ' )examplehow to create dictionary by two sequences dict zip (apple peach ( , ))apple ' peach ' member of the helmholtz association slide
7,401
what happensif for is applied on an objectfor in obj pass the __iter__ method for obj is calledreturn an iterator on each loop cycle the iterator __next__(method will be called the exception stopiteration is raised when there are no more elements advantagememory efficient (access timemember of the helmholtz association slide
7,402
class reverse def __init__ self data )self data data self index len data def __iter__ self )return self def __next__ self )if self index = self index len self data raise stopiteration self index self index return self data self index for char in reverse spam )print char end member of the helmholtz association slide
7,403
simple way to create iteratorsmethods uses the yield statement breaks at this pointreturns element and continues there on the next iterator __next__(call def reverse data )for element in data [:- ]yield element for char in reverse spam )print char end member of the helmholtz association slide
7,404
similar to the list comprehension an iterator can be created using generator expressiondata spam for in elem for elem in data [:- ])print ( end member of the helmholtz association slide
7,405
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,406
enhanced interactive python shell numbered input/output prompts object introspection system shell access member of the helmholtz association slide
7,407
tab-completion command history retrieval across session user-extensible 'magiccommands %timeit =time execution of python statement or expression using the timeit module %cd =change the current working directory %edit =bring up an editor and execute the resulting code %run =run the named file inside ipython as program =more 'magiccommands =ipython documentation member of the helmholtz association slide
7,408
command pip tool for installing python packages python and later (on the python series)and python and later include pip by default installing packages pip install somepackage pip install -user somepackage user install uninstall packages pip uninstall somepackage member of the helmholtz association slide
7,409
listing packages pip list docutils (jinja ( pygments (sphinx (pip list -outdated docutils current latest sphinx current latest searching for packages pip search query =pip documentation member of the helmholtz association slide
7,410
easily switch between multiple versions of python doesn' depend on python itself inserts directory of shims at the front of your path easy installationgit clone https :/github com yyuu pyenv git ~pyenv echo export pyenv_root home pyenv >~bashrc echo export path pyenv_root bin path >~bashrc echo eval pyenv init ->~bashrc =pyenv repository kind of infrastructure to redirect system/function calls metaphora shim is piece of wood or metal to make two things fit together member of the helmholtz association slide
7,411
install python versions into $pyenv_root/versions pyenv install -list pyenv install available python versions install python change the python version pyenv global pyenv local pyenv shell global python per project python shell specific python list all installed python versions (asterisk shows the activepyenv versions system set by pyenv_version environment variable member of the helmholtz association slide
7,412
allow python packages to be installed in an isolated location use cases two applications need different versions of library install an application and leave it be can' install packages into the global site-packages directory virtual environments have their own installation directories virtual environments don' share libraries with other virtual environments available implementationsvirtualenv (python and python venv (python and latermember of the helmholtz association slide
7,413
create virtual environment python - venv path to env activate source path to env bin activate deactivate deactivate =venv documentation member of the helmholtz association slide
7,414
pylint is the lint implementation for python code checks for errors in python code tries to enforce coding standard looks for bad code smells displays classified messages under various categories such as errors and warnings displays statistics about the number of warnings and errors found in different files member of the helmholtz association slide
7,415
the code is given an overall mark python - pylint example py global evaluation your code has been rated at previous run + =pylint documentation member of the helmholtz association slide
7,416
part of quality management point out the defects and errors that were made during the development phases it always ensures the users or customers satisfaction and reliability of the application the cost of fixing the bug is larger if testing is not done =testing saves time python testing tools pytest unittest member of the helmholtz association slide
7,417
easy to get started test_ prefixed test functions or methods are test items asserting with the assert statement pytest will run all files in the current directory and its subdirectories of the form test_py or *_test py usagepython - pytest python - pytest example py =pytest documentation member of the helmholtz association slide
7,418
example _test py def incr )return def test_incr ()assert incr ( = python - pytest - example _test py ___ __ __ __ test_incr ____ def test_incr ()assert incr ( = assert = where incr ( example _test py : assertionerror ============ failed in seconds ============member of the helmholtz association slide
7,419
import pytest def ()raise systemexit ( def test_error ()with pytest raises systemexit )passes (member of the helmholtz association slide
7,420
import pytest def ()raise systemexit ( def test_error ()with pytest raises systemexit )passes (pytest examplecomparing two data object def es t_ co rison ()list [ , , , list [ , , , assert list =list member of the helmholtz association fails slide
7,421
def incr )return @pytest mark parametrize test_input expected ( ( ( ]def test_incr test_input expected )assert incr test_input =expected member of the helmholtz association slide
7,422
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,423
regular expression (regexp)formal language for pattern matching in strings motivationanalyze various text fileslog files data files ( experimental datasystem configurationcommand output python moduleimport re re findall abc aac aa abb abc aac ' 'rememberrraw string (escape sequences are not interpretedmember of the helmholtz association slide
7,424
class/set of possible characters[!?,; -zat the beginning negates the class [^aeiouall characters besides the vocals character class in pattern tests for one character the represents any (onecharacter predefined character classesname whitespace word digit character \nr -za-z_ - [ - acr \ \ \ negated \ \ \ re findall 're findall [aeiou python kurs ' ' ' ' ' ' ' ' 'member of the helmholtz association slide
7,425
quantifier can be defined in ranges (minmax)\ { , matches sequences of - digits acronym{ { ,{ , { ,one- occurrence none occurrences none one- occurrence one- occurrence re findall ab ]{ , aa ab ba bb ' aa ab ba bb ' 're findall python kurs ' 'member of the helmholtz association slide default
7,426
anchors define special restrictions to the pattern matching\ \ word boundary between and \ negate of the end re findall ^ python course ' 'look-around anchors (context)lookahead ab (? ab matches ab abc matches ab by lookbehind (< ab ab member of the helmholtz association matches ab cab matches ab behind slide
7,427
pattern analysis will start at the beginning of the string if pattern matchesanalysis will continue as long as the pattern is still matching (greedypattern matching behavior can be changed to non-greedy by using the "?behind the quantifier the pattern analysis stops at the first (minimalmatching re findall py on python python python python 're findall py *on python python python python 'member of the helmholtz association slide
7,428
(brackets in pattern create group group name is numbered serially (starting with the first groups \ \ can be referenced in the same pattern patterns can be combined with logical or inside group re findall ( +\ py py abc test test py test 're findall ( za ]+| +,uid = zdv uid zdv 're findall (\*?\]hi ] sd 'hi 'member of the helmholtz association slide
7,429
some re methods return re matchobject contain captured groups re_groups py text adm : : st graf :home adm :bin bash grp re match ^( - ]+) :[ - ]+:[ - ]+:+)+text if grp )print found grp groups ()print user id grp group ( )print name grp group ( )python re_groups py found adm st graf 'user id adm name st graf member of the helmholtz association slide
7,430
special flags can change behavior of the pattern matching re case insensitive pattern matching re or will match at beginning/end of each line (not only at the beginning/end of stringre also matches newline \ re findall abc abc nabc [re findall abc abc nabc re abc 're findall abc abc nabc re re abc abc 're findall abc abc nabc [re findall abc abc nabc re abc 'member of the helmholtz association slide
7,431
findallsimple pattern matching list of strings (hitsre findall \*?\ bc hal def 'bc 'hal 'subquery replace new (replacedstring re sub \*?\ bc hal def ' def searchfind first match of the pattern returns re matchobject or none if re search \*?\ bc hal def )print pattern matched member of the helmholtz association slide
7,432
matchstarts pattern matching at beginning of the string returns re matchobject or none text adm : : st graf :home adm :bin bash grp re match ( - ]+) :[ - ]+:[ - ]+:+)+text compileregular expressions can be pre-compiled gain performance on reusing these regexp multiple times ( in loopspattern re compile \*?\pattern findall bc hal def 'bc 'hal 'member of the helmholtz association slide
7,433
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,434
we have learnedmultiple data types ( ,,high level"common statements declaration and usage of functions modules and packages errors and exceptionsexception handling object oriented programming some of the often used standard modules popular tools for python developers member of the helmholtz association slide
7,435
closuresdecorators (function wrappersmeta classes more standard modulesmailwwwxmlprofilingdebuggingunit-testing extending and embeddingpython / +third party-modulesgraphicweb programmingdata basesmember of the helmholtz association slide
7,436
cgi scriptsmodule cgi (standard libweb frameworksdjangoflaskpylonstemplate systemscheetahgenshijinjacontent management systems (cms)zopeploneskeletonzwikismoinmoinmember of the helmholtz association slide
7,437
alternative to matlabmatrix algebranumeric functionsplottingmember of the helmholtz association slide
7,438
jupyter notebook (interactive computational environmentpython ides pycharm eclipse (pydevpython and other languagesjythonpython code in java vm ctypesaccess -libraries in python (since in standard libswigaccess cand +-libraries in python pilpython imaging library for image manipulation sqlalchemyorm-framework abstractionobject oriented access to database member of the helmholtz association slide
7,439
table of contents installing python downloading and installing python starting idle how to use this book finding help online the interactive shell some simple math stuff evaluating expressions storing values in variables writing programs strings string concatenation writing programs in idle' file editor hello world saving your program opening the programs you've saved how the "hello worldprogram works variable names guess the number sample run of guess the number source code of guess the number import statements the random randint(function loops blocks the boolean data type post questions to
7,440
conditions the difference between and = looping with while statements converting values with the int()float()and str(functions if statements leaving loops early with the break statement flow control statements jokes making the most of print( sample run of jokes source code of jokes escape characters quotes and double quotes print()' end keyword argument dragon realm functions how to play dragon realm sample run of dragon realm source code of dragon realm def statements boolean operators return values global scope and local scope parameters designing the program using the debugger bugs the debugger
7,441
stepping find the bug break points example using break points flow charts how to play hangman sample run of hangman ascii art designing program with flowchart creating the flow chart hangman source code of hangman multi-line strings constant variables lists methods the lower(and upper(string methods the reverse(and append(list methods the split(list method the range(and list(functions for loops slicing elif ("else if"statements / extending hangman dictionaries the random choice(function multiple assignment tic tac toe sample run of tic tac toe post questions to
7,442
designing the program game ai references short-circuit evaluation the none value bagels sample run of bagels source code of bagels the random shuffle(function augmented assignment operators the sort(list method the join(string method string interpolation cartesian coordinates grids and cartesian coordinates negative numbers math tricks absolute values and the abs(function coordinate system of computer screen sonar treasure hunt sample run of sonar treasure hunt source code of sonar treasure hunt designing the program an algorithm for finding the closest treasure chest the remove(list method caesar cipher cryptography the caesar cipher
7,443
asciiand using numbers for letters the chr(and ord(functions sample run of caesar cipher source code of caesar cipher how the code works the isalpha(string method the isupper(and islower(string methods brute force reversi sample run of reversi source code of reversi how the code works the bool(function reversi ai simulation making the computer play against itself percentages the round(function sample run of aisim py comparing different ai algorithms graphics and animation installing pygame hello world in pygame source code of hello world running the hello world program tuples rgb colors fontsand the pygame font sysfont(function attributes constructor functions post questions to
7,444
events and the game loop animation source code of the animation program how the animation program works running the game loop collision detection and keyboard/mouse input source code of the collision detection program the collision detection algorithm don' add to or delete from list while iterating over it source code of the keyboard input program the colliderect(method sounds and images sound and image files sprites and sounds program source code of the sprites and sounds program the pygame transform scale(function dodger review of the basic pygame data types source code of dodger fullscreen mode the game loop event handling the move_ip(method the pygame mouse set_pos(function modifying the dodger game
7,445
installing python topics covered in this downloading and installing the python interpreter how to use this book the book' website at hellothis book teaches you how to program by making video games once you learn how the games in this book workyou'll be able to create your own games all you'll need is computersome software called the python interpreterand this book the python interpreter is free to download from the internet when was kida book like this one taught me how to write my first programs and games it was fun and easy now as an adulti still have fun programming and get paid for it but even if you don' become computer programmer when you grow upprogramming is useful and fun skill to have computers are incredible machinesand learning to program them isn' as hard as people think if you can read this bookyou can program computer computer program is bunch of instructions that the computer can understandjust like storybook is bunch of sentences understood by the reader since video games are nothing but computer programsthey are also made up of instructions to instruct computeryou write program in language the computer understands this book teaches programming language named python there are many different programming languages including basicjavajavascriptphpand +when was kidbasic was common first language to learn howevernew programming languages such as python have been invented since then python is even easier to learn than basicbut it' still serious programming language used by professional programmers many adults use python in their work and when programming for fun the games you'll create from this book seem simple compared to the games for xboxplaystationor nintendo these games don' have fancy graphics because they're meant to teach coding basics they're purposely simple so you can focus on learning to program games don' have to be complicated to be fun
7,446
downloading and installing python you'll need to install software called the python interpreter the interpreter program understands the instructions you'll write in the python language 'll just refer to "the python interpreter softwareas "pythonfrom now on important notebe sure to install python and not python the programs in this book use python and you'll get errors if you try to run them with python it is so important 've added cartoon penguin in figure - to tell you to install python so you do not miss this message figure - an incongruous penguin tells you to install python on windowsdownload the python installer (the filename will end with msiand double-click it follow the instructions the installer displays on the screen to install pythonas listed here select install for all users and then click next install to the :\python folder by clicking next click next to skip the customize python section on mac os xdownload the dmg file that' right for your version of os from the website and double-click it follow the instructions the installer displays on the screen to install pythonas listed here when the dmg package opens in new windowdouble-click the python mpkg file you may have to enter the administrator password click continue through the welcome section and click agree to accept the license post questions to
7,447
select hd macintosh (or whatever name your hard drive hasand click install if you're running ubuntuyou can install python from the ubuntu software center by following these steps open the ubuntu software center type python in the search box in the top-right corner of the window select idle (using python )or whatever is the latest version click install you may have to enter the administrator password to complete the installation starting idle idle stands for interactive development environment the development environment is like word processing software for writing python programs starting idle is different on each operating system on windowsclick the start button in the lower left cornertype "idleand select idle (python guion mac os xopen the finder window and click on applications then click python then click the idle icon on ubuntu or linuxopen terminal window and then type "idle you may also be able to click on applications at the top of the screen then click programming and idle the window that appears when you first run idle is the interactive shellas shown in figure you can enter python instructions into the interactive shell at the prompt and python will perform them after displaying instruction resultsa new prompt will wait for your next instruction figure - the idle program' interactive shell on windowsos xand ubuntu linux
7,448
how to use this book most in this book will begin with sample run of the featured program this sample run shows you what the program looks like when you run it the parts the user types in are shown as bold print type the code for the program into idle' file editor yourselfrather than download or copy/paste it you'll remember programming better if you take the time to type in the code line numbers and spaces when typing the source code from this bookdo not type the line numbers at the start of each line for exampleif you see this in the book number random randint( you do not need to type the " on the left sideor the one space immediately following it just type it like thisnumber random randint( those numbers are there only so that this book can refer to specific lines in the program they are not part of the actual program' source code aside from the line numbersenter the code exactly as it appears notice that some of the lines of code are indented by four or eight spaces each character in idle is the same widthso you can count the number of spaces by counting the number of characters on the line above or below for examplethe indented spaces here are marked with black square so you can see themwhile guesses ####if number = ########print('hello'text wrapping in this book some instructions are too long to fit on one line on the page and will wrap around to the next line when you type this codeenter it all on one line without pressing enter you can tell when new instruction starts by looking at the line numbers on the left the example below has only two instructions print('this is the first instructionxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx'post questions to
7,449
print('this is the second instructionnot the third instruction 'the first instruction wraps around and makes it look like three instructions in total that' only because this book' pages aren' wide enough to fit the first instruction on one line finding help online this book' website is at this book there several links in this book use the invpy com domain name for shortened urls the website at related to this book post general python questions to the learnprogramming and learnpython websites at respectively you can also email me your programming questions at al@inventwithpython com keep in mind there are smart ways to ask programming questions that help others help you be sure to read the frequently asked questions sections these websites have about the proper way to post questions when asking programming questionsdo the followingif you are typing out the programs in this book but getting an errorfirst check for typos with the online diff tool at tool to find any differences from the book' code in your program explain what you are trying to do when you explain the error this will let your helper know if you are on the wrong path entirely copy and paste the entire error message and your code search the web to see whether someone else has already asked (and answeredyour question explain what you've already tried to do to solve your problem this tells people you've already put in some work to try to figure things out on your own be polite don' demand help or pressure your helpers to respond quickly asking someone"why isn' my program working?doesn' tell them anything tell them what you are trying to dothe exact error you are gettingand your operating system and version
7,450
the interactive shell topics covered in this integers and floating point numbers expressions values operators evaluating expressions storing values in variables before you can make gamesyou need to learn few basic programming concepts you won' make games in this but learning these concepts is the first step to programming video games you'll start by learning how to use python' interactive shell some simple math stuff open idle using the steps in then get python to solve some simple math stuff the interactive shell can work just like calculator type into the interactive shell at the prompt and press the enter key on your keyboard (on some keyboardsthis is the return key figure - shows how the interactive shell responds with the number figure - enter + into the interactive shell this math problem is simple programming instruction the sign tells the computer to add the numbers and table - lists the other math symbols available in python the sign will subtract numbers the asterisk will multiply numbers the slash will divide numbers post questions to
7,451
table - the various math operators in python operator operation addition subtraction multiplication division when used in this way+-*and are called operators operators tell python what to do with the numbers surrounding them integers and floating point numbers integers (or ints for shortare whole numbers such as and floating point numbers (or floats for shortare fractions or numbers with decimal points like and in pythonthe number is an integerbut is float these numbers are called values expressions these math problems are examples of expressions computers can solve millions of these problems in seconds expressions are made up of values (the numbersconnected by operators (the math signstry entering some of these math problems into the interactive shellpressing the enter key after each one + + + + * - + after you type in the above instructionsthe interactive shell will look like figure - figure - what the idle window looks like after entering instructions
7,452
figure - an expression is made up of values and operators in the examplenotice that there can be any amount of spaces between the values and operators howeveralways start instructions at the beginning of the line when entering them into the interactive shell evaluating expressions when computer solves the expression and gets the value it has evaluated the expression evaluating an expression reduces the it to single valuejust like solving math problem reduces the problem to single numberthe answer the expressions and both evaluate to expressions can be of any sizebut they will always evaluate down to single value even single values are expressionsthe expression evaluates to the value for examplethe expression will evaluate down to the value through the following steps you don' see all of these steps in the interactive shell the interactive shell does them and just shows you the results post questions to
7,453
notice that the division operator evaluates to float valueas in evaluating to math operations with float values also evaluate to float valuesas in evaluating to syntax errors if you enter into the interactive shellyou'll get an error message syntaxerrorinvalid syntax this error happened because isn' an expression expressions have values connected by operators but the operator expects value after the sign an error message appears when this value is missing syntaxerror means python doesn' understand the instruction because you typed it incorrectly lot of computer programming isn' just telling the computer what to dobut also knowing how to tell it don' worry about making mistakes though errors don' damage your computer just retype the instruction correctly into the interactive shell at the next prompt storing values in variables you can save the value an expression evaluates to so you can use it later by storing them in variables think of variables like box that can hold value an assignment statement instruction will store value inside variable type the name for the variablefollowed by the sign (called the assignment operator)and then the value to store in the variable for exampleenter spam into the interactive shellspam the spam variable' box will have the value stored in itas shown in figure - the name "spamis the label on the box (so python can tell variables apartand the value is written on small note inside the box when you press enter you won' see anything in response in pythonthe instruction executed was successful if no error message appears the prompt will appear so you can type in the next instruction
7,454
figure - variables are like boxes that can hold values in them unlike expressionsstatements are instructions that do not evaluate to any value this is why there' no value displayed on the next line in the interactive shell after spam if you are confused about which instructions are expressions and which are statementsremember that expressions evaluate to single value any other kind of instruction is statement variables store valuesnot expressions for exampleconsider the expression in the statements spam and spam they both evaluate to the end result is the sameboth assignment statements store the value in the variable spam the first time variable is used in an assignment statementpython will create that variable to check what value is in variabletype the variable name into the interactive shellspam spam the expression spam evaluates to the value inside the spam variable you can use variables in expressions try entering the following in the interactive shellspam spam you've set the value of the variable spam to so writing spam is like writing the expression here are the steps of spam being evaluatedspam post questions to
7,455
you cannot use variable before an assignment statement creates it python will give you nameerror because no such variable by that name exists yet mistyping the variable name also causes this errorspam spma traceback (most recent call last)file ""line in spma nameerrorname 'spmais not defined the error appeared because there' spam variable but no variable named spma you can change the value stored in variable by entering another assignment statement for exampletry entering the following into the interactive shellspam spam spam spam when you first enter spam the expression evaluates to because you stored inside spam howeverwhen you enter spam the value is replacedor overwrittenwith the value now when you enter spam the expression evaluates to because the value of spam is now overwriting is shown in figure - figure - the value in spam being overwritten by the value you can even use the value in the spam variable to assign new value to spam
7,456
spam spam spam the assignment statement spam spam is like saying"the new value of the spam variable will be the current value of spam plus five keep increasing the value in spam by several times by entering the following into the interactive shellspam spam spam spam spam spam spam spam using more than one variable create as many variables as you need in your programs for examplelet' assign different values to two variables named eggs and baconlike sobacon eggs now the bacon variable has inside itand eggs has inside it each variable is its own box with its own valuelike in figure - figure - the "baconand "eggsvariables have values stored in them try entering spam bacon eggs into the interactive shellthen check the new value of spambacon eggs spam bacon eggs spam post questions to
7,457
the value in spam is now when you added bacon and eggs you are adding their valueswhich are and respectively variables contain valuesnot expressions the spam variable was assigned value and not the expression bacon eggs after the spam bacon eggs assignment statementchanging bacon or eggs does not affect spam summary in this you learned the basics about writing python instructions python needs you to tell it exactly what to do in strict way computers don' have common sense and only understand specific instructions expressions are values (such as or combined with operators (such as or -python can evaluate expressionsthat isreduce the expression to single value you can store values inside of variables so that your program can remember them and use them later there are many other types of operators and values in python in the next you'll go over some more basic concepts and write your first program you'll learn about working with text in expressions python isn' limited to just numbersit' more than calculator
7,458
writing programs topics covered in this flow of execution strings string concatenation data types (such as strings or integersusing the file editor to write progams saving and running programs in idle the print(function the input(function comments case-sensitivity that' enough math for now now let' see what python can do with text in this you'll learn how to store text in variablescombine textand display text on the screen almost all programs display text to the userand the user enters text into your programs through the keyboard you'll also make your first program in this this program displays the greeting"hello world!and asks for the user' name strings in pythontext values are called strings string values can be used just like integer or float values you can store strings in variables in codestring values start and end with single quote ('try entering this code into the interactive shellspam 'hellothe single quotes tell python where the string begins and ends they are not part of the string value' text now if you type spam into the interactive shellyou will see the contents of the spam variable rememberpython evaluates variables to the value stored inside the variable in this casethis is the string 'hello'spam 'hellospam 'hellopost questions to
7,459
strings can have any keyboard character in them and can be as long as you want these are all examples of strings'hello'hi there!'kittens' apples oranges lemons'anything not pertaining to elephants is irrelephant ' long time agoin galaxy farfar away ' *&#wy%*&ocfsdyo*&gfc%yo*&% yc string concatenation string values can combine with operators to make expressionsjust like integer and float values do you can combine two strings with the operator this is string concatenation try entering 'hello'world!into the interactive shell'hello'world!'helloworld!the expression evaluates to single string value'helloworld!there is no space between the words because there was no space in either of the two concatenated stringsunlike this example'hello 'world!'hello world!the operator works differently on string and integer values because they are different data types all values have data type the data type of the value 'hellois string the data type of the value is an integer the data type tells python what operators should do when evaluating expressions the operator will concatenate string values but add integer and float values writing programs in idle' file editor until nowyou've been typing instructions into idle' interactive shell one at time when you write programs thoughyou type in several instructions and have them run all at once let' write your first programidle has another part called the file editor click on the file menu at the top of the interactive shell window then select new window blank window will appear for you to type your program' code intolike in figure -
7,460
figure - the file editor window (leftand the interactive shell window (rightthe two windows look similarbut just remember thisthe interactive shell window will have the prompt the file editor window will not hello worldit' traditional for programmers to make their first program display "hello world!on the screen you'll create your own hello world program now when you enter your programdon' enter the numbers at the left side of the code they're there so this book can refer to code by line number the bottom-right corner of the file editor window will tell you where the blinking cursor is figure - shows that the cursor is on line and column figure - the bottom right of the file editor window tells you what line the cursor is on hello py enter the following text into the new file editor window this is the program' source code it contains the instructions python will follow when the program is run post questions to
7,461
important notethe programs in this book will only run on python not python when the idle window startsit will say something like "python at the top if you have python installedyou can have python installed at the same time to download python go to hello py this program says hello and asks for my name print('hello world!' print('what is your name?' myname input( print('it is good to meet youmynamethe idle program will write different types of instructions with different colors after you're done typing the codethe window should look like thisfigure - the file editor window will look like this after you type in the code saving your program once you've entered your source codesave it by clicking on file save as or press ctrl- to save with keyboard shortcut figure - shows the save as window that will open enter hello py in the file name text field then click save
7,462
figure - saving the program you should save your programs often while you type them that wayif the computer crashes or you accidentally exit from idle you won' lose much work opening the programs you've saved to load your previously saved programclick file open choose the file in the window that appears and click the open button your saved hello py program will open in the file editor window now it' time to run the program click file run run module or just press from the file editor window your program will run in the interactive shell window enter your name when the program asks for it this will look like figure - figure - the interactive shell after running hello py post questions to
7,463
when you type your name and push enterthe program will greet you by name congratulationsyou've written your first program and are now computer programmer press again to run the program second time and enter another name if you got an errorcompare your code to this book' code with the online diff tool at the compare button this tool will highlight any differences between your code and the code in this booklike in figure - figure - the diff tool at while codingif you get nameerror that looks like thishello worldwhat is your namealbert traceback (most recent call last)file " :/python /test py"line in myname input(file ""line in nameerrorname 'albertis not defined that means you are using python instead of python install version of python from
7,464
how the "hello worldprogram works each line of code is an instruction interpreted by python these instructions make up the program computer program' instructions are like the steps in cookbook recipe each instruction executes in orderbeginning from the top of the program and going down the list of instructions the step python is at in the program is called the execution when the program startsthe execution is at the first instruction after executing the instructionthe execution moves down to the next instruction let' look at each line of code to see what it' doing we'll begin with line number comments this program says hello and asks for my name this instruction is comment any text following sign (called the pound signis comment comments are not for pythonbut for youthe programmer python ignores comments comments are the programmer' notes about what the code does you can write anything in comment to make it easier to read the source codethis book prints comments in light graycolored text programmers usually put comment at the top of their code to give their program title functions function is kind of like mini-program inside your program functions contain several instructions to execute when the function is called python provides some built-in functions already two functionsprint(and input()are described next the great thing about functions is that you only need to know what the function doesbut not how it does it function call is an instruction that tells python to run the code inside function for exampleyour program calls the print(function to display string on the screen the print(function takes the string you type between the parentheses as input and displays the text on the screen to display hello worldon the screentype the print function namefollowed by an opening parenthesisfollowed by the 'hello world!string and closing parenthesis the print(function print('hello world!'post questions to
7,465
print('what is your name?'lines and are calls to the print(function value between the parentheses in function call is an argument the argument on line ' print(function call is 'hello world!the argument on line ' print(function call is 'what is your name?this is called passing the argument to the print(function in this bookfunction names have parentheses at the end this makes it clear that print(means this book is talking about function named print()and not variable named print this is like the quotes around the number ' telling python that you are talking about string ' and not an integer the input(function myname input(line is an assignment statement with variable (mynameand function call (input()when input(is calledthe program waits for the user to enter text the text string that the user enters becomes the value that the function call evaluates to function calls can be used in expressions anywhere value can be used the value that the function call evaluates to is called the return value (in fact"the value function call returnsmeans the same thing as "the value function call evaluates toin this casethe return value of the input(function is the string that the user typed in-their name if the user typed in "albert"the input(function call evaluates to the string 'albertthe evaluation looks like thismyname input( myname 'albertthis is how the string value 'albertgets stored in the myname variable using expressions in function calls print('it is good to meet youmynamethe last line is another print(function call the expression 'it is good to meet youmyname in between the parentheses of print(howeverarguments are always single values python will first evaluate this expression and then pass that value as the argument if 'albertis stored in mynamethe evaluation looks like this
7,466
print('it is good to meet youmynamev print('it is good to meet you'albert' print('it is good to meet youalbert'this is how the program greets the user by name ending the program once the program executes the last lineit terminates or exits this means the program stops running python forgets all of the values stored in variablesincluding the string stored in myname if you run the program again and enter different namethe program will think that is your name hello worldwhat is your namecarolyn it is good to meet youcarolyn rememberthe computer does exactly what you program it to do computers are dumb and just follow the instructions you give it exactly the computer doesn' care if you type in your namesomeone else' nameor just something silly type in anything you want the computer will treat it the same wayhello worldwhat is your namepoop it is good to meet youpoop variable names giving variables descriptive names makes it easier to understand what program does imagine if you were moving to new house and you labeled every moving box "stuffthat wouldn' be helpful at allinstead of mynameyou could have called this variable abrahamlincoln or name python doesn' care it will run the program just the same variable names are case-sensitive case-sensitive means the same variable name in different case is considered different variable so spamspamspamand spam are four different variables in python they each contain their own separate values it' bad idea to have differently cased variables in your program use descriptive names for your variables instead post questions to
7,467
variable names are usually lowercase if there' more than one word in the variable namecapitalize each word after the first this makes your code more readable for examplethe variable name whatihadforbreakfastthismorning is much easier to read than whatihadforbreakfastthismorning this is conventionan optional but standard way of doing things in python programming short variable names are better than long namesbreakfast or foodthismorning is more readable than whatihadforbreakfastthismorning this book' interactive shell examples use variable names like spameggshamand bacon this is because the variable names in these examples don' matter howeverthis book' programs all use descriptive names your programs should use descriptive variable names too summary once you learn about strings and functionsyou can start making programs that interact with users this is important because text is the main way the user and the computer will communicate with each other the user enters text through the keyboard with the input(function the computer will display text on the screen with the print(function strings are just values of new data type all values have data typeand there are many data types in python the operator can concatenate strings functions are used to carry out some complicated instruction as part of your program python has many built-in functions that you'll learn about in this book function calls can be used in expressions anywhere value is used the instruction in your program that python is currently at is called the execution in the next you'll learn more about making the execution move in ways other than just straight down the program once you learn thisyou'll be ready to create games
7,468
guess the number topics covered in this import statements modules while statements conditions blocks booleans comparison operators the difference between and =if statements the break keyword the str()and int()and float(functions the random randint(function in this you're going to make "guess the numbergame the computer will think of random number from to and ask you to guess it the computer will tell you if each guess is too high or too low you win if you can guess the number within six tries this is good game to code because it uses random numbersloopsand input from the user in short program you'll learn how to convert values to different data typesand why you would need to do this since this program is gamewe'll call the user the player but "userwould be correct too sample run of guess the number here' what the program looks like to the player when run the text that the player types in is in bold hellowhat is your namealbert wellalberti am thinking of number between and take guess your guess is too high take guess post questions to
7,469
your guess is too low take guess good jobalbertyou guessed my number in guessessource code of guess the number open new file editor window by clicking on the file new window in the blank window that appearstype in the source code and save it as guess py then run the program by pressing when you enter this code into the file editorbe sure to pay attention to the spacing at the front of some of the lines some lines have four or eight spaces of indentation important notethe programs in this book will only run on python not python when the idle window startsit will say something like "python at the top if you have python installedyou can have python installed at the same time to download python go to if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at guess py this is guess the number game import random guessestaken print('hellowhat is your name?' myname input( number random randint( print('wellmyname ' am thinking of number between and ' while guessestaken print('take guess 'there are four spaces in front of print guess input( guess int(guess guessestaken guessestaken if guess number print('your guess is too low 'there are eight spaces in front of print if guess number
7,470
print('your guess is too high ' if guess =number break if guess =number guessestaken str(guessestaken print('good jobmyname 'you guessed my number in guessestaken guesses!' if guess !number number str(number print('nope the number was thinking of was numberimport statements this is guess the number game import random the first line is comment remember that python will ignore everything after the sign this just reminds us what this program does the second line is an import statement rememberstatements are instructions that perform some action but don' evaluate to value like expressions do you've already seen statementsassignment statements store value in variable while python includes many built-in functionssome functions exist in separate programs called modules you can use these functions by importing their modules into your program with an import statement line imports the module named random so that the program can call random randint(this function will come up with random number for the user to guess guessestaken line creates new variable named guessestaken you'll store the number of guesses the player has made in this variable since the player hasn' made any guesses at this point in the programstore the integer here print('hellowhat is your name?' myname input(post questions to
7,471
lines and are the same as the lines in the hello world program that you saw in programmers often reuse code from their other programs to save themselves work line is function call to the print(function remember that function is like miniprogram inside your program when your program calls functionit runs this mini-program the code inside the print(function displays the string argument you passed it on the screen line lets the user type in their name and stores it in the myname variable (rememberthe string might not really be the player' name it' just whatever string the player typed computers are dumb and just follow their instructions no matter what the random randint(function number random randint( line calls new function named randint(and stores the return value in number rememberfunction calls can be part of expressions because they evaluate to value the randint(function is provided by the random moduleso you must precede it with random (don' forget the period!to tell python that the function randint(is in the random module the randint(function will return random integer between (and includingthe two integer arguments you pass to it line passes and between the parentheses separated by commas that follow the function name the random integer that randint(returns is stored in variable named numberthis is the secret number the player is trying to guess just for momentgo back to the interactive shell and enter import random to import the random module then enter random randint( to see what the function call evaluates to it will return an integer between and repeat the code again and the function call will return different integer the randint(function returns random integer each timejust as rolling dice you'll get random number each timeimport random random randint( random randint( random randint( random randint( random randint(
7,472
use the randint(function when you want to add randomness to your games you'll use randomness in many games (think of how many board games use dice you can also try different ranges of numbers by changing the arguments for exampleenter random randint( to only get integers between and (including both and or try random randint( to get integers between and for exampleenter the following into the interactive shell the results you get when you call the random randint(function will probably be different (it is randomafter allrandom randint( random randint( you can change the game' code slightly to make the game behave differently try changing line and from this number random randint( print('wellname ' am thinking of number between and 'into these lines number random randint( print('wellname ' am thinking of number between and 'and now the computer will think of an integer between and instead of and changing line will change the range of the random numberbut remember to change line so that the game also tells the player the new range instead of the old one welcoming the player print('wellmyname ' am thinking of number between and 'on line the print(function welcomes the player by nameand tells them that the computer is thinking of random number it may look like there' more than one string argument in line but look at the line carefully the plus signs concatenate the three strings to evaluate down to one string and that one string is the argument passed to the print(function if you look closelyyou'll see that the commas are inside the quotes and part of the strings themselves post questions to
7,473
loops while guessestaken line is while statementwhich indicates the beginning of while loop loops let you execute code over and over again howeveryou need to learn few other concepts first before learning about loops those concepts are blocksbooleanscomparison operatorsconditionsand the while statement blocks several lines of code can be grouped together in block every line in block of code has the same minimum amount of indentation you can tell where block begins and ends by looking at the number of spaces at the front of the lines this is the line' indentation block begins when line' indentation increases (usually by four spacesany following line also indented by four spaces is part of the block the block ends when there' line of code with the same indentation before the block started this means blocks can exist within other blocks figure - is diagram of code with the blocks outlined and numbered in figure - line has no indentation and isn' inside any block line has an indentation of four spaces since this indentation is larger than the previous line' indentationa new block has started this block is labeled ( in figure - this block will continue until line with zero spaces (the original indentation before the block beganblank lines are ignored line has an indentation of eight spaces eight spaces is more than four spaceswhich starts new block this block is labeled ( in figure - this block is inside of another block figure - blocks and their indentation the black dots represent spaces
7,474
line has only four spaces because the indentation has decreasedyou know that block has ended line is the only line in that block line is in the same block as the other lines with four spaces line increases the indentation to eight spacesso again new block has started it is labeled ( in figure - to recapline isn' in any block lines to all in one block marked ( line is in block in block marked as ( line is the only line in another block in block marked as ( the boolean data type the boolean data type has only two valuestrue or false these values must be typed with capital "tand "fthe rest of the value' name must be in lowercase you will use boolean values (called bools for shortwith comparison operators to form conditions (conditions are explained later for exampletry storing the boolean values in variablesspam true eggs false the data types that have been introduced so far are integersfloatsstringsand now bools every value in python belongs to one data type comparison operators line has while statement while guessestaken the expression that follows the while keyword (the guessestaken partcontains two values (the value in the variable guessestakenand the integer value connected by an operator (the "less thansignthe sign is comparison operator comparison operators compare two values and evaluate to true or false boolean value list of all the comparison operators is in table - post questions to
7,475
table - comparison operators operator sign operator name less than greater than <less than or equal to >greater than or equal to =equal to !not equal to you've already read about the +-*and math operators like any operatorthe comparison operators combine with values to form expressions such as guessestaken conditions condition is an expression that combines two values with comparison operator (such as or >and evaluates to boolean value condition is just another name for an expression that evaluates to true or false conditions are used in while statements (and few other instructionsexplained later for examplethe condition guessestaken asks"is the value stored in guessestaken less than the number ?if sothen the condition evaluates to true if notthe condition evaluates to false in the case of the "guess the numberprogramon line you stored the value in guessestaken because is less than this condition evaluates to the boolean value of true the evaluation would look like thisguessestaken true experiment with booleanscomparison operatorsand conditions enter the following expressions in the interactive shell to see their boolean results true false
7,476
false true false the condition returns the boolean value true because the number is less than the number but because isn' less than the condition evaluates to false isn' less than so is false is less than so is true notice that evaluates to false because the number isn' smaller than the number they are the same size if alice were the same height as bobyou wouldn' say that alice is taller than bob or that alice is shorter than bob both of those statements would be false now try entering these expressions into the interactive shell = true = false = false ! false ! true 'hello='hellotrue 'hello='goodbyefalse 'hello='hellofalse 'goodbye!'hellotrue the difference between and =try not to confuse the assignment operator (=and the "equal tocomparison operator (==the equal sign (=is used in assignment statements to store value to variablewhile the equalequal sign (==is used in expressions to see whether two values are equal it' easy to accidentally use one when you meant to use the other just remember that the "equal tocomparison operator (==has two characters in itjust as the "not equal tocomparison operator (!=has two characters in it post questions to
7,477
string and integer values will never be equal to each other for exampletry entering the following into the interactive shell ='hellofalse !' true looping with while statements the while statement marks the beginning of loop loops can execute the same code repeatedly when the execution reaches while statementit evaluates the condition next to the while keyword if the condition evaluates to truethe execution moves inside the following blockcalled the while-block (in the programthe while-block begins on line if the condition evaluates to falsethe execution moves all the way past the while-block in guess the numberthe first line after the while-block is line while statement always has colon after the condition statements that end with colon expect new block on the next line while guessestaken figure - the while loop' condition figure - shows how the execution flows depending on the condition if the condition evaluates to true (which it does the first timebecause the value of guessestaken is )execution will
7,478
enter the while-block at line and keep going down once the program reaches the end of the while-blockinstead of going down to the next linethe execution loops back up to the while statement' line (line and re-evaluates the condition as beforeif the condition is true the execution enters the while-block again each time the execution goes through the loop is called an iteration this is how the loop works as long as the condition is truethe program keeps executing the code inside the while-block repeatedly until the first time the condition is false think of the while statement as saying"while this condition is truekeep executing the code in the following blockthe player guesses print('take guess 'there are four spaces in front of print guess input(lines to ask the player to guess what the secret number is and lets them enter their guess that number is stored in variable named guess converting values with the int()float()str()and bool(functions guess int(guessline calls new function named int(the int(function takes one argument and returns an integer value form of that argument try entering the following into the interactive shellint(' ' int(' ' the int(' 'call will return the integer value howevereven though you can pass string to the int(functionyou cannot pass just any string passing 'forty-twoto int(will result in an error the string you pass to int(must be made up of numbersint('forty-two'traceback (most recent call last)file ""line in int('forty-two'valueerrorinvalid literal for int(with base 'forty-twopost questions to
7,479
the int(' 'line shows an expression that uses the return value of int(as part of an expression it evaluates to the integer value int(' ' rememberthe input(function always returns string of text the player typed if the player types the input(function will return the string value ' 'not the integer value python cannot use the comparison operators to compare string and an integer value ' traceback (most recent call last)file ""line in ' typeerrorunorderable typesint(str( guess input(guess int(guesson line the guess variable originally held the string value of what the player typed line overwrites the string value in guess with the integer value returned by int(this lets the code later in the program compare if guess is greater thanless thanor equal to the secret number in the number variable one last thingcalling int(guessdoesn' change the value in the guess variable the code int(guessis an expression that evaluates to the integer value form of the string stored in the guess variable what changes guess is the assignment statementguess int(guessthe float()str()and bool(functions will similarly return floatstringand boolean versions of the arguments passed to them try entering the following into the interactive shellfloat(' ' float( str( ' str( ' str(false'falsebool(''
7,480
false bool('any nonempty string'true using the int()float()str()and bool(functionsyou can take value of one data type and return it as value of different data type incrementing variables guessestaken guessestaken once the player has taken guessthe number of guesses should be increased by one on the first iteration of the loopguessestaken has the value of python will take this value and add to it evaluates to which is stored as the new value of guessestaken think of line as meaning"the guessestaken variable should be one more than what it already isadding one to variable' integer or float value is called incrementing the variable subtracting one from variable' integer or float value is called decrementing the variable if statements if guess number print('your guess is too low 'there are eight spaces in front of print line is an if statement the execution will run the code in the following block if the if statement' condition evaluates to true if the condition is falsethen the code in the if-block is skipped using if statementsyou can make the program only run certain code when you want it to line checks if the player' guess is less than the computer' secret number if sothen the execution moves inside the if-block on line and prints message telling the player this the if statement works almost the same as while statementtoo but unlike the while-blockthe execution doesn' jump back to the if statement at the end of the if-block it just continues down to the next line in other wordsif statements don' loop see figure - for comparison of the two statements post questions to
7,481
figure - if and while statements if guess numberprint('your guess is too high 'line checks if the player' guess is greater than the secret number if this condition is truethen the print(function call tells the player that their guess is too high leaving loops early with the break statement if guess =numberbreak the if statement on line checks if the guess is equal to the secret number if it isthe program runs the break statement on line break statement tells the execution to jump immediately out of the while-block to the first line after the end of the while-block the break statement doesn' bother rechecking the while loop' condition the break statement is only found inside loopssuch as in while-block if the player' guess isn' equal to the secret numberthe execution reaches the bottom of the while-block this means the execution will loop back to the top and recheck the condition on line (guessestaken remember after the guessestaken guessestaken instruction executedthe new value of guessestaken is because is truethe execution enters the loop again if the player keeps guessing too low or too highthe value of guessestaken will change to then then then then when guessestaken has the number stored in itthe while
7,482
statement' condition (guessestaken is falsesince isn' less than because the while statement' condition is falsethe execution moves to the first line after the while-blockline check if the player won if guess =numberline has no indentationwhich means the while-block has ended and this is the first line after the while-block the execution left the while-block either because the while statement' condition was false (when the player runs out of guessesor the break statement on line was executed (when the player guesses the number correctlyline checks to see if the player guessed correctly if sothe execution enters the if-block at line guessestaken str(guessestaken print('good jobmyname 'you guessed my number in guessestaken guesses!'lines and only execute if the condition in the if statement on line was true (that isif the player correctly guessed the computer' numberline calls the str(functionwhich returns the string form of guessestaken line concatenates strings to tell the player they have won and how many guesses it took them only string values can concatenate to other strings this is why line had to change guessestaken to the string form otherwisetrying to concatenate string to an integer would cause python to display an error check if the player lost if guess !numberline uses the "not equal tocomparison operator !to check if player' last guess is not equal to the secret number if this condition evaluates to truethe execution moves into the if-block on line lines and are inside the if-blockand only execute if the condition on line was true number str(numberprint('nope the number was thinking of was numberpost questions to
7,483
in this blockthe program tells the player what the secret number they failed to guess correctly was this requires concatenating stringsbut number stores an integer value line will overwrite number with string form so that it can be concatenated to the 'nope the number was thinking of was string on line at this pointthe execution has reached the end of the codeand the program terminates congratulationsyou've just programmed your first real gameyou can change the game' difficulty by changing the number of guesses the player gets to give the player only four guesseschange the code on line while guessestaken into this line while guessestaken code later in the while-block increases the guessestaken variable by on each iteration by setting the condition to guessestaken you ensure that the code inside the loop only runs four times instead of six this makes the game much more difficult to make the game easierset the condition to guessestaken or guessestaken this will cause the loop to run few more times and accept more guesses from the player flow control statements in previous the program execution started at the top instruction in program and went straight downexecuting each instruction in order but with the whileifelseand break statementsyou can cause the execution to loop and skip instructions based on conditions the name for these kinds of statements is flow control statementsince they change the "flowof the program execution as it moves around your program summary if someone asked you"what exactly is programming anyway?what could you say to themprogramming is just the action of writing code for programsthat iscreating programs that can be executed by computer "but what exactly is program?when you see someone using computer program (for exampleplaying your "guess the numbergame)all you see is some text appearing on the screen the program decides what exact text to show on the screen (the program' output)based
7,484
on its instructions and on the text that the player typed on the keyboard (the program' inputa program is just collection of instructions that act on the user' input "what kind of instructions?there are only few different kinds of instructionsreally expressions are values connected by operators expressions are all evaluated down to single valueas evaluates to or 'hello'worldevaluates to 'hello worldwhen expressions are next to the if and while keywordsyou can also call them conditions assignment statements store values in variables so you can remember the values later in the program the ifwhileand break statements are flow control statements that can cause the execution to skip instructionsloop over instructionsor break out of loops function calls also change the flow of execution by jumping to the instructions inside of function the print(and input(functions these functions display text on the screen and get text from the keyboard this is called / (pronounced like the letters"eye-oh")because it deals with the input and output of the program and that' itjust those four things of coursethere are many details about those four types of instructions in this book you'll learn about new data types and operatorsnew flow control statementsand many other functions that come with python there are also different types of / such as input from the mouse or outputting sound and graphics instead of just text for the person using your programsthey only care about that last typei/ the user types on the keyboard and then sees things on the screen or hears things from the speakers but for the computer to figure out what sights to show and what sounds to playit needs programand programs are just bunch of instructions that youthe programmerhave written post questions to
7,485
jokes topics covered in this escape characters using single quotes and double quotes for strings using print()' end keyword argument to skip newlines making the most of print(most of the games in this book will have simple text for input and output the input is typed by the user on the keyboard the output is the text displayed on the screen in pythonthe print(function displays textual output on the screen but there' more to learn about how strings and print(work in python this program tells few different jokes to the userand demonstrates advanced string and print(code sample run of jokes what do you get when you cross snowman with vampirefrostbitewhat do dentists call an astronaut' cavitya black holeknock knock who' thereinterrupting cow interrupting cow wh-moosource code of jokes open new file editor window by clicking on the file new window in the blank window that appears type in the source code and save it as jokes py then run the program by pressing important notethe programs in this book will only run on python not python when the idle window startsit will say something like "python at the top if you have python installedyou can have python installed at the same time to download python go to
7,486
if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at jokes py print('what do you get when you cross snowman with vampire?' input( print('frostbite!' print( print('what do dentists call astronaut\' cavity?' input( print(' black hole!' print( print('knock knock ' input( print("who' there?" input( print('interrupting cow ' input( print('interrupting cow wh'end='' print('-moo!'how the code works print('what do you get when you cross snowman with vampire?' input( print('frostbite!' print(lines to have three print(function calls you don' want the player to immediately read the joke' punch lineso there' call to the input(function after the first print(the player can read the jokepress enterand then read the punch line the user can still type in string and hit enterbut this returned string isn' being stored in any variable the program will just forget about it and move to the next line of code the last print(function call has no string argument this tells the program to just print blank line blank lines are useful to keep the text from being bunched up escape characters print('what do dentists call astronaut\' cavity?' input( print(' black hole!'post questions to
7,487
print(on line there' backslash right before the single quote\note that is backslashand is forward slash this backslash tells you that the letter right after it is an escape character an escape character lets you print characters that are hard to enter into the source code on line the escape character is the single quote the single quote escape character is there because otherwise python would think the quote meant the end of the string but this quote needs to be part of the string the escaped single quote tells python that the single quote is literally part of the string rather than marking the end of the string value some other escape characters what if you really want to display backslashthis instruction would not workprint('they flew away in green\teal helicopter 'they flew away in green eal helicopter this is because the "tin "tealwas seen as an escape character since it came after backslash the escape character simulates pushing the tab key on your keyboard insteadtry this lineprint('they flew away in green\\teal helicopter 'they flew away in green\teal helicopter table - is list of escape characters in python table - escape characters escape character \\\\ \ what is actually printed backslash (\single quote ('double quote ("newline tab quotes and double quotes strings don' always have to be between single quotes in python you can also put them between double quotes these two lines print the same thingprint('hello world'hello world
7,488
print("hello world"hello world but you cannot mix quotes this line will give you an error if you try to use themprint('hello world"syntaxerroreol while scanning single-quoted string like to use single quotes so don' have to hold down the shift key to type them it' easier to typeand python doesn' care either way just like you need the escape character \to have single quote in string surrounded by single quotesyou need the escape character \to have double quote in string surrounded by double quotes for examplelook at these two linesprint(' asked to borrow abe\' car for week he said"sure "' asked to borrow abe' car for week he said"sure print("she said\" can' believe you let them borrow your car \""she said" can' believe you let them borrow your car in the single quote strings you don' need to escape double quotesand in the double quote strings you don' need to escape single quotes"astronaut'sthe python interpreter is smart enough to know that if string starts with one type of quotethe other type of quote doesn' mean the string is ending print(' end keyword argument print('knock knock ' input( print("who' there?" input( print('interrupting cow ' input( print('interrupting cow wh'end='' print('-moo!'did you notice the second parameter on line ' print()normallyprint(adds newline character to the end of the string it prints this is why blank print(function will just print newline but the print(function can optionally have second parameter (which has the name end post questions to
7,489
the blank string passed is called keyword argument the end parameter has specific nameand to pass keyword argument to this specific parameter you must type endbefore it by passing blank string for endthe print(function won' add newline at the end of the stringbut instead add blank string this is why '-moo!appears next to the previous lineinstead of on its own new line there was no newline after the 'interrupting cow whstring was printed summary this explores the different ways you can use the print(function escape characters are used for characters that are difficult or impossible to type into the code with the keyboard escape characters are typed into strings beginning with backslash followed by single letter for the escape character for example\ would be newline to include backslash in stringyou would use the escape character \the print(function automatically appends newline character to the end of the string passed it to be displayed on the screen most of the timethis is helpful shortcut but sometimes you don' want newline character at the end to change thisyou can pass the end keyword argument with blank string for exampleto print "spamto the screen without newline characteryou would call print('spam'end=''python provides many flexible ways to display text on the screen
7,490
dragon realm topics covered in this the time sleep(function creating your own functions with the def keyword the return keyword the andorand not boolean operators truth tables global and local variable scope parameters and arguments flow charts functions you've already used few functionsprint()input()random randint()str()and int(you've called these functions to execute the code inside them in this you'll write your own functions for your programs to call function is like mini-program inside program functions let you run the same code multiple times without duplicating the source code several times insteadyou can put that code inside function and call the function several times this has the added benefit that if the function' code has mistakeyou only have one place in the program to change it the game you will create in this is called "dragon realmthe player decides between two caves which hold either treasure or certain doom how to play dragon realm in this gamethe player is in land full of dragons the dragons all live in caves with their large piles of collected treasure some dragons are friendly and share their treasure with you other dragons are hungry and eat anyone who enters their cave the player is in front of two cavesone with friendly dragon and the other with hungry dragon the player must choose between the two open new file editor window by clicking on the file new window in the blank window that appears type in the source code and save it as dragon py then run the program by pressing post questions to
7,491
sample run of dragon realm you are in land full of dragons in front of youyou see two caves in one cavethe dragon is friendly and will share his treasure with you the other dragon is greedy and hungryand will eat you on sight which cave will you go into( or you approach the cave it is dark and spooky large dragon jumps out in front of youhe opens his jaws and gobbles you down in one bitedo you want to play again(yes or nono source code of dragon realm important notethe programs in this book will only run on python not python when the idle window startsit will say something like "python at the top if you have python installedyou can have python installed at the same time to download python go to if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at dragon py import random import time def displayintro() print('you are in land full of dragons in front of you,' print('you see two caves in one cavethe dragon is friendly' print('and will share his treasure with you the other dragon' print('is greedy and hungryand will eat you on sight ' print( def choosecave() cave ' while cave !' and cave !' ' print('which cave will you go into( or )' cave input( return cave
7,492
def checkcave(chosencave) print('you approach the cave ' time sleep( print('it is dark and spooky ' time sleep( print(' large dragon jumps out in front of youhe opens his jaws and ' print( time sleep( friendlycave random randint( if chosencave =str(friendlycave) print('gives you his treasure!' else print('gobbles you down in one bite!' playagain 'yes while playagain ='yesor playagain =' ' displayintro( cavenumber choosecave( checkcave(cavenumber print('do you want to play again(yes or no)' playagain input(how the code works let' look at the source code in more detail import random import time this program imports two modules the random module will provide the random randint(function like it did in the "guess the numbergame you will also want time-related functions that the time module includesso line imports the time module def statements def displayintro() print('you are in land full of dragons in front of you,'post questions to
7,493
print('you see two caves in one cavethe dragon is friendly'print('and will share his treasure with you the other dragon'print('is greedy and hungryand will eat you on sight 'print(line is def statement the def statement defines new function that you can call later in the program when you define this functionyou specify the instructions in its def-block when you call this functionthe code inside the def-block executes figure - shows the parts of def statement it has the def keyword followed by function name with parentheses and then colon (the signthe block after the def statement is called the def-block figure - parts of def statement rememberthe def statement doesn' execute the code it only defines what code to execute when you call the function when the execution reaches def statement it skips down to the first line after the def-block but when the displayintro(function is called (such as on line )the execution moves inside of the displayintro(function to the first line of the def-block displayintro(then all of the print(calls are run and the "you are in land full of dragons introduction is displayed where to put function definitions function' def statement and the def-block must come before you call the function this is like how you must assign value to variable before you use the variable if you put the function call before the function definitionyou'll get an error for examplelook at this codesaygoodbye(def saygoodbye()
7,494
print('goodbye!'if you try to run itpython will give you an error message that looks like thistraceback (most recent call last)file " :\python \spam py"line in saygoodbye(nameerrorname 'saygoodbyeis not defined to fix thisput the function definition before the function calldef saygoodbye()print('goodbye!'saygoodbye(defining the choosecave(function def choosecave()line defines another function called choosecave(this function' code asks the player which cave they want to go ineither or cave 'while cave !' and cave !' 'this function needs to make sure the player typed or and not something else loop here will keep asking the player until they enter one of these two valid responses this is called input validation line creates new variable called cave and stores blank string in it then while loop begins on line the condition contains new operator you haven' seen before called and just like the or are mathematical operatorsand =or !are comparison operatorsthe and operator is boolean operator boolean operators boolean logic deals with things that are either true or false boolean operators compare values and evaluate to single boolean value post questions to
7,495
think of the sentence"cats have whiskers and dogs have tails "cats have whiskersis true and "dogs have tailsis also trueso the entire sentence "cats have whiskers and dogs have tailsis true but the sentence"cats have whiskers and dogs have wingswould be false even though "cats have whiskersis truedogs do not have wingsso "dogs have wingsis false in boolean logicthings can only be entirely true or entirely false because of the word "and"the entire sentence is only true if both parts are true if one or both parts are falsethen the entire sentence is false the and and or operators the and operator in python is the same if the boolean values on both sides of the and keyword are truethen the expression evaluates to true if either or both of the boolean values are falsethen the expression evaluates to false try entering the following expressions with the and operator into the interactive shelltrue and true true true and false false false and true false false and false false spam 'hello and spam ='hellotrue the or operator is similar to the and operatorexcept it will evaluate to true if either of the two boolean values are true the only time the or operator evaluates to false is if both of the boolean values are false try entering the following into the interactive shelltrue or true true true or false true false or true true false or false false or true
7,496
the not operator the not operator only works on one valueinstead of combining two values the not operator evaluates to the opposite boolean value the expression not true will evaluate to false and not false will evaluate to true try entering the following into the interactive shellnot true false not false true not ('black='white'true truth tables if you ever forget how the boolean operators workyou can look at these truth tablestable - the and operator' truth table and is entire statement true and true is true true and false is false false and true is false false and false is false table - the or operator' truth table or is entire statement true or true is true true or false is true false or true is true false or false is false table - the not operator' truth table not is entire statement not true is false not false is true post questions to
7,497
evaluating boolean operators look at line again while cave !' and cave !' 'the condition has two parts connected by the and boolean operator the condition is true only if both parts are true the first time the while statement' condition is checkedcave is set to the blank string'the blank string is not equal to the string ' 'so the left side evaluates to true the blank string is also not equal to the string ' 'so the right side evaluates to true so the condition then turns into true and true because both values are truethe condition finally evaluates to true so the program execution enters the while-block this is what the evaluation looks like (if the value of cave is the blank string)while cave !' and cave !' ' while '!' and cave !' ' while true and cave !' ' while true and '!' ' while true and truev while truegetting the player' input while cave !' and cave !' 'print('which cave will you go into( or )'cave input(line asks the player which cave they choose line lets the player type the response and hit enter this response is stored in cave after this code is executedthe execution loops back to the top of the while statement and rechecks the condition if the player typed in or then cave will either be ' or ' (since input(always returns stringsthis makes the condition falseand the program execution will continue past the while loop for exampleif the user entered ' then the evaluation would look like this
7,498
while cave !' and cave !' ' while ' !' and cave !' ' while false and cave !' ' while false and ' !' ' while false and truev while falsebut if the player typed or or hellothat response would be invalid the condition will be true and enters the while-block to ask the player again the program will keep asking until the player types or this will guarantee that once the execution moves onthe cave variable contains valid response return values return cave this is return statementwhich only appears inside def-blocks remember how the input(function returns string value that the player typed inthe choosecave(function will also return value line returns the string that is stored in caveeither ' or ' once the return statement executesthe program execution jumps immediately out of the defblock (this is like how the break statement will make the execution jump out of while-block the program execution moves back to the line with the function call the function call itself will evaluate to the return value skip down and look at line for moment cavenumber choosecave(when the choosecave(function is later called by the program on line the return value is stored in the cavenumber variable the while loop guarantees that choosecave(will only return either ' or ' as its return value so when line returns stringthe function call on line evaluates to this stringwhich is then stored in cavenumber post questions to
7,499
global scope and local scope your program' variables are forgotten after the program terminates the variables created while the execution is inside function call are the same the variables are created when the function is called and forgotten when the function returns rememberfunctions are kind of like miniprograms in your program when execution is inside functionyou cannot change the variables outside of the functionincluding variables inside other functions this is because these variables exist in different "scopeall variables exist in either the global scope or function call' local scope the scope outside of all functions is called the global scope the scope inside of function (for the duration of particular function callis called local scope the entire program has only one global scope variables defined in the global scope can be read outside and inside functionsbut can only be modified outside of all functions variables created in function call can only be read or modified during that function call you can read the value of global variables from the local scopebut attempting to change global variable from the local scope won' work what python actually does in that case is create local variable with the same name as the global variable you couldfor examplehave local variable named spam at the same time as having global variable named spam python will consider these to be two different variables look at this example to see what happens when you try to change global variable from inside local scope the comments explain what is going ondef bacon()we create local variable named "spaminstead of changing the value of the global variable "spam"spam the name "spamnow refers to the local variable only for the rest of this functionprint(spam spam global variable named "spam"print(spam bacon(call the bacon(functionthe global variable was not changed in bacon()print(spam when runthis code will output the following