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... |
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 =... |
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 ->~bashr... |
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 s... |
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 li... |
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 t... |
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... |
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 associa... |
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 hel... |
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... |
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... |
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 ... |
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 t... |
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 a... |
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 find... |
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 abstracti... |
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 sav... |
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 q... |
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 app... |
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 nu... |
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 simul... |
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 ... |
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 softw... |
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 prog... |
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... |
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 re... |
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 ... |
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 programm... |
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 fl... |
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 an... |
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 expre... |
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 statementsr... |
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 ... |
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 crea... |
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... |
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 ... |
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 ... |
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... |
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... |
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 o... |
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 but... |
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... |
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 ... |
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 ... |
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 standar... |
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... |
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... |
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 t... |
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-progr... |
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 ra... |
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 l... |
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... |
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 c... |
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... |
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 evaluate... |
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 ... |
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 us... |
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 t... |
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 ... |
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-b... |
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... |
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 eval... |
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 d... |
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 kn... |
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 quot... |
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 li... |
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 ... |
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()st... |
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... |
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 d... |
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... |
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(def... |
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 wings... |
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 ('bl... |
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 stri... |
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 pl... |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.