id
int64
0
25.6k
text
stringlengths
0
4.59k
0
eric matthes is high school science and math teacher living in alaskawhere he teaches an introductory python course he has been writing programs since he was five years old eric currently focuses on writing software that addresses inefficiencies in education and brings the benefits of open source software to the field of education in his spare time he enjoys climbing mountains and spending time with his family about the technical reviewer kenneth love has been python programmer and teacher for many years he has given talks and tutorials at conferencesdone professional trainingsbeen python and django freelancerand now teaches for an online education company kenneth is also the co-creator of the django-braces packagewhich provides several handy mixins for django' class-based views you can keep up with him on twitter at @kennethlove
1
answer my questions about programmingand for everwho is just beginning to ask me his questions
2
acknowledgments xxvii introduction xxix part ibasics getting started variables and simple data types introducing lists working with lists if statements dictionaries user input and while loops functions classes files and exceptions testing your code part iiprojects project alien invasion ship that fires bullets aliens scoring
3
generating data downloading data working with apis project web applications getting started with django user accounts styling and deploying an app afterword appendix ainstalling python appendix btext editors appendix cgetting help appendix dusing git for version control index brief contents
4
acknowledgments xxvii introduction xxix who is this book forxxx what can you expect to learnxxx why pythonxxxi part ibasics getting started setting up your programming environment python and python running snippets of python code hello world python on different operating systems python on linux python on os python on windows troubleshooting installation issues running python programs from terminal on linux and os on windows exercise - python org exercise - hello world typos exercise - infinite skills summary variables and simple data types what really happens when you run hello_world py variables naming and using variables avoiding name errors when using variables exercise - simple message exercise - simple messages strings changing case in string with methods combining or concatenating strings adding whitespace to strings with tabs or newlines stripping whitespace avoiding syntax errors with strings printing in python exercise - personal message exercise - name cases exercise - famous quote
5
exercise - stripping names numbers integers floats avoiding type errors with the str(function integers in python exercise - number eight exercise - favorite number comments how do you write comments what kind of comments should you write exercise - adding comments the zen of python exercise - zen of python summary introducing lists what is list accessing elements in list index positions start at not using individual values from list exercise - names exercise - greetings exercise - your own list changingaddingand removing elements modifying elements in list adding elements to list removing elements from list exercise - guest list exercise - changing guest list exercise - more guests exercise - shrinking guest list organizing list sorting list permanently with the sort(method sorting list temporarily with the sorted(function printing list in reverse order finding the length of list exercise - seeing the world exercise - dinner guests exercise - every function avoiding index errors when working with lists exercise - intentional error summary working with lists looping through an entire list closer look at looping doing more work within for loop doing something after for loop xii contents in detail
6
forgetting to indent forgetting to indent additional lines indenting unnecessarily indenting unnecessarily after the loop forgetting the colon exercise - pizzas exercise - animals making numerical lists using the range(function using range(to make list of numbers simple statistics with list of numbers list comprehensions exercise - counting to twenty exercise - one million exercise - summing million exercise - odd numbers exercise - threes exercise - cubes exercise - cube comprehension working with part of list slicing list looping through slice copying list exercise - slices exercise - my pizzasyour pizzas exercise - more loops tuples defining tuple looping through all values in tuple writing over tuple exercise - buffet styling your code the style guide indentation line length blank lines other style guidelines exercise - pep exercise - code review summary if statements simple example conditional tests checking for equality ignoring case when checking for equality checking for inequality numerical comparisons checking multiple conditions checking whether value is in list contents in detail xiii
7
boolean expressions exercise - conditional tests exercise - more conditional tests if statements simple if statements if-else statements the if-elif-else chain using multiple elif blocks omitting the else block testing multiple conditions exercise - alien colors # exercise - alien colors # exercise - alien colors # exercise - stages of life exercise - favorite fruit using if statements with lists checking for special items checking that list is not empty using multiple lists exercise - hello admin exercise - no users exercise - checking usernames exercise - ordinal numbers styling your if statements exercise - styling if statements exercise - your ideas summary dictionaries simple dictionary working with dictionaries accessing values in dictionary adding new key-value pairs starting with an empty dictionary modifying values in dictionary removing key-value pairs dictionary of similar objects exercise - person exercise - favorite numbers exercise - glossary looping through dictionary looping through all key-value pairs looping through all the keys in dictionary looping through dictionary' keys in order looping through all values in dictionary exercise - glossary exercise - rivers exercise - polling nesting list of dictionaries list in dictionary xiv contents in detail
8
exercise - people exercise - pets exercise - favorite places exercise - favorite numbers exercise - cities exercise - extensions summary user input and while loops how the input(function works writing clear prompts using int(to accept numerical input the modulo operator accepting input in python exercise - rental car exercise - restaurant seating exercise - multiples of ten introducing while loops the while loop in action letting the user choose when to quit using flag using break to exit loop using continue in loop avoiding infinite loops exercise - pizza toppings exercise - movie tickets exercise - three exits exercise - infinity using while loop with lists and dictionaries moving items from one list to another removing all instances of specific values from list filling dictionary with user input exercise - deli exercise - no pastrami exercise - dream vacation summary functions defining function passing information to function arguments and parameters exercise - message exercise - favorite book passing arguments positional arguments keyword arguments default values contents in detail xv
9
avoiding argument errors exercise - -shirt exercise - large shirts exercise - cities return values returning simple value making an argument optional returning dictionary using function with while loop exercise - city names exercise - album exercise - user albums passing list modifying list in function preventing function from modifying list exercise - magicians exercise - great magicians exercise - unchanged magicians passing an arbitrary number of arguments mixing positional and arbitrary arguments using arbitrary keyword arguments exercise - sandwiches exercise - user profile exercise - cars storing your functions in modules importing an entire module importing specific functions using as to give function an alias using as to give module an alias importing all functions in module styling functions exercise - printing models exercise - imports exercise - styling functions summary classes creating and using class creating the dog class making an instance from class exercise - restaurant exercise - three restaurants exercise - users working with classes and instances the car class setting default value for an attribute modifying attribute values exercise - number served exercise - login attempts xvi contents in detail
10
the __init__(method for child class inheritance in python defining attributes and methods for the child class overriding methods from the parent class instances as attributes modeling real-world objects exercise - ice cream stand exercise - admin exercise - privileges exercise - battery upgrade importing classes importing single class storing multiple classes in module importing multiple classes from module importing an entire module importing all classes from module importing module into module finding your own workflow exercise - imported restaurant exercise - imported admin exercise - multiple modules the python standard library exercise - ordereddict rewrite exercise - dice exercise - python module of the week styling classes summary files and exceptions reading from file reading an entire file file paths reading line by line making list of lines from file working with file' contents large filesone million digits is your birthday contained in pi exercise - learning python exercise - learning writing to file writing to an empty file writing multiple lines appending to file exercise - guest exercise - guest book exercise - programming poll exceptions handling the zerodivisionerror exception using try-except blocks using exceptions to prevent crashes contents in detail xvii
11
handling the filenotfounderror exception analyzing text working with multiple files failing silently deciding which errors to report exercise - addition exercise - addition calculator exercise - cats and dogs exercise - silent cats and dogs exercise - common words storing data using json dump(and json load( saving and reading user-generated data refactoring exercise - favorite number exercise - favorite number remembered exercise - verify user summary testing your code testing function unit tests and test cases passing test failing test responding to failed test adding new tests exercise - citycountry exercise - population testing class variety of assert methods class to test testing the anonymoussurvey class the setup(method exercise - employee summary part iiprojects project alien invasion ship that fires bullets planning your project installing pygame installing python packages with pip installing pygame on linux xviii contents in detail
12
installing pygame on windows starting the game project creating pygame window and responding to user input setting the background color creating settings class adding the ship image creating the ship class drawing the ship to the screen refactoringthe game_functions module the check_events(function the update_screen(function exercise - blue sky exercise - game character piloting the ship responding to keypress allowing continuous movement moving both left and right adjusting the ship' speed limiting the ship' range refactoring check_events( quick recap alien_invasion py settings py game_functions py ship py exercise - rocket exercise - keys shooting bullets adding the bullet settings creating the bullet class storing bullets in group firing bullets deleting old bullets limiting the number of bullets creating the update_bullets(function creating the fire_bullet(function exercise - sideways shooter summary aliens reviewing your project creating the first alien creating the alien class creating an instance of the alien making the alien appear onscreen building the alien fleet determining how many aliens fit in row creating rows of aliens creating the fleet contents in detail xix
13
adding rows exercise - stars exercise - better stars making the fleet move moving the aliens right creating settings for fleet direction checking to see whether an alien has hit the edge dropping the fleet and changing direction exercise - raindrops exercise - steady rain shooting aliens detecting bullet collisions making larger bullets for testing repopulating the fleet speeding up the bullets refactoring update_bullets( exercise - catch ending the game detecting alien-ship collisions responding to alien-ship collisions aliens that reach the bottom of the screen game over identifying when parts of the game should run exercise - game over summary scoring adding the play button creating button class drawing the button to the screen starting the game resetting the game deactivating the play button hiding the mouse cursor exercise - press to play exercise - target practice leveling up modifying the speed settings resetting the speed exercise - challenging target practice scoring displaying the score making scoreboard updating the score as aliens are shot down making sure to score all hits increasing point values rounding the score high scores xx contents in detail
14
displaying the number of ships exercise - all-time high score exercise - refactoring exercise - expanding alien invasion summary project data visualization generating data installing matplotlib on linux on os on windows testing matplotlib the matplotlib gallery plotting simple line graph changing the label type and graph thickness correcting the plot plotting and styling individual points with scatter( plotting series of points with scatter( calculating data automatically removing outlines from data points defining custom colors using colormap saving your plots automatically exercise - cubes exercise - colored cubes random walks creating the randomwalk(class choosing directions plotting the random walk generating multiple random walks styling the walk coloring the points plotting the starting and ending points cleaning up the axes adding plot points altering the size to fill the screen exercise - molecular motion exercise - modified random walks exercise - refactoring rolling dice with pygal installing pygal the pygal gallery creating the die class rolling the die analyzing the results contents in detail xxi
15
rolling two dice rolling dice of different sizes exercise - automatic labels exercise - two exercise - three dice exercise - multiplication exercise - practicing with both libraries summary downloading data the csv file format parsing the csv file headers printing the headers and their positions extracting and reading data plotting data in temperature chart the datetime module plotting dates plotting longer timeframe plotting second data series shading an area in the chart error-checking exercise - san francisco exercise - sitka-death valley comparison exercise - rainfall exercise - explore mapping global data setsjson format downloading world population data extracting relevant data converting strings into numerical values obtaining two-digit country codes building world map plotting numerical data on world map plotting complete population map grouping countries by population styling world maps in pygal lightening the color theme exercise - all countries exercise - gross domestic product exercise - choose your own data exercise - testing the country_codes module summary working with apis using web api git and github requesting data using an api call installing requests xxii contents in detail
16
working with the response dictionary summarizing the top repositories monitoring api rate limits visualizing repositories using pygal refining pygal charts adding custom tooltips plotting the data adding clickable links to our graph the hacker news api exercise - other languages exercise - active discussions exercise - testing python_repos py summary project web applications getting started with django setting up project writing spec creating virtual environment installing virtualenv activating the virtual environment installing django creating project in django creating the database viewing the project exercise - new projects starting an app defining models activating models the django admin site defining the entry model migrating the entry model registering entry with the admin site the django shell exercise - short entries exercise - the django api exercise - pizzeria making pagesthe learning log home page mapping url writing view writing template exercise - meal planner exercise - pizzeria home page building additional pages template inheritance the topics page individual topic pages contents in detail xxiii
17
exercise - pizzeria pages summary user accounts allowing users to enter data adding new topics adding new entries editing entries exercise - blog setting up user accounts the users app the login page logging out the registration page exercise - blog accounts allowing users to own their data restricting access with @login_required connecting data to certain users restricting topics access to appropriate users protecting user' topics protecting the edit_entry page associating new topics with the current user exercise - refactoring exercise - protecting new_entry exercise - protected blog summary styling and deploying an app styling learning log the django-bootstrap app using bootstrap to style learning log modifying base html styling the home page using jumbotron styling the login page styling the new_topic page styling the topics page styling the entries on the topic page exercise - other forms exercise - stylish blog deploying learning log making heroku account installing the heroku toolbelt installing required packages creating packages list with requirements txt file specifying the python runtime modifying settings py for heroku making procfile to start processes modifying wsgi py for heroku xxiv contents in detail
18
using the gunicorn server locally using git to track the project' files pushing to heroku setting up the database on heroku refining the heroku deployment securing the live project committing and pushing changes creating custom error pages ongoing development the secret_key setting deleting project on heroku exercise - live blog exercise - more exercise - extended learning log summary afterword installing python python on linux finding the installed version installing python on linux python on os finding the installed version using homebrew to install python python on windows installing python on windows finding the python interpreter adding python to your path variable python keywords and built-in functions python keywords python built-in functions text editors geany installing geany on linux installing geany on windows running python programs in geany customizing geany settings sublime text installing sublime text on os installing sublime text on linux installing sublime text on windows running python programs in sublime text configuring sublime text customizing sublime text settings contents in detail xxv
19
installing idle on linux installing idle on os installing idle on windows customizing idle settings emacs and vim getting help first steps try it again take break refer to this book' resources searching online stack overflow the official python documentation official library documentation /learnpython blog posts irc (internet relay chat make an irc account channels to join irc culture using git for version control installing git installing git on linux installing git on os installing git on windows configuring git making project ignoring files initializing repository checking the status adding files to the repository making commit checking the log the second commit reverting change checking out previous commits deleting the repository index xxvi contents in detail
20
this book would not have been possible without the wonderful and extremely professional staff at no starch press bill pollock invited me to write an introductory bookand deeply appreciate that original offer tyler ortman helped shape my thinking in the early stages of drafting liz chadwick' and leslie shen' initial feedback on each was invaluableand anne marie walker helped to clarify many parts of the book riley hoffman answered every question had about the process of assembling complete book and patiently turned my work into beautiful finished product ' like to thank kenneth lovethe technical reviewer for python crash course met kenneth at pycon one yearand his enthusiasm for the language and the python community has been constant source of professional inspiration ever since kenneth went beyond simple fact-checking and reviewed the book with the goal of helping beginning programmers develop solid understanding of the python language and programming in general that saidany inaccuracies that remain are completely my own ' like to thank my father for introducing me to programming at young age and for not being afraid that ' break his equipment ' like to thank my wifeerinfor supporting and encouraging me through the writing of this bookand ' like to thank my soneverwhose curiosity inspires me every single day
21
every programmer has story about how they learned to write their first program started learning as child when my father was working for digital equipment corporationone of the pioneering companies of the modern computing era wrote my first program on kit computer my dad had assembled in our basement the computer consisted of nothing more than bare motherboard connected to keyboard without caseand it had bare cathode ray tube for monitor my initial program was simple number guessing gamewhich looked something like thisi' thinking of numbertry to guess the number ' thinking of too lowguess again too highguess again that' itwould you like to play again(yes/nono thanks for playing
22
that created and that worked as intended it to that early experience had lasting impact there is real satisfaction in building something with purposesomething that solves problem the software write now meets more significant need than my childhood effortsbut the sense of satisfaction get from creating program that works is still largely the same who is this book forthe goal of this book is to bring you up to speed with python as quickly as possible so you can build programs that work--gamesdata visualizationsand web applications--while developing foundation in programming that will serve you well for the rest of your life python crash course is written for people of any age who have never programmed in python before or have never programmed at all if you want to learn the basics of programming quickly so you can focus on interesting projectsand you like to test your understanding of new concepts by solving meaningful problemsthis book is for you python crash course is also perfect for middle school and high school teachers who want to offer their students project-based introduction to programming what can you expect to learnthe purpose of this book is to make you good programmer in general and good python programmer in particular you'll learn efficiently and adopt good habits as provide you with solid foundation in general programming concepts after working your way through python crash courseyou should be ready to move on to more advanced python techniquesand your next programming language will be even easier to grasp in the first part of this book you'll learn basic programming concepts you need to know to write python programs these concepts are the same as those you' learn when starting out in almost any programming language you'll learn about different kinds of data and the ways you can store data in lists and dictionaries within your programs you'll learn to build collections of data and work through those collections in efficient ways you'll learn to use while and if loops to test for certain conditions so you can run specific sections of code while those conditions are true and run other sections when they're not-- technique that greatly helps to automate processes you'll learn to accept input from users to make your programs inter active and to keep your programs running as long as the user is active you'll explore how to write functions to make parts of your program reusableso you only have to write blocks of code that perform certain xxx introduction
23
extend this concept to more complicated behavior with classesmaking fairly simple programs respond to variety of situations you'll learn to write programs that handle common errors gracefully after working through each of these basic conceptsyou'll write few short programs that solve some well-defined problems finallyyou'll take your first step toward intermediate programming by learning how to write tests for your code so you can develop your programs further without worrying about introducing bugs all the information in part will prepare you for taking on largermore complex projects in part ii you'll apply what you learned in part to three projects you can do any or all of these projects in whichever order works best for you in the first project - you'll create space invaders-style shooting game called alien invasionwhich consists of levels of increasing difficulty after you've completed this projectyou should be well on your way to being able to develop your own games the second project - introduces you to data visualization data scientists aim to make sense of the vast amount of information available to them through variety of visualization techniques you'll work with data sets that you generate through codedata sets downloaded from online sourcesand data sets your programs download automatically after you've completed this projectyou'll be able to write programs that sift through large data sets and make visual representations of that stored information in the third project - you'll build small web application called learning log this project allows you to keep journal of ideas and concepts you've learned about specific topic you'll be able to keep separate logs for different topics and allow others to create an account and start their own journals you'll also learn how to deploy your project so anyone can access it online from anywhere why pythonevery year consider whether to continue using python or whether to move on to different language--perhaps one that' newer to the programming world but continue to focus on python for many reasons python is an incredibly efficient languageyour programs will do more in fewer lines of code than many other languages would require python' syntax will also help you write "cleancode your code will be easy to readeasy to debugand easy to extend and build upon compared to other languages people use python for many purposesto make gamesbuild web applicationssolve business problemsand develop internal tools at all kinds of interesting companies python is also used heavily in scientific fields for academic research and applied work introduction xxxi
24
because of the python communitywhich includes an incredibly diverse and welcoming group of people community is essential to programmers because programming isn' solitary pursuit most of useven the most experienced programmersneed to ask advice from others who have already solved similar problems having well-connected and supportive community is critical in helping you solve problemsand the python community is fully supportive of people like you who are learning python as your first programming language python is great language to learnso let' get startedxxxii introduction
25
ic part of this book teaches you the basic concepts you'll need to write python programs many of these concepts are common to all programming languagesso they'll be useful throughout your life as programmer in you'll install python on your computer and run your first programwhich prints the message hello worldto the screen in you'll learn to store information in variables and work with text and numerical values and introduce lists lists can store as much information as you want in one variableallowing you to work with that data efficiently you'll be able to work with hundredsthousandsand even millions of values in just few lines of code in you'll use if statements to write code that responds one way if certain conditions are trueand responds in different way if those conditions are not true shows you how to use python' dictionarieswhich let you make connections between different pieces of information like listsdictionaries can contain as much information as you need to store in you'll learn how to accept input from users to make your programs interactive you'll also learn about while loopswhich run blocks of code repeatedly as long as certain conditions remain true in you'll write functionswhich are named blocks of code that perform specific task and can be run whenever you need them
26
objectssuch as dogscatspeoplecarsrocketsand much moreso your code can represent anything real or abstract shows you how to work with files and handle errors so your programs won' crash unexpectedly you'll store data before your program closesand read the data back in when the program runs again you'll learn about python' exceptionswhich allow you to anticipate errorsand make your programs handle those errors gracefully in you'll learn to write tests for your code to check that your programs work the way you intend them to as resultyou'll be able to expand your programs without worrying about introducing new bugs testing your code is one of the first skills that will help you transition from beginner to intermediate programmer part
27
ge ting ta te in this you'll run your first python programhello_world py firstyou'll need to check whether python is installed on your computerif it isn'tyou'll install it you'll also install text editor to work with your python programs text editors recognize python code and highlight sections as you writemaking it easy to understand the structure of your code setting up your programming environment python differs slightly on different operating systemsso you'll need to keep few considerations in mind herewe'll look at the two major versions of python currently in use and outline the steps to set up python on your system
28
todaytwo versions of python are availablepython and the newer python every programming language evolves as new ideas and technologies emergeand the developers of python have continually made the language more versatile and powerful most changes are incremental and hardly noticeablebut in some cases code written for python may not run properly on systems with python installed throughout this book 'll point out areas of significant difference between python and python so whichever version you useyou'll be able to follow the instructions if both versions are installed on your system or if you need to install pythonuse python if python is the only version on your system and you' rather jump into writing code instead of installing pythonyou can start with python but the sooner you upgrade to using python the betterso you'll be working with the most recent version running snippets of python code python comes with an interpreter that runs in terminal windowallowing you to try bits of python without having to save and run an entire program throughout this bookyou'll see snippets that look like thisu print("hello python interpreter!"hello python interpreterthe text in bold is what you'll type in and then execute by pressing enter most of the examples in the book are smallself-contained programs that you'll run from your editorbecause that' how you'll write most of your code but sometimes basic concepts will be shown in series of snippets run through python terminal session to demonstrate isolated concepts more efficiently any time you see the three angle brackets in code listing uyou're looking at the output of terminal session we'll try coding in the interpreter for your system in moment hello worlda long-held belief in the programming world has been that printing hello worldmessage to the screen as your first program in new language will bring you luck in pythonyou can write the hello world program in one lineprint("hello world!"such simple program serves very real purpose if it runs correctly on your systemany python program you write should work as well we'll look at writing this program on your particular system in just moment
29
python is cross-platform programming languagewhich means it runs on all the major operating systems any python program you write should run on any modern computer that has python installed howeverthe methods for setting up python on different operating systems vary slightly in this section you'll learn how to set up python and run the hello world program on your own system you'll first check whether python is installed on your system and install it if it' not then you'll install simple text editor and save an empty python file called hello_world py finallyyou'll run the hello world program and troubleshoot anything that didn' work 'll walk you through this process for each operating systemso you'll have beginner-friendly python programming environment python on linux linux systems are designed for programmingso python is already installed on most linux computers the people who write and maintain linux expect you to do your own programming at some point and encourage you to do so for this reason there' very little you have to install and very few settings you have to change to start programming checking your version of python open terminal window by running the terminal application on your system (in ubuntuyou can press ctrl alt-tto find out whether python is installedenter python with lowercase you should see output telling you which version of python is installed and prompt where you can start entering python commandslike thispython python (defaultmar : : [gcc on linux type "help""copyright""creditsor "licensefor more information this output tells you that python is currently the default version of python installed on this computer when you've seen this outputpress ctrl - or enter exit(to leave the python prompt and return to terminal prompt to check for python you might have to specify that versionso even if the output displayed python as the default versiontry the command python python python (defaultsep : : [gcc on linux type "help""copyright""creditsor "licensefor more information getting started
30
able to use either version whenever you see the python command in this bookenter python instead most linux distributions have python already installedbut if for some reason yours didn' or if your system came with python and you want to install python refer to appendix installing text editor geany is simple text editorit' easy to installwill let you run almost all your programs directly from the editor instead of through terminaluses syntax highlighting to color your codeand runs your code in terminal window so you'll get used to using terminals appendix provides information on other text editorsbut recommend using geany unless you have good reason to use different editor you can install geany in one line on most linux systemssudo apt-get install geany if this doesn' worksee the instructions at thirdpartypackagesrunning the hello world program to start your first programopen geany press the super key (often called the windows keyand search for geany on your system make shortcut by dragging the icon to your taskbar or desktop then make folder somewhere on your system for your projects and call it python_work (it' best to use lowercase letters and underscores for spaces in file and folder names because these are python naming conventions go back to geany and save an empty python file (file save ascalled hello_world py in your python_ work folder the extension py tells geany your file will contain python program it also tells geany how to run your program and highlight the text in helpful way after you've saved your fileenter the following lineprint("hello python world!"if multiple versions of python are installed on your systemyou need to make sure geany is configured to use the correct version go to build set build commands you should see the words compile and execute with command next to each geany assumes the correct command for each is pythonbut if your system uses the python commandyou'll need to change this if the command python worked in terminal sessionchange the compile and execute commands so geany will use the python interpreter your compile command should look like thispython - py_compile "%
31
spaces and capitalization match what is shown here your execute command should look like thispython "%fagainmake sure the spacing and capitalization match what is shown here figure - shows how these commands should look in geany' configuration menu figure - heregeany is configured to use python on linux now run hello_world py by selecting build execute in the menuby clicking the execute icon (which shows set of gears)or by pressing terminal window should pop up with the following outputhello python world(program exited with code press return to continue if you don' see thischeck every character on the line you entered did you accidentally capitalize printdid you forget one or both of the quotation marks or parenthesesprogramming languages expect very specific syntaxand if you don' provide thatyou'll get errors if you can' get the program to runsee "troubleshooting installation issueson page getting started
32
you can try running snippets of python code by opening terminal and typing python or python as you did when checking your version do this againbut this time enter the following line in the terminal sessionprint("hello python interpreter!"hello python interpreteryou should see your message printed directly in the current terminal window remember that you can close the python interpreter by pressing ctrl - or by typing the command exit(python on os python is already installed on most os systems once you know python is installedyou'll need to install text editor and make sure it' configured correctly checking whether python is installed open terminal window by going to applications utilities terminal you can also press command -spacebartype terminaland then press enter to find out whether python is installedenter python with lowercase you should see output telling you which version of python is installed on your system and prompt where you can start entering python commandslike thispython python (defaultmar : : [gcc compatible apple llvm (clang-)on darwin type "help""copyright""credits"or "licensefor more information this output tells you that python is currently the default version installed on this computer when you've seen this outputpress ctrl - or enter exit(to leave the python prompt and return to terminal prompt to check for python try the command python you might get an error messagebut if the output shows you have python installedyou'll be able to use python without having to install it if python works on your systemwhenever you see the python command in this bookmake sure you use python instead if for some reason your system didn' come with python or if you only have python and you want to install python nowsee appendix
33
you can try running snippets of python code by opening terminal and typing python or python as you did when checking your version do this againbut this time enter the following line in the terminal sessionprint("hello python interpreter!"hello python interpreteryou should see your message printed directly in the current terminal window remember that you can close the python interpreter by pressing ctrl - or by typing the command exit(installing text editor sublime text is simple text editorit' easy to install on os xwill let you run almost all of your programs directly from the editor instead of through terminaluses syntax highlighting to color your codeand runs your code in terminal session embedded in the sublime text window to make it easy to see the output appendix provides information on other text editorsbut recommend using sublime text unless you have good reason to use different editor you can download an installer for sublime text from com/ click the download link and look for an installer for os sublime text has very liberal licensing policyyou can use the editor for free as long as you wantbut the author requests that you purchase license if you like it and want continual use after the installer has been downloadedopen it and then drag the sublime text icon into your applications folder configuring sublime text for python if you use command other than python to start python terminal sessionyou'll need to configure sublime text so it knows where to find the correct version of python on your system issue the following command to find out the full path to your python interpretertype - python python is /usr/local/bin/python now open sublime textand go to tools build system new build systemwhich will open new configuration file for you delete what you see and enter the followingpython sublime-build "cmd"["/usr/local/bin/python ""- ""$file"]getting started
34
when running the currently open file make sure you use the path you found when issuing the command type - python in the previous step save the file as python sublime-build in the default directory that sublime text opens when you choose save running the hello world program to start your first programlaunch sublime text by opening the applications folder and double-clicking the sublime text icon you can also press command -spacebar and enter sublime text in the search bar that pops up make folder called python_work somewhere on your system for your projects (it' best to use lowercase letters and underscores for spaces in file and folder namesbecause these are python naming conventions save an empty python file (file save ascalled hello_world py in your python_work folder the extension py tells sublime text that your file will contain python program and tells it how to run your program and highlight the text in helpful way after you've saved your fileenter the following lineprint("hello python world!"if the command python works on your systemyou can run your program by selecting tools build in the menu or by pressing ctrl- if you configured sublime text to use command other than pythonselect tools build system and then select python this sets python as the default version of pythonand you'll be able to select tools build or just press command - to run your programs from now on terminal screen should appear at the bottom of the sublime text windowshowing the following outputhello python world[finished in sif you don' see thischeck every character on the line you entered did you accidentally capitalize printdid you forget one or both of the quotation marks or parenthesesprogramming languages expect very specific syntaxand if you don' provide thatyou'll get errors if you can' get the program to runsee "troubleshooting installation issueson page python on windows windows doesn' always come with pythonso you'll probably need to download and install itand then download and install text editor
35
firstcheck whether python is installed on your system open command window by entering command into the start menu or by holding down the shift key while right-clicking on your desktop and selecting open command window here in the terminal windowenter python in lowercase if you get python prompt ()python is installed on your system howeveryou'll probably see an error message telling you that python is not recognized command in that casedownload python installer for windows go to python org/downloadsyou should see two buttonsone for downloading python and one for downloading python click the python buttonwhich should automatically start downloading the correct installer for your system after you've downloaded the filerun the installer make sure you check the option add python to pathwhich will make it easier to configure your system correctly figure - shows this option checked figure - make sure you check the box labeled add python to path starting python terminal session setting up your text editor will be straightforward if you first set up your system to run python in terminal session open command window and enter python in lowercase if you get python prompt ()windows has found the version of python you just installedc:\python python ( : sep : : [msc bit (intel)on win type "help""copyright""creditsor "licensefor more information getting started
36
in terminal session howeveryou may see output that looks more like thisc:\python 'pythonis not recognized as an internal or external commandoperable program or batch file in this case you need to tell windows how to find the python version you just installed your system' python command is usually saved in your driveso open windows explorer and open your drive look for folder starting with the name pythonopen that folderand find the python file (in lowercasefor examplei have python folder with file named python inside itso the path to the python command on my system is :\python python otherwiseenter python into the search box in windows explorer to show you exactly where the python command is stored on your system when you think you know the pathtest it by entering that path into terminal window open command window and enter the full path you just foundc:\ :\python \python python ( : sep : : [msc bit (intel)on win type "help""copyright""creditsor "licensefor more information if this workedyou know how to access python on your system running python in terminal session enter the following line in your python sessionand make sure you see the output hello python worldprint("hello python world!"hello python worldany time you want to run snippet of python codeopen command window and start python terminal session to close the terminal sessionpress ctrl- and then press enteror enter the command exit(installing text editor geany is simple text editorit' easy to installwill let you run almost all of your programs directly from the editor instead of through terminaluses syntax highlighting to color your codeand runs your code in terminal window so you'll get used to using terminals appendix provides information on other text editorsbut recommend using geany unless you have good reason to use different editor
37
click releases under the download menuand look for the geany- setup exe installer or something similar run the installer and accept all the defaults to start your first programopen geanypress the windows key and search for geany on your system you should make shortcut by dragging the icon to your taskbar or desktop make folder called python_work somewhere on your system for your projects (it' best to use lowercase letters and underscores for spaces in file and folder namesbecause these are python naming conventions go back to geany and save an empty python file (file save ascalled hello_world py in your python_work folder the extension py tells geany that your file will contain python program it also tells geany how to run your program and to highlight the text in helpful way after you've saved your filetype the following lineprint("hello python world!"if the command python worked on your systemyou won' have to configure geanyskip the next section and move on to "running the hello world programon page if you needed to enter path like :\python \python to start python interpreterfollow the directions in the next section to configure geany for your system configuring geany to configure geanygo to build set build commands you should see the words compile and execute with command next to each the compile and execute commands start with python in lowercasebut geany doesn' know where your system stored the python command you need to add the path you used in the terminal session in the compile and execute commandsadd the drive your python command is on and the folder where the python command is stored your compile command should look something like thisc:\python \python - py_compile "%fyour path might be little differentbut make sure the spaces and capitalization match what is shown here your execute command should look something like thisc:\python \python "%fagainmake sure the spacing and capitalization in your execute command matches what is shown here figure - shows how these commands should look in geany' configuration menu getting started
38
after you've set these commands correctlyclick ok running the hello world program you should now be able to run your program successfully run hello_world py by selecting build execute in the menuby clicking the execute icon (which shows set of gears)or by pressing terminal window should pop up with the following outputhello python world(program exited with code press return to continue if you don' see thischeck every character on the line you entered did you accidentally capitalize printdid you forget one or both of the quotation marks or parenthesesprogramming languages expect very specific syntaxand if you don' provide thatyou'll get errors if you can' get the program to runsee the next section for help
39
hopefullysetting up your programming environment was successfulbut if you've been unable to run hello_world pyhere are few remedies you can trywhen program contains significant errorpython displays traceback python looks through the file and tries to report the problem the traceback might give you clue as to what issue is preventing the program from running step away from your computertake short breakand then try again remember that syntax is very important in programmingso even missing colona mismatched quotation markor mismatched paren theses can prevent program from running properly reread the relevant parts of this look over what you've doneand see if you can find the mistake start over again you probably don' need to uninstall anythingbut it might make sense to delete your hello_world py file and create it again from scratch ask someone else to follow the steps in this on your computer or different oneand watch what they do carefully you might have missed one small step that someone else happens to catch find someone who knows python and ask them to help you get set up if you ask aroundyou might find that you know someone who uses python the setup instructions in this are also available onlinethrough instructions may work better for you ask for help online appendix provides number of resources and areas onlinelike forums and live chat siteswhere you can ask for solutions from people who've already worked through the issue you're currently facing don' worry about bothering experienced programmers every programmer has been stuck at some pointand most programmers are happy to help you set up your system correctly as long as you can state clearly what you're trying to dowhat you've already triedand the results you're gettingthere' good chance someone will be able to help you as mentioned in the introductionthe python community is very beginner friendly python should run well on any modern computerso find way to ask for help if you're having trouble so far early issues can be frustratingbut they're well worth sorting out once you get hello_world py runningyou can start to learn pythonand your programming work will become more interesting and satisfying getting started
40
most of the programs you write in your text editor you'll run directly from the editorbut sometimes it' useful to run programs from terminal instead for exampleyou might want to run an existing program without opening it for editing you can do this on any system with python installed if you know how to access the directory where you've stored your program file to try thismake sure you've saved the hello_world py file in the python_work folder on your desktop on linux and os running python program from terminal session is the same on linux and os the terminal command cdfor change directoryis used to navigate through your file system in terminal session the command lsfor listshows you all the nonhidden files that exist in the current directory open new terminal window and issue the following commands to run hello_world pyu ~cd desktop/python_workv ~/desktop/python_workls hello_world py ~/desktop/python_workpython hello_world py hello python worldat we use the cd command to navigate to the python_work folderwhich is in the desktop folder nextwe use the ls command to make sure hello_world py is in this folder thenwe run the file using the command python hello_world py it' that simple you just use the python (or python command to run python programs on windows the terminal command cdfor change directoryis used to navigate through your file system in command window the command dirfor directoryshows you all the files that exist in the current directory open new terminal window and issue the following commands to run hello_world pyu :\cd desktop\python_work :\desktop\python_workdir hello_world py :\desktop\python_workpython hello_world py hello python worldat we use the cd command to navigate to the python_work folderwhich is in the desktop folder nextwe use the dir command to make sure hello_world py is in this folder thenwe run the file using the command python hello_world py
41
pythonyou may need to use the longer version of this commandc:\cd desktop\python_work :\desktop\python_workdir hello_world py :\desktop\python_workc:\python \python hello_world py hello python worldmost of your programs will run fine directly from your editorbut as your work becomes more complexyou might write programs that you'll need to run from terminal try it yourse lf the exercises in this are exploratory in nature starting in the challenges you'll solve will be based on what you've learned - python orgexplore the python home page (topics that interest you as you become familiar with pythondifferent parts of the site will be more useful to you - hello world typosopen the hello_world py file you just created make typo somewhere in the line and run the program again can you make typo that generates an errorcan you make sense of the error messagecan you make typo that doesn' generate an errorwhy do you think it didn' make an error - infinite skillsif you had infinite programming skillswhat would you buildyou're about to learn how to program if you have an end goal in mindyou'll have an immediate use for your new skillsnow is great time to draft descriptions of what you' like to create it' good habit to keep an "ideasnotebook that you can refer to whenever you want to start new project take few minutes now to describe three programs you' like to create summary in this you learned bit about python in generaland you installed python to your system if it wasn' already there you also installed text editor to make it easier to write python code you learned to run snippets of python code in terminal sessionand you ran your first actual programhello_world py you probably learned bit about troubleshooting as well in the next you'll learn about the different kinds of data you can work with in your python programsand you'll learn to use variables as well getting started
42
variables and si in this you'll learn about the different kinds of data you can work with in your python programs you'll also learn how to store your data in variables and how to use those variables in your programs what really happens when you run hello_world py let' take closer look at what python does when you run hello_world py as it turns outpython does fair amount of workeven when it runs simple programhello_world py print("hello python world!"
43
hello python worldwhen you run the file hello_world pythe ending py indicates that the file is python program your editor then runs the file through the python interpreterwhich reads through the program and determines what each word in the program means for examplewhen the interpreter sees the word printit prints to the screen whatever is inside the parentheses as you write your programsyour editor highlights different parts of your program in different ways for exampleit recognizes that print is the name of function and displays that word in blue it recognizes that "hello python world!is not python code and displays that phrase in orange this feature is called syntax highlighting and is quite useful as you start to write your own programs variables let' try using variable in hello_world py add new line at the beginning of the fileand modify the second linemessage "hello python world!print(messagerun this program to see what happens you should see the same output you saw previouslyhello python worldwe've added variable named message every variable holds valuewhich is the information associated with that variable in this case the value is the text "hello python world!adding variable makes little more work for the python interpreter when it processes the first lineit associates the text "hello python world!with the variable message when it reaches the second lineit prints the value associated with message to the screen let' expand on this program by modifying hello_world py to print second message add blank line to hello_world pyand then add two new lines of codemessage "hello python world!print(messagemessage "hello python crash course world!print(message
44
hello python worldhello python crash course worldyou can change the value of variable in your program at any timeand python will always keep track of its current value naming and using variables when you're using variables in pythonyou need to adhere to few rules and guidelines breaking some of these rules will cause errorsother guidelines just help you write code that' easier to read and understand be sure to keep the following variable rules in mindvariable names can contain only lettersnumbersand underscores they can start with letter or an underscorebut not with number for instanceyou can call variable message_ but not _message spaces are not allowed in variable namesbut underscores can be used to separate words in variable names for examplegreeting_message worksbut greeting message will cause errors avoid using python keywords and function names as variable namesthat isdo not use words that python has reserved for particular programmatic purposesuch as the word print (see "python keywords and built-in functionson page variable names should be short but descriptive for examplename is better than nstudent_name is better than s_nand name_length is better than length_of_persons_name be careful when using the lowercase letter and the uppercase letter because they could be confused with the numbers and it can take some practice to learn how to create good variable namesespecially as your programs become more interesting and complicated as you write more programs and start to read through other people' codeyou'll get better at coming up with meaningful names note the python variables you're using at this point should be lowercase you won' get errors if you use uppercase lettersbut it' good idea to avoid using them for now avoiding name errors when using variables every programmer makes mistakesand most make mistakes every day although good programmers might create errorsthey also know how to respond to those errors efficiently let' look at an error you're likely to make early on and learn how to fix it variables and simple data types
45
following codeincluding the misspelled word mesage shown in boldmessage "hello python crash course reader!print(mesagewhen an error occurs in your programthe python interpreter does its best to help you figure out where the problem is the interpreter provides traceback when program cannot run successfully traceback is record of where the interpreter ran into trouble when trying to execute your code here' an example of the traceback that python provides after you've accidentally misspelled variable' nametraceback (most recent call last) file "hello_world py"line in print(mesagew nameerrorname 'mesageis not defined the output at reports that an error occurs in line of the file hello_world py the interpreter shows this line to help us spot the error quickly and tells us what kind of error it found in this case it found name error and reports that the variable being printedmesagehas not been defined python can' identify the variable name provided name error usually means we either forgot to set variable' value before using itor we made spelling mistake when entering the variable' name of coursein this example we omitted the letter in the variable name message in the second line the python interpreter doesn' spellcheck your codebut it does ensure that variable names are spelled consistently for examplewatch what happens when we spell message incorrectly in another place in the code as wellmesage "hello python crash course reader!print(mesagein this casethe program runs successfullyhello python crash course readercomputers are strictbut they disregard good and bad spelling as resultyou don' need to consider english spelling and grammar rules when you're trying to create variable names and writing code many programming errors are simplesingle-character typos in one line of program if you're spending long time searching for one of these errorsknow that you're in good company many experienced and talented programmers spend hours hunting down these kinds of tiny errors try to laugh about it and move onknowing it will happen frequently throughout your programming life
46
the best way to understand new programming concepts is to try using them in your programs if you get stuck while working on an exercise in this booktry doing something else for while if you're still stuckreview the relevant part of that if you still need helpsee the suggestions in appendix try it yourse lf write separate program to accomplish each of these exercises save each program with filename that follows standard python conventionsusing lowercase letters and underscoressuch as simple_message py and simple_messages py - simple messagestore message in variableand then print that message - simple messagesstore message in variableand print that message then change the value of your variable to new messageand print the new message strings because most programs define and gather some sort of dataand then do something useful with itit helps to classify different types of data the first data type we'll look at is the string strings are quite simple at first glancebut you can use them in many different ways string is simply series of characters anything inside quotes is considered string in pythonand you can use single or double quotes around your strings like this"this is string 'this is also string this flexibility allows you to use quotes and apostrophes within your strings' told my friend"python is my favorite language!""the language 'pythonis named after monty pythonnot the snake "one of python' strengths is its diverse and supportive community let' explore some of the ways you can use strings variables and simple data types
47
one of the simplest tasks you can do with strings is change the case of the words in string look at the following codeand try to determine what' happeningname py name "ada lovelaceprint(name title()save this file as name pyand then run it you should see this outputada lovelace in this examplethe lowercase string "ada lovelaceis stored in the variable name the method title(appears after the variable in the print(statement method is an action that python can perform on piece of data the dot after name in name title(tells python to make the title(method act on the variable name every method is followed by set of parenthesesbecause methods often need additional information to do their work that information is provided inside the parentheses the title(function doesn' need any additional informationso its parentheses are empty title(displays each word in titlecasewhere each word begins with capital letter this is useful because you'll often want to think of name as piece of information for exampleyou might want your program to recognize the input values adaadaand ada as the same nameand display all of them as ada several other useful methods are available for dealing with case as well for exampleyou can change string to all uppercase or all lowercase letters like thisname "ada lovelaceprint(name upper()print(name lower()this will display the followingada lovelace ada lovelace the lower(method is particularly useful for storing data many times you won' want to trust the capitalization that your users provideso you'll convert strings to lowercase before storing them then when you want to display the informationyou'll use the case that makes the most sense for each string
48
it' often useful to combine strings for exampleyou might want to store first name and last name in separate variablesand then combine them when you want to display someone' full namefirst_name "adalast_name "lovelaceu full_name first_name last_name print(full_namepython uses the plus symbol (+to combine strings in this examplewe use to create full name by combining first_namea spaceand last_name ugiving this resultada lovelace this method of combining strings is called concatenation you can use concatenation to compose complete messages using the information you've stored in variable let' look at an examplefirst_name "adalast_name "lovelacefull_name first_name last_name print("hellofull_name title("!"herethe full name is used at in sentence that greets the userand the title(method is used to format the name appropriately this code returns simple but nicely formatted greetinghelloada lovelaceyou can use concatenation to compose message and then store the entire message in variablefirst_name "adalast_name "lovelacefull_name first_name last_name message "hellofull_name title("! print(messagethis code displays the message "helloada lovelace!as wellbut storing the message in variable at makes the final print statement at much simpler variables and simple data types
49
in programmingwhitespace refers to any nonprinting charactersuch as spacestabsand end-of-line symbols you can use whitespace to organize your output so it' easier for users to read to add tab to your textuse the character combination \ as shown at uprint("python"python print("\tpython"python to add newline in stringuse the character combination \nprint("languages:\npython\nc\njavascript"languagespython javascript you can also combine tabs and newlines in single string the string "\ \ttells python to move to new lineand start the next line with tab the following example shows how you can use one-line string to generate four lines of outputprint("languages:\ \tpython\ \tc\ \tjavascript"languagespython javascript newlines and tabs will be very useful in the next two when you start to produce many lines of output from just few lines of code stripping whitespace extra whitespace can be confusing in your programs to programmers 'pythonand 'python look pretty much the same but to programthey are two different strings python detects the extra space in 'python and considers it significant unless you tell it otherwise it' important to think about whitespacebecause often you'll want to compare two strings to determine whether they are the same for exampleone important instance might involve checking people' usernames when they log in to website extra whitespace can be confusing in much simpler situations as well fortunatelypython makes it easy to eliminate extraneous whitespace from data that people enter python can look for extra whitespace on the right and left sides of string to ensure that no whitespace exists at the right end of stringuse the rstrip(method
50
favorite_language 'python favorite_language rstrip('pythonx favorite_language 'python the value stored in favorite_language at contains extra whitespace at the end of the string when you ask python for this value in terminal sessionyou can see the space at the end of the value when the rstrip(method acts on the variable favorite_language at wthis extra space is removed howeverit is only removed temporarily if you ask for the value of favorite_language againyou can see that the string looks the same as when it was enteredincluding the extra whitespace to remove the whitespace from the string permanentlyyou have to store the stripped value back into the variablefavorite_language 'python favorite_language favorite_language rstrip(favorite_language 'pythonto remove the whitespace from the stringyou strip the whitespace from the right side of the string and then store that value back in the original variableas shown at changing variable' value and then storing the new value back in the original variable is done often in programming this is how variable' value can change as program is executed or in response to user input you can also strip whitespace from the left side of string using the lstrip(method or strip whitespace from both sides at once using strip() favorite_language python favorite_language rstrip(pythonw favorite_language lstrip('python favorite_language strip('pythonin this examplewe start with value that has whitespace at the beginning and the end we then remove the extra space from the right side at vfrom the left side at wand from both sides at experimenting with these stripping functions can help you become familiar with manipulating strings in the real worldthese stripping functions are used most often to clean up user input before it' stored in program variables and simple data types
51
one kind of error that you might see with some regularity is syntax error syntax error occurs when python doesn' recognize section of your program as valid python code for exampleif you use an apostrophe within single quotesyou'll produce an error this happens because python interprets everything between the first single quote and the apostrophe as string it then tries to interpret the rest of the text as python codewhich causes errors here' how to use single and double quotes correctly save this program as apostrophe py and then run itapostrophe py message "one of python' strengths is its diverse community print(messagethe apostrophe appears inside set of double quotesso the python interpreter has no trouble reading the string correctlyone of python' strengths is its diverse community howeverif you use single quotespython can' identify where the string should endmessage 'one of python' strengths is its diverse community print(messageyou'll see the following outputfile "apostrophe py"line message 'one of python' strengths is its diverse community ^ syntaxerrorinvalid syntax in the output you can see that the error occurs at right after the second single quote this syntax error indicates that the interpreter doesn' recognize something in the code as valid python code errors can come from variety of sourcesand 'll point out some common ones as they arise you might see syntax errors often as you learn to write proper python code syntax errors are also the least specific kind of errorso they can be difficult and frustrating to identify and correct if you get stuck on particularly stubborn errorsee the suggestions in appendix note your editor' syntax highlighting feature should help you spot some syntax errors quickly as you write your programs if you see python code highlighted as if it' english or english highlighted as if it' python codeyou probably have mismatched quotation mark somewhere in your file
52
the print statement has slightly different syntax in python python print "hello python world!hello python worldparentheses are not needed around the phrase you want to print in python technicallyprint is function in python which is why it needs parentheses some python print statements do include parenthesesbut the behavior can be little different than what you'll see in python basicallywhen you're looking at code written in python expect to see some print statements with parentheses and some without try it yourse lf save each of the following exercises as separate file with name like name_cases py if you get stucktake break or see the suggestions in appendix - personal messagestore person' name in variableand print message to that person your message should be simplesuch as"hello ericwould you like to learn some python today? - name casesstore person' name in variableand then print that person' name in lowercaseuppercaseand titlecase - famous quotefind quote from famous person you admire print the quote and the name of its author your output should look something like the followingincluding the quotation marksalbert einstein once said" person who never made mistake never tried anything new - famous quote repeat exercise - but this time store the famous person' name in variable called famous_person then compose your message and store it in new variable called message print your message - stripping namesstore person' nameand include some whitespace characters at the beginning and end of the name make sure you use each character combination"\tand "\ "at least once print the name onceso the whitespace around the name is displayed then print the name using each of the three stripping functionslstrip()rstrip()and strip(variables and simple data types
53
numbers are used quite often in programming to keep score in gamesrepresent data in visualizationsstore information in web applicationsand so on python treats numbers in several different waysdepending on how they are being used let' first look at how python manages integersbecause they are the simplest to work with integers you can add (+)subtract (-)multiply (*)and divide (/integers in python in terminal sessionpython simply returns the result of the operation python uses two multiplication symbols to represent exponents * * * python supports the order of operations tooso you can use multiple operations in one expression you can also use parentheses to modify the order of operations so python can evaluate your expression in the order you specify for example * ( the spacing in these examples has no effect on how python evaluates the expressionsit simply helps you more quickly spot the operations that have priority when you're reading through the code floats python calls any number with decimal point float this term is used in most programming languagesand it refers to the fact that decimal point can appear at any position in number every programming language must
54
behave appropriately no matter where the decimal point appears for the most partyou can use decimals without worrying about how they behave simply enter the numbers you want to useand python will most likely do what you expect but be aware that you can sometimes get an arbitrary number of decimal places in your answer this happens in all languages and is of little concern python tries to find way to represent the result as precisely as possiblewhich is sometimes difficult given how computers have to represent numbers internally just ignore the extra decimal places for nowyou'll learn ways to deal with the extra places when you need to in the projects in part ii avoiding type errors with the str(function oftenyou'll want to use variable' value within message for examplesay you want to wish someone happy birthday you might write code like thisbirthday py age message "happy age "rd birthday!print(messageyou might expect this code to print the simple birthday greetinghappy rd birthdaybut if you run this codeyou'll see that it generates an errortraceback (most recent call last)file "birthday py"line in message "happy age "rd birthday! typeerrorcan' convert 'intobject to str implicitly this is type error it means python can' recognize the kind of information you're using in this example python sees at that you're using variable that has an integer value (int)but it' not sure how to interpret that variables and simple data types
55
value or the characters and when you use integers within strings like thisyou need to specify explicitly that you want python to use the integer as string of characters you can do this by wrapping the variable in the str(functionwhich tells python to represent non-string values as stringsage message "happy str(age"rd birthday!print(messagepython now knows that you want to convert the numerical value to string and display the characters and as part of the birthday message now you get the message you were expectingwithout any errorshappy rd birthdayworking with numbers in python is straightforward most of the time if you're getting unexpected resultscheck whether python is interpreting your numbers the way you want it toeither as numerical value or as string value integers in python python returns slightly different result when you divide two integerspython instead of python returns division of integers in python results in an integer with the remainder truncated note that the result is not rounded integerthe remainder is simply omitted to avoid this behavior in python make sure that at least one of the numbers is float by doing sothe result will be float as well this division behavior is common source of confusion when people who are used to python start using python or vice versa if you use or create code that mixes integers and floatswatch out for irregular behavior
56
- number eightwrite additionsubtractionmultiplicationand division operations that each result in the number be sure to enclose your operations in print statements to see the results you should create four lines that look like thisprint( your output should simply be four lines with the number appearing once on each line - favorite numberstore your favorite number in variable thenusing that variablecreate message that reveals your favorite number print that message comments comments are an extremely useful feature in most programming languages everything you've written in your programs so far is python code as your programs become longer and more complicatedyou should add notes within your programs that describe your overall approach to the problem you're solving comment allows you to write notes in english within your programs how do you write commentsin pythonthe hash mark (#indicates comment anything following hash mark in your code is ignored by the python interpreter for examplecomment py say hello to everyone print("hello python people!"python ignores the first line and executes the second line hello python peoplewhat kind of comments should you writethe main reason to write comments is to explain what your code is supposed to do and how you are making it work when you're in the middle of working on projectyou understand how all of the pieces fit together but when you return to project after some time awayyou'll likely have forgotten some of the details you can always study your code for while and figure out how segments were supposed to workbut writing good comments can save you time by summarizing your overall approach in clear english variables and simple data types
57
other programmersyou should write meaningful comments todaymost software is written collaborativelywhether by group of employees at one company or group of people working together on an open source project skilled programmers expect to see comments in codeso it' best to start adding descriptive comments to your programs now writing clearconcise comments in your code is one of the most beneficial habits you can form as new programmer when you're determining whether to write commentask yourself if you had to consider several approaches before coming up with reasonable way to make something workif sowrite comment about your solution it' much easier to delete extra comments later on than it is to go back and write comments for sparsely commented program from now oni'll use comments in examples throughout this book to help explain sections of code try it yourse lf - adding commentschoose two of the programs you've writtenand add at least one comment to each if you don' have anything specific to write because your programs are too simple at this pointjust add your name and the current date at the top of each program file then write one sentence describing what the program does the zen of python for long timethe programming language perl was the mainstay of the internet most interactive websites in the early days were powered by perl scripts the perl community' motto at the time was"there' more than one way to do it people liked this mind-set for whilebecause the flexibility written into the language made it possible to solve most problems in variety of ways this approach was acceptable while working on your own projectsbut eventually people realized that the emphasis on flexibility made it difficult to maintain large projects over long periods of time it was difficulttediousand time-consuming to review code and try to figure out what someone else was thinking when they were solving complex problem experienced python programmers will encourage you to avoid complexity and aim for simplicity whenever possible the python community' philosophy is contained in "the zen of pythonby tim peters you can access this brief set of principles for writing good python code by entering import this into your interpreter won' reproduce the entire "zen of
58
should be important to you as beginning python programmer import this the zen of pythonby tim peters beautiful is better than ugly python programmers embrace the notion that code can be beautiful and elegant in programmingpeople solve problems programmers have always respected well-designedefficientand even beautiful solutions to problems as you learn more about python and use it to write more codesomeone might look over your shoulder one day and say"wowthat' some beautiful code!simple is better than complex if you have choice between simple and complex solutionand both workuse the simple solution your code will be easier to maintainand it will be easier for you and others to build on that code later on complex is better than complicated real life is messyand sometimes simple solution to problem is unattainable in that caseuse the simplest solution that works readability counts even when your code is complexaim to make it readable when you're working on project that involves complex codingfocus on writing informative comments for that code there should be one-and preferably only one --obvious way to do it if two python programmers are asked to solve the same problemthey should come up with fairly compatible solutions this is not to say there' no room for creativity in programming on the contrarybut much of programming consists of using smallcommon approaches to simple situations within largermore creative project the nuts and bolts of your programs should make sense to other python programmers now is better than never you could spend the rest of your life learning all the intricacies of python and of programming in generalbut then you' never complete any projects don' try to write perfect codewrite code that worksand then decide whether to improve your code for that project or move on to something new variables and simple data types
59
involved topicstry to keep this philosophy of simplicity and clarity in mind experienced programmers will respect your code more and will be happy to give you feedback and collaborate with you on interesting projects try it yourse lf - zen of pythonenter import this into python terminal session and skim through the additional principles summary in this you learned to work with variables you learned to use descriptive variable names and how to resolve name errors and syntax errors when they arise you learned what strings are and how to display strings using lowercaseuppercaseand titlecase you started using whitespace to organize output neatlyand you learned to strip unneeded whitespace from different parts of string you started working with integers and floatsand you read about some unexpected behavior to watch out for when working with numerical data you also learned to write explanatory comments to make your code easier for you and others to read finallyyou read about the philosophy of keeping your code as simple as possiblewhenever possible in you'll learn to store collections of information in variables called lists you'll learn to work through listmanipulating any information in that list
60
ci li in this and the next you'll learn what lists are and how to start working with the elements in list lists allow you to store sets of information in one placewhether you have just few items or millions of items lists are one of python' most powerful features readily accessible to new programmersand they tie together many important concepts in programming what is lista list is collection of items in particular order you can make list that includes the letters of the alphabetthe digits from - or the names of all the people in your family you can put anything you want into listand
61
list usually contains more than one elementit' good idea to make the name of your list pluralsuch as lettersdigitsor names in pythonsquare brackets ([]indicate listand individual elements in the list are separated by commas here' simple example of list that contains few kinds of bicyclesbicycles py bicycles ['trek''cannondale''redline''specialized'print(bicyclesif you ask python to print listpython returns its representation of the listincluding the square brackets['trek''cannondale''redline''specialized'because this isn' the output you want your users to seelet' learn how to access the individual items in list accessing elements in list lists are ordered collectionsso you can access any element in list by telling python the positionor indexof the item desired to access an element in listwrite the name of the list followed by the index of the item enclosed in square brackets for examplelet' pull out the first bicycle in the list bicyclesbicycles ['trek''cannondale''redline''specialized' print(bicycles[ ]the syntax for this is shown at when we ask for single item from listpython returns just that element without square brackets or quotation markstrek this is the result you want your users to see--cleanneatly formatted output you can also use the string methods from on any element in list for exampleyou can format the element 'trekmore neatly by using the title(methodbicycles ['trek''cannondale''redline''specialized'print(bicycles[ title()this example produces the same output as the preceding example except 'trekis capitalized
62
python considers the first item in list to be at position not position this is true of most programming languagesand the reason has to do with how the list operations are implemented at lower level if you're receiving unexpected resultsdetermine whether you are making simple off-by-one error the second item in list has an index of using this simple counting systemyou can get any element you want from list by subtracting one from its position in the list for instanceto access the fourth item in listyou request the item at index the following asks for the bicycles at index and index bicycles ['trek''cannondale''redline''specialized'print(bicycles[ ]print(bicycles[ ]this code returns the second and fourth bicycles in the listcannondale specialized python has special syntax for accessing the last element in list by asking for the item at index - python always returns the last item in the listbicycles ['trek''cannondale''redline''specialized'print(bicycles[- ]this code returns the value 'specializedthis syntax is quite usefulbecause you'll often want to access the last items in list without knowing exactly how long the list is this convention extends to other negative index values as well the index - returns the second item from the end of the listthe index - returns the third item from the endand so forth using individual values from list you can use individual values from list just as you would any other variable for exampleyou can use concatenation to create message based on value from list let' try pulling the first bicycle from the list and composing message using that value bicycles ['trek''cannondale''redline''specialized' message "my first bicycle was bicycles[ title(print(messageintroducing lists
63
the variable message the output is simple sentence about the first bicycle in the listmy first bicycle was trek try it yourse lf try these short programs to get some firsthand experience with python' lists you might want to create new folder for each exercises to keep them organized - namesstore the names of few of your friends in list called names print each person' name by accessing each element in the listone at time - greetingsstart with the list you used in exercise - but instead of just printing each person' nameprint message to them the text of each message should be the samebut each message should be personalized with the person' name - your own listthink of your favorite mode of transportationsuch as motorcycle or carand make list that stores several examples use your list to print series of statements about these itemssuch as " would like to own honda motorcycle changingaddingand removing elements most lists you create will be dynamicmeaning you'll build list and then add and remove elements from it as your program runs its course for exampleyou might create game in which player has to shoot aliens out of the sky you could store the initial set of aliens in list and then remove an alien from the list each time one is shot down each time new alien appears on the screenyou add it to the list your list of aliens will decrease and increase in length throughout the course of the game modifying elements in list the syntax for modifying an element is similar to the syntax for accessing an element in list to change an elementuse the name of the list followed by the index of the element you want to changeand then provide the new value you want that item to have
64
the list is 'hondahow would we change the value of this first itemmotorcycles py motorcycles ['honda''yamaha''suzuki'print(motorcyclesv motorcycles[ 'ducatiprint(motorcyclesthe code at defines the original listwith 'hondaas the first element the code at changes the value of the first item to 'ducatithe output shows that the first item has indeed been changedand the rest of the list stays the same['honda''yamaha''suzuki'['ducati''yamaha''suzuki'you can change the value of any item in listnot just the first item adding elements to list you might want to add new element to list for many reasons for exampleyou might want to make new aliens appear in gameadd new data to visualizationor add new registered users to website you've built python provides several ways to add new data to existing lists appending elements to the end of list the simplest way to add new element to list is to append the item to the list when you append an item to listthe new element is added to the end of the list using the same list we had in the previous examplewe'll add the new element 'ducatito the end of the listmotorcycles ['honda''yamaha''suzuki'print(motorcyclesu motorcycles append('ducati'print(motorcyclesthe append(method at adds 'ducatito the end of the list without affecting any of the other elements in the list['honda''yamaha''suzuki'['honda''yamaha''suzuki''ducati'introducing lists
65
exampleyou can start with an empty list and then add items to the list using series of append(statements using an empty listlet' add the elements 'honda''yamaha'and 'suzukito the listmotorcycles [motorcycles append('honda'motorcycles append('yamaha'motorcycles append('suzuki'print(motorcyclesthe resulting list looks exactly the same as the lists in the previous examples['honda''yamaha''suzuki'building lists this way is very commonbecause you often won' know the data your users want to store in program until after the program is running to put your users in controlstart by defining an empty list that will hold the usersvalues then append each new value provided to the list you just created inserting elements into list you can add new element at any position in your list by using the insert(method you do this by specifying the index of the new element and the value of the new item motorcycles ['honda''yamaha''suzuki' motorcycles insert( 'ducati'print(motorcyclesin this examplethe code at inserts the value 'ducatiat the beginning of the list the insert(method opens space at position and stores the value 'ducatiat that location this operation shifts every other value in the list one position to the right['ducati''honda''yamaha''suzuki'removing elements from list oftenyou'll want to remove an item or set of items from list for examplewhen player shoots down an alien from the skyyou'll most likely want to remove it from the list of active aliens or when user
66
want to remove that user from the list of active users you can remove an item according to its position in the list or according to its value removing an item using the del statement if you know the position of the item you want to remove from listyou can use the del statement motorcycles ['honda''yamaha''suzuki'print(motorcyclesu del motorcycles[ print(motorcyclesthe code at uses del to remove the first item'honda'from the list of motorcycles['honda''yamaha''suzuki'['yamaha''suzuki'you can remove an item from any position in list using the del statement if you know its index for examplehere' how to remove the second item'yamaha'in the listmotorcycles ['honda''yamaha''suzuki'print(motorcyclesdel motorcycles[ print(motorcyclesthe second motorcycle is deleted from the list['honda''yamaha''suzuki'['honda''suzuki'in both examplesyou can no longer access the value that was removed from the list after the del statement is used removing an item using the pop(method sometimes you'll want to use the value of an item after you remove it from list for exampleyou might want to get the and position of an alien that was just shot downso you can draw an explosion at that position in web applicationyou might want to remove user from list of active members and then add that user to list of inactive members the pop(method removes the last item in listbut it lets you work with that item after removing it the term pop comes from thinking of list as stack of items and popping one item off the top of the stack in this analogythe top of stack corresponds to the end of list introducing lists
67
motorcycles ['honda''yamaha''suzuki'print(motorcyclesv popped_motorcycle motorcycles pop( print(motorcyclesx print(popped_motorcyclewe start by defining and printing the list motorcycles at at we pop value from the list and store that value in the variable popped_motorcycle we print the list at to show that value has been removed from the list then we print the popped value at to prove that we still have access to the value that was removed the output shows that the value 'suzukiwas removed from the end of the list and is now stored in the variable popped_motorcycle['honda''yamaha''suzuki'['honda''yamaha'suzuki how might this pop(method be usefulimagine that the motorcycles in the list are stored in chronological order according to when we owned them if this is the casewe can use the pop(method to print statement about the last motorcycle we boughtmotorcycles ['honda''yamaha''suzuki'last_owned motorcycles pop(print("the last motorcycle owned was last_owned title("the output is simple sentence about the most recent motorcycle we ownedthe last motorcycle owned was suzuki popping items from any position in list you can actually use pop(to remove an item in list at any position by including the index of the item you want to remove in parentheses motorcycles ['honda''yamaha''suzuki' first_owned motorcycles pop( print('the first motorcycle owned was first_owned title('
68
print message about that motorcycle at the output is simple sentence describing the first motorcycle ever ownedthe first motorcycle owned was honda remember that each time you use pop()the item you work with is no longer stored in the list if you're unsure whether to use the del statement or the pop(methodhere' simple way to decidewhen you want to delete an item from list and not use that item in any wayuse the del statementif you want to use an item as you remove ituse the pop(method removing an item by value sometimes you won' know the position of the value you want to remove from list if you only know the value of the item you want to removeyou can use the remove(method for examplelet' say we want to remove the value 'ducatifrom the list of motorcycles motorcycles ['honda''yamaha''suzuki''ducati'print(motorcyclesu motorcycles remove('ducati'print(motorcyclesthe code at tells python to figure out where 'ducatiappears in the list and remove that element['honda''yamaha''suzuki''ducati'['honda''yamaha''suzuki'you can also use the remove(method to work with value that' being removed from list let' remove the value 'ducatiand print reason for removing it from the listu motorcycles ['honda''yamaha''suzuki''ducati'print(motorcyclesv too_expensive 'ducatiw motorcycles remove(too_expensiveprint(motorcyclesx print("\na too_expensive title(is too expensive for me "after defining the list at uwe store the value 'ducatiin variable called too_expensive we then use this variable to tell python which value introducing lists
69
the list but is still stored in the variable too_expensiveallowing us to print statement about why we removed 'ducatifrom the list of motorcycles['honda''yamaha''suzuki''ducati'['honda''yamaha''suzuki' ducati is too expensive for me note the remove(method deletes only the first occurrence of the value you specify if there' possibility the value appears more than once in the listyou'll need to use loop to determine if all occurrences of the value have been removed you'll learn how to do this in try it yourse lf the following exercises are bit more complex than those in but they give you an opportunity to use lists in all of the ways described - guest listif you could invite anyoneliving or deceasedto dinnerwho would you invitemake list that includes at least three people you' like to invite to dinner then use your list to print message to each personinviting them to dinner - changing guest listyou just heard that one of your guests can' make the dinnerso you need to send out new set of invitations you'll have to think of someone else to invite start with your program from exercise - add print statement at the end of your program stating the name of the guest who can' make it modify your listreplacing the name of the guest who can' make it with the name of the new person you are inviting print second set of invitation messagesone for each person who is still in your list - more guestsyou just found bigger dinner tableso now more space is available think of three more guests to invite to dinner start with your program from exercise - or exercise - add print statement to the end of your program informing people that you found bigger dinner table use insert(to add one new guest to the beginning of your list use insert(to add one new guest to the middle of your list use append(to add one new guest to the end of your list print new set of invitation messagesone for each person in your list
70
arrive in time for the dinnerand you have space for only two guests start with your program from exercise - add new line that prints message saying that you can invite only two people for dinner use pop(to remove guests from your list one at time until only two names remain in your list each time you pop name from your listprint message to that person letting them know you're sorry you can' invite them to dinner print message to each of the two people still on your listletting them know they're still invited use del to remove the last two names from your listso you have an empty list print your list to make sure you actually have an empty list at the end of your program organizing list oftenyour lists will be created in an unpredictable orderbecause you can' always control the order in which your users provide their data although this is unavoidable in most circumstancesyou'll frequently want to present your information in particular order sometimes you'll want to preserve the original order of your listand other times you'll want to change the original order python provides number of different ways to organize your listsdepending on the situation sorting list permanently with the sort(method python' sort(method makes it relatively easy to sort list imagine we have list of cars and want to change the order of the list to store them alphabetically to keep the task simplelet' assume that all the values in the list are lowercase cars py cars ['bmw''audi''toyota''subaru' cars sort(print(carsthe sort(methodshown at uchanges the order of the list permanently the cars are now in alphabetical orderand we can never revert to the original order['audi''bmw''subaru''toyota'introducing lists
71
argument reverse=true to the sort(method the following example sorts the list of cars in reverse alphabetical ordercars ['bmw''audi''toyota''subaru'cars sort(reverse=trueprint(carsagainthe order of the list is permanently changed['toyota''subaru''bmw''audi'sorting list temporarily with the sorted(function to maintain the original order of list but present it in sorted orderyou can use the sorted(function the sorted(function lets you display your list in particular order but doesn' affect the actual order of the list let' try this function on the list of cars cars ['bmw''audi''toyota''subaru' print("here is the original list:"print(carsv print("\nhere is the sorted list:"print(sorted(cars) print("\nhere is the original list again:"print(carswe first print the list in its original order at and then in alphabetical order at after the list is displayed in the new orderwe show that the list is still stored in its original order at here is the original list['bmw''audi''toyota''subaru'here is the sorted list['audi''bmw''subaru''toyota' here is the original list again['bmw''audi''toyota''subaru'notice that the list still exists in its original order at after the sorted(function has been used the sorted(function can also accept reverse=true argument if you want to display list in reverse alphabetical order
72
sorting list alphabetically is bit more complicated when all the values are not in lowercase there are several ways to interpret capital letters when you're deciding on sort orderand specifying the exact order can be more complex than we want to deal with at this time howevermost approaches to sorting will build directly on what you learned in this section printing list in reverse order to reverse the original order of listyou can use the reverse(method if we originally stored the list of cars in chronological order according to when we owned themwe could easily rearrange the list into reverse chronological ordercars ['bmw''audi''toyota''subaru'print(carscars reverse(print(carsnotice that reverse(doesn' sort backward alphabeticallyit simply reverses the order of the list['bmw''audi''toyota''subaru'['subaru''toyota''audi''bmw'the reverse(method changes the order of list permanentlybut you can revert to the original order anytime by applying reverse(to the same list second time finding the length of list you can quickly find the length of list by using the len(function the list in this example has four itemsso its length is cars ['bmw''audi''toyota''subaru'len(cars you'll find len(useful when you need to identify the number of aliens that still need to be shot down in gamedetermine the amount of data you have to manage in visualizationor figure out the number of registered users on websiteamong other tasks note python counts the items in list starting with oneso you shouldn' run into any offby-one errors when determining the length of list introducing lists
73
- seeing the worldthink of at least five places in the world you' like to visit store the locations in list make sure the list is not in alphabetical order print your list in its original order don' worry about printing the list neatlyjust print it as raw python list use sorted(to print your list in alphabetical order without modifying the actual list show that your list is still in its original order by printing it use sorted(to print your list in reverse alphabetical order without changing the order of the original list show that your list is still in its original order by printing it again use reverse(to change the order of your list print the list to show that its order has changed use reverse(to change the order of your list again print the list to show it' back to its original order use sort(to change your list so it' stored in alphabetical order print the list to show that its order has been changed use sort(to change your list so it' stored in reverse alphabetical order print the list to show that its order has changed - dinner guestsworking with one of the programs from exercises - through - (page )use len(to print message indicating the number of people you are inviting to dinner - every functionthink of something you could store in list for exampleyou could make list of mountainsriverscountriescitieslanguagesor anything else you' like write program that creates list containing these items and then uses each function introduced in this at least once avoiding index errors when working with lists one type of error is common to see when you're working with lists for the first time let' say you have list with three itemsand you ask for the fourth itemmotorcycles ['honda''yamaha''suzuki'print(motorcycles[ ]
74
traceback (most recent call last)file "motorcycles py"line in print(motorcycles[ ]indexerrorlist index out of range python attempts to give you the item at index but when it searches the listno item in motorcycles has an index of because of the off-by-one nature of indexing in liststhis error is typical people think the third item is item number because they start counting at but in python the third item is number because it starts indexing at an index error means python can' figure out the index you requested if an index error occurs in your programtry adjusting the index you're asking for by one then run the program again to see if the results are correct keep in mind that whenever you want to access the last item in list you use the index - this will always workeven if your list has changed size since the last time you accessed itmotorcycles ['honda''yamaha''suzuki'print(motorcycles[- ]the index - always returns the last item in listin this case the value 'suzuki''suzukithe only time this approach will cause an error is when you request the last item from an empty listmotorcycles [print(motorcycles[- ]no items are in motorcyclesso python returns another index errortraceback (most recent call last)file "motorcyles py"line in print(motorcycles[- ]indexerrorlist index out of range note if an index error occurs and you can' figure out how to resolve ittry printing your list or just printing the length of your list your list might look much different than you thought it didespecially if it has been managed dynamically by your program seeing the actual listor the exact number of items in your listcan help you sort out such logical errors introducing lists
75
- intentional errorif you haven' received an index error in one of your programs yettry to make one happen change an index in one of your programs to produce an index error make sure you correct the error before closing the program summary in this you learned what lists are and how to work with the individual items in list you learned how to define list and how to add and remove elements you learned to sort lists permanently and temporarily for display purposes you also learned how to find the length of list and how to avoid index errors when you're working with lists in you'll learn how to work with items in list more efficiently by looping through each item in list using just few lines of code you'll be able to work efficientlyeven when your list contains thousands or millions of items
76
li in you learned how to make simple listand you learned to work with the individual elements in list in this you'll learn how to loop through an entire list using just few lines of code regardless of how long the list is looping allows you to take the same actionor set of actionswith every item in list as resultyou'll be able to work efficiently with lists of any lengthincluding those with thousands or even millions of items looping through an entire list you'll often want to run through all entries in listperforming the same task with each item for examplein game you might want to move every element on the screen by the same amountor in list of numbers you might want to perform the same statistical operation on every element or perhaps you'll want to display each headline from list of articles on website when you want to do the same action with every item in listyou can use python' for loop
77
each name in the list we could do this by retrieving each name from the list individuallybut this approach could cause several problems for oneit would be repetitive to do this with long list of names alsowe' have to change our code each time the list' length changed for loop avoids both of these issues by letting python manage these issues internally let' use for loop to print out each name in list of magiciansmagicians py magicians ['alice''david''carolina' for magician in magiciansw print(magicianwe begin by defining list at ujust as we did in at vwe define for loop this line tells python to pull name from the list magiciansand store it in the variable magician at we tell python to print the name that was just stored in magician python then repeats lines and wonce for each name in the list it might help to read this code as "for every magician in the list of magiciansprint the magician' name the output is simple printout of each name in the listalice david carolina closer look at looping the concept of looping is important because it' one of the most common ways computer automates repetitive tasks for examplein simple loop like we used in magicians pypython initially reads the first line of the loopfor magician in magiciansthis line tells python to retrieve the first value from the list magicians and store it in the variable magician this first value is 'alicepython then reads the next lineprint(magicianpython prints the current value of magicianwhich is still 'alicebecause the list contains more valuespython returns to the first line of the loopfor magician in magicianspython retrieves the next name in the list'david'and stores that value in magician python then executes the lineprint(magician
78
python repeats the entire loop once more with the last value in the list'carolinabecause no more values are in the listpython moves on to the next line in the program in this case nothing comes after the for loopso the program simply ends when you're using loops for the first timekeep in mind that the set of steps is repeated once for each item in the listno matter how many items are in the list if you have million items in your listpython repeats these steps million times--and usually very quickly also keep in mind when writing your own for loops that you can choose any name you want for the temporary variable that holds each value in the list howeverit' helpful to choose meaningful name that represents single item from the list for examplehere' good way to start for loop for list of catsa list of dogsand general list of itemsfor cat in catsfor dog in dogsfor item in list_of_itemsthese naming conventions can help you follow the action being done on each item within for loop using singular and plural names can help you identify whether section of code is working with single element from the list or the entire list doing more work within for loop you can do just about anything with each item in for loop let' build on the previous example by printing message to each magiciantelling them that they performed great trickmagicians ['alice''david''carolina'for magician in magiciansu print(magician title("that was great trick!"the only difference in this code is at where we compose message to each magicianstarting with that magician' name the first time through the loop the value of magician is 'alice'so python starts the first message with the name 'alicethe second time through the message will begin with 'david'and the third time through the message will begin with 'carolinathe output shows personalized message for each magician in the listalicethat was great trickdavidthat was great trickcarolinathat was great trickyou can also write as many lines of code as you like in the for loop every indented line following the line for magician in magicians is considered inside the loopand each indented line is executed once for each working with lists
79
each value in the list let' add second line to our messagetelling each magician that we're looking forward to their next trickmagicians ['alice''david''carolina'for magician in magiciansprint(magician title("that was great trick!" print(" can' wait to see your next trickmagician title(\ "because we have indented both print statementseach line will be executed once for every magician in the list the newline ("\ "in the second print statement inserts blank line after each pass through the loop this creates set of messages that are neatly grouped for each person in the listalicethat was great tricki can' wait to see your next trickalice davidthat was great tricki can' wait to see your next trickdavid carolinathat was great tricki can' wait to see your next trickcarolina you can use as many lines as you like in your for loops in practice you'll often find it useful to do number of different operations with each item in list when you use for loop doing something after for loop what happens once for loop has finished executingusuallyyou'll want to summarize block of output or move on to other work that your program must accomplish any lines of code after the for loop that are not indented are executed once without repetition let' write thank you to the group of magicians as wholethanking them for putting on an excellent show to display this group message after all of the individual messages have been printedwe place the thank you message after the for loop without indentationmagicians ['alice''david''carolina'for magician in magiciansprint(magician title("that was great trick!"print(" can' wait to see your next trickmagician title(\ " print("thank youeveryone that was great magic show!"
80
the listas you saw earlier howeverbecause the line at is not indentedit' printed only oncealicethat was great tricki can' wait to see your next trickalice davidthat was great tricki can' wait to see your next trickdavid carolinathat was great tricki can' wait to see your next trickcarolina thank youeveryone that was great magic showwhen you're processing data using for loopyou'll find that this is good way to summarize an operation that was performed on an entire data set for exampleyou might use for loop to initialize game by running through list of characters and displaying each character on the screen you might then write an unindented block after this loop that displays play now button after all the characters have been drawn to the screen avoiding indentation errors python uses indentation to determine when one line of code is connected to the line above it in the previous examplesthe lines that printed messages to individual magicians were part of the for loop because they were indented python' use of indentation makes code very easy to read basicallyit uses whitespace to force you to write neatly formatted code with clear visual structure in longer python programsyou'll notice blocks of code indented at few different levels these indentation levels help you gain general sense of the overall program' organization as you begin to write code that relies on proper indentationyou'll need to watch for few common indentation errors for examplepeople sometimes indent blocks of code that don' need to be indented or forget to indent blocks that need to be indented seeing examples of these errors now will help you avoid them in the future and correct them when they do appear in your own programs let' examine some of the more common indentation errors forgetting to indent always indent the line after the for statement in loop if you forgetpython will remind youmagicians py magicians ['alice''david''carolina'for magician in magiciansu print(magicianworking with lists
81
expects an indented block and doesn' find oneit lets you know which line it had problem with file "magicians py"line print(magicianindentationerrorexpected an indented block you can usually resolve this kind of indentation error by indenting the line or lines immediately after the for statement forgetting to indent additional lines sometimes your loop will run without any errors but won' produce the expected result this can happen when you're trying to do several tasks in loop and you forget to indent some of its lines for examplethis is what happens when we forget to indent the second line in the loop that tells each magician we're looking forward to their next trickmagicians ['alice''david''carolina'for magician in magiciansprint(magician title("that was great trick!" print(" can' wait to see your next trickmagician title(\ "the print statement at is supposed to be indentedbut because python finds at least one indented line after the for statementit doesn' report an error as resultthe first print statement is executed once for each name in the list because it is indented the second print statement is not indentedso it is executed only once after the loop has finished running because the final value of magician is 'carolina'she is the only one who receives the "looking forward to the next trickmessagealicethat was great trickdavidthat was great trickcarolinathat was great tricki can' wait to see your next trickcarolina this is logical error the syntax is valid python codebut the code does not produce the desired result because problem occurs in its logic if you expect to see certain action repeated once for each item in list and it' executed only oncedetermine whether you need to simply indent line or group of lines
82
if you accidentally indent line that doesn' need to be indentedpython informs you about the unexpected indenthello_world py message "hello python world!print(messagewe don' need to indent the print statement at ubecause it doesn' belong to the line above ithencepython reports that errorfile "hello_world py"line print(messageindentationerrorunexpected indent you can avoid unexpected indentation errors by indenting only when you have specific reason to do so in the programs you're writing at this pointthe only lines you should indent are the actions you want to repeat for each item in for loop indenting unnecessarily after the loop if you accidentally indent code that should run after loop has finishedthat code will be repeated once for each item in the list sometimes this prompts python to report an errorbut often you'll receive simple logical error for examplelet' see what happens when we accidentally indent the line that thanked the magicians as group for putting on good showmagicians ['alice''david''carolina'for magician in magiciansprint(magician title("that was great trick!"print(" can' wait to see your next trickmagician title(\ " print("thank you everyonethat was great magic show!"because the line at is indentedit' printed once for each person in the listas you can see at valicethat was great tricki can' wait to see your next trickalice thank you everyonethat was great magic showdavidthat was great tricki can' wait to see your next trickdavid thank you everyonethat was great magic showcarolinathat was great tricki can' wait to see your next trickcarolina thank you everyonethat was great magic showworking with lists
83
additional lineson page because python doesn' know what you're trying to accomplish with your codeit will run all code that is written in valid syntax if an action is repeated many times when it should be executed only oncedetermine whether you just need to unindent the code for that action forgetting the colon the colon at the end of for statement tells python to interpret the next line as the start of loop magicians ['alice''david''carolina' for magician in magicians print(magicianif you accidentally forget the colonas shown at uyou'll get syntax error because python doesn' know what you're trying to do although this is an easy error to fixit' not always an easy error to find you' be surprised by the amount of time programmers spend hunting down singlecharacter errors like this such errors are difficult to find because we often just see what we expect to see try it yourse lf - pizzasthink of at least three kinds of your favorite pizza store these pizza names in listand then use for loop to print the name of each pizza modify your for loop to print sentence using the name of the pizza instead of printing just the name of the pizza for each pizza you should have one line of output containing simple statement like like pepperoni pizza add line at the end of your programoutside the for loopthat states how much you like pizza the output should consist of three or more lines about the kinds of pizza you like and then an additional sentencesuch as really love pizza - animalsthink of at least three different animals that have common characteristic store the names of these animals in listand then use for loop to print out the name of each animal modify your program to print statement about each animalsuch as dog would make great pet add line at the end of your program stating what these animals have in common you could print sentence such as any of these animals would make great pet
84
many reasons exist to store set of numbers for exampleyou'll need to keep track of the positions of each character in gameand you might want to keep track of player' high scores as well in data visualizationsyou'll almost always work with sets of numberssuch as temperaturesdistancespopulation sizesor latitude and longitude valuesamong other types of numerical sets lists are ideal for storing sets of numbersand python provides number of tools to help you work efficiently with lists of numbers once you understand how to use these tools effectivelyyour code will work well even when your lists contain millions of items using the range(function python' range(function makes it easy to generate series of numbers for exampleyou can use the range(function to print series of numbers like thisnumbers py for value in range( , )print(valuealthough this code looks like it should print the numbers from to it doesn' print the number in this examplerange(prints only the numbers through this is another result of the off-by-one behavior you'll see often in programming languages the range(function causes python to start counting at the first value you give itand it stops when it reaches the second value you provide because it stops at that second valuethe output never contains the end valuewhich would have been in this case to print the numbers from to you would use range( , )for value in range( , )print(valuethis time the output starts at and ends at working with lists
85
range()try adjusting your end value by using range(to make list of numbers if you want to make list of numbersyou can convert the results of range(directly into list using the list(function when you wrap list(around call to the range(functionthe output will be list of numbers in the example in the previous sectionwe simply printed out series of numbers we can use list(to convert that same set of numbers into listnumbers list(range( , )print(numbersand this is the result[ we can also use the range(function to tell python to skip numbers in given range for examplehere' how we would list the even numbers between and even_numbers py even_numbers list(range( , , )print(even_numbersin this examplethe range(function starts with the value and then adds to that value it adds repeatedly until it reaches or passes the end value and produces this result[ you can create almost any set of numbers you want to using the range(function for exampleconsider how you might make list of the first square numbers (that isthe square of each integer from through in pythontwo asterisks (**represent exponents here' how you might put the first square numbers into listsquares py squares [ for value in range( , ) square value** squares append(squarey print(squareswe start with an empty list called squares at at vwe tell python to loop through each value from to using the range(function inside the loopthe current value is raised to the second power and stored in the
86
squares finallywhen the loop has finished runningthe list of squares is printed at [ to write this code more conciselyomit the temporary variable square and append each new value directly to the listsquares [for value in range( , ) squares append(value** print(squaresthe code at does the same work as the lines at and in squares py each value in the loop is raised to the second power and then immediately appended to the list of squares you can use either of these two approaches when you're making more complex lists sometimes using temporary variable makes your code easier to readother times it makes the code unnecessarily long focus first on writing code that you understand clearlywhich does what you want it to do then look for more efficient approaches as you review your code simple statistics with list of numbers few python functions are specific to lists of numbers for exampleyou can easily find the minimummaximumand sum of list of numbersdigits [ min(digits max(digits sum(digits note the examples in this section use short lists of numbers in order to fit easily on the page they would work just as well if your list contained million or more numbers list comprehensions the approach described earlier for generating the list squares consisted of using three or four lines of code list comprehension allows you to generate this same list in just one line of code list comprehension combines the for loop and the creation of new elements into one lineand automatically appends each new element list comprehensions are not always presented to beginnersbut have included them here because you'll most likely see them as soon as you start looking at other people' code working with lists
87
earlier but uses list comprehensionsquares py squares [value** for value in range( , )print(squaresto use this syntaxbegin with descriptive name for the listsuch as squares nextopen set of square brackets and define the expression for the values you want to store in the new list in this example the expression is value** which raises the value to the second power thenwrite for loop to generate the numbers you want to feed into the expressionand close the square brackets the for loop in this example is for value in range( , )which feeds the values through into the expression value** notice that no colon is used at the end of the for statement the result is the same list of square numbers you saw earlier[ it takes practice to write your own list comprehensionsbut you'll find them worthwhile once you become comfortable creating ordinary lists when you're writing three or four lines of code to generate lists and it begins to feel repetitiveconsider writing your own list comprehensions try it yourse lf - counting to twentyuse for loop to print the numbers from to inclusive - one millionmake list of the numbers from one to one millionand then use for loop to print the numbers (if the output is taking too longstop it by pressing ctrl- or by closing the output window - summing millionmake list of the numbers from one to one millionand then use min(and max(to make sure your list actually starts at one and ends at one million alsouse the sum(function to see how quickly python can add million numbers - odd numbersuse the third argument of the range(function to make list of the odd numbers from to use for loop to print each number - threesmake list of the multiples of from to use for loop to print the numbers in your list - cubesa number raised to the third power is called cube for examplethe cube of is written as ** in python make list of the first cubes (that isthe cube of each integer from through )and use for loop to print out the value of each cube - cube comprehensionuse list comprehension to generate list of the first cubes
88
in you learned how to access single elements in listand in this you've been learning how to work through all the elements in list you can also work with specific group of items in listwhich python calls slice slicing list to make sliceyou specify the index of the first and last elements you want to work with as with the range(functionpython stops one item before the second index you specify to output the first three elements in listyou would request indices through which would return elements and the following example involves list of players on teamplayers py players ['charles''martina''michael''florence''eli' print(players[ : ]the code at prints slice of this listwhich includes just the first three players the output retains the structure of the list and includes the first three players in the list['charles''martina''michael'you can generate any subset of list for exampleif you want the secondthirdand fourth items in listyou would start the slice at index and end at index players ['charles''martina''michael''florence''eli'print(players[ : ]this time the slice starts with 'martinaand ends with 'florence'['martina''michael''florence'if you omit the first index in slicepython automatically starts your slice at the beginning of the listplayers ['charles''martina''michael''florence''eli'print(players[: ]without starting indexpython starts at the beginning of the list['charles''martina''michael''florence'working with lists
89
for exampleif you want all items from the third item through the last itemyou can start with index and omit the second indexplayers ['charles''martina''michael''florence''eli'print(players[ :]python returns all items from the third item through the end of the list['michael''florence''eli'this syntax allows you to output all of the elements from any point in your list to the end regardless of the length of the list recall that negative index returns an element certain distance from the end of listthereforeyou can output any slice from the end of list for exampleif we want to output the last three players on the rosterwe can use the slice players[- :]players ['charles''martina''michael''florence''eli'print(players[- :]this prints the names of the last three players and would continue to work as the list of players changes in size looping through slice you can use slice in for loop if you want to loop through subset of the elements in list in the next example we loop through the first three players and print their names as part of simple rosterplayers ['charles''martina''michael''florence''eli'print("here are the first three players on my team:" for player in players[: ]print(player title()instead of looping through the entire list of players at upython loops through only the first three nameshere are the first three players on my teamcharles martina michael slices are very useful in number of situations for instancewhen you're creating gameyou could add player' final score to list every time that player finishes playing you could then get player' top three scores by sorting the list in decreasing order and taking slice that includes just the first three scores when you're working with datayou can use slices to process
90
an appropriate amount of information on each page copying list oftenyou'll want to start with an existing list and make an entirely new list based on the first one let' explore how copying list works and examine one situation in which copying list is useful to copy listyou can make slice that includes the entire original list by omitting the first index and the second index ([:]this tells python to make slice that starts at the first item and ends with the last itemproducing copy of the entire list for exampleimagine we have list of our favorite foods and want to make separate list of foods that friend likes this friend likes everything in our list so farso we can create their list by copying oursfoods py my_foods ['pizza''falafel''carrot cake' friend_foods my_foods[:print("my favorite foods are:"print(my_foodsprint("\nmy friend' favorite foods are:"print(friend_foodsat we make list of the foods we like called my_foods at we make new list called friend_foods we make copy of my_foods by asking for slice of my_foods without specifying any indices and store the copy in friend_foods when we print each listwe see that they both contain the same foodsmy favorite foods are['pizza''falafel''carrot cake'my friend' favorite foods are['pizza''falafel''carrot cake'to prove that we actually have two separate listswe'll add new food to each list and show that each list keeps track of the appropriate person' favorite foodsmy_foods ['pizza''falafel''carrot cake' friend_foods my_foods[: my_foods append('cannoli' friend_foods append('ice cream'print("my favorite foods are:"print(my_foodsworking with lists
91
print(friend_foodsat we copy the original items in my_foods to the new list friend_foodsas we did in the previous example nextwe add new food to each listat we add 'cannolito my_foodsand at we add 'ice creamto friend_foods we then print the two lists to see whether each of these foods is in the appropriate list my favorite foods arex ['pizza''falafel''carrot cake''cannoli'my friend' favorite foods arey ['pizza''falafel''carrot cake''ice cream'the output at shows that 'cannolinow appears in our list of favorite foods but 'ice creamdoesn' at we can see that 'ice creamnow appears in our friend' list but 'cannolidoesn' if we had simply set friend_foods equal to my_foodswe would not produce two separate lists for examplehere' what happens when you try to copy list without using slicemy_foods ['pizza''falafel''carrot cake'this doesn' worku friend_foods my_foods my_foods append('cannoli'friend_foods append('ice cream'print("my favorite foods are:"print(my_foodsprint("\nmy friend' favorite foods are:"print(friend_foodsinstead of storing copy of my_foods in friend_foods at uwe set friend_foods equal to my_foods this syntax actually tells python to connect the new variable friend_foods to the list that is already contained in my_foodsso now both variables point to the same list as resultwhen we add 'cannolito my_foodsit will also appear in friend_foods likewise 'ice creamwill appear in both listseven though it appears to be added only to friend_foods the output shows that both lists are the same nowwhich is not what we wantedmy favorite foods are['pizza''falafel''carrot cake''cannoli''ice cream'my friend' favorite foods are['pizza''falafel''carrot cake''cannoli''ice cream'
92
don' worry about the details in this example for now basicallyif you're trying to work with copy of list and you see unexpected behaviormake sure you are copying the list using sliceas we did in the first example try it yourse lf - slicesusing one of the programs you wrote in this add several lines to the end of the program that do the followingprint the messagethe first three items in the list arethen use slice to print the first three items from that program' list print the messagethree items from the middle of the list areuse slice to print three items from the middle of the list print the messagethe last three items in the list areuse slice to print the last three items in the list - my pizzasyour pizzasstart with your program from exercise - (page make copy of the list of pizzasand call it friend_pizzas thendo the followingadd new pizza to the original list add different pizza to the list friend_pizzas prove that you have two separate lists print the messagemy favorite pizzas are:and then use for loop to print the first list print the messagemy friend' favorite pizzas are:and then use for loop to print the second list make sure each new pizza is stored in the appropriate list - more loopsall versions of foods py in this section have avoided using for loops when printing to save space choose version of foods pyand write two for loops to print each list of foods tuples lists work well for storing sets of items that can change throughout the life of program the ability to modify lists is particularly important when you're working with list of users on website or list of characters in game howeversometimes you'll want to create list of items that cannot change tuples allow you to do just that python refers to values that cannot change as immutableand an immutable list is called tuple defining tuple tuple looks just like list except you use parentheses instead of square brackets once you define tupleyou can access individual elements by using each item' indexjust as you would for list working with lists
93
we can ensure that its size doesn' change by putting the dimensions into tupledimensions py dimensions ( print(dimensions[ ]print(dimensions[ ]we define the tuple dimensions at uusing parentheses instead of square brackets at we print each element in the tuple individuallyusing the same syntax we've been using to access elements in list let' see what happens if we try to change one of the items in the tuple dimensionsdimensions ( dimensions[ the code at tries to change the value of the first dimensionbut python returns type error basicallybecause we're trying to alter tuplewhich can' be done to that type of objectpython tells us we can' assign new value to an item in tupletraceback (most recent call last)file "dimensions py"line in dimensions[ typeerror'tupleobject does not support item assignment this is beneficial because we want python to raise an error when line of code tries to change the dimensions of the rectangle looping through all values in tuple you can loop over all the values in tuple using for loopjust as you did with listdimensions ( for dimension in dimensionsprint(dimensionpython returns all the elements in the tuplejust as it would for list
94
although you can' modify tupleyou can assign new value to variable that holds tuple so if we wanted to change our dimensionswe could redefine the entire tupleu dimensions ( print("original dimensions:"for dimension in dimensionsprint(dimensionv dimensions ( print("\nmodified dimensions:"for dimension in dimensionsprint(dimensionthe block at defines the original tuple and prints the initial dimensions at vwe store new tuple in the variable dimensions we then print the new dimensions at python doesn' raise any errors this timebecause overwriting variable is validoriginal dimensions modified dimensions when compared with liststuples are simple data structures use them when you want to store set of values that should not be changed throughout the life of program try it yourse lf - buffeta buffet-style restaurant offers only five basic foods think of five simple foodsand store them in tuple use for loop to print each food the restaurant offers try to modify one of the itemsand make sure that python rejects the change the restaurant changes its menureplacing two of the items with different foods add block of code that rewrites the tupleand then use for loop to print each of the items on the revised menu working with lists
95
now that you're writing longer programsideas about how to style your code are worthwhile to know take the time to make your code as easy as possible to read writing easy-to-read code helps you keep track of what your programs are doing and helps others understand your code as well python programmers have agreed on number of styling conventions to ensure that everyone' code is structured in roughly the same way once you've learned to write clean python codeyou should be able to understand the overall structure of anyone else' python codeas long as they follow the same guidelines if you're hoping to become professional programmer at some pointyou should begin following these guidelines as soon as possible to develop good habits the style guide when someone wants to make change to the python languagethey write python enhancement proposal (pepone of the oldest peps is pep which instructs python programmers on how to style their code pep is fairly lengthybut much of it relates to more complex coding structures than what you've seen so far the python style guide was written with the understanding that code is read more often than it is written you'll write your code once and then start reading it as you begin debugging when you add features to programyou'll spend more time reading your code when you share your code with other programmersthey'll read your code as well given the choice between writing code that' easier to write or code that' easier to readpython programmers will almost always encourage you to write code that' easier to read the following guidelines will help you write clear code from the start indentation pep recommends that you use four spaces per indentation level using four spaces improves readability while leaving room for multiple levels of indentation on each line in word processing documentpeople often use tabs rather than spaces to indent this works well for word processing documentsbut the python interpreter gets confused when tabs are mixed with spaces every text editor provides setting that lets you use the tab key but then converts each tab to set number of spaces you should definitely use your tab keybut also make sure your editor is set to insert spaces rather than tabs into your document mixing tabs and spaces in your file can cause problems that are very difficult to diagnose if you think you have mix of tabs and spacesyou can convert all tabs in file to spaces in most editors
96
many python programmers recommend that each line should be less than characters historicallythis guideline developed because most computers could fit only characters on single line in terminal window currentlypeople can fit much longer lines on their screensbut other reasons exist to adhere to the -character standard line length professional programmers often have several files open on the same screenand using the standard line length allows them to see entire lines in two or three files that are open side by side onscreen pep also recommends that you limit all of your comments to characters per linebecause some of the tools that generate automatic documentation for larger projects add formatting characters at the beginning of each commented line the pep guidelines for line length are not set in stoneand some teams prefer -character limit don' worry too much about line length in your code as you're learningbut be aware that people who are working collaboratively almost always follow the pep guidelines most editors allow you to set up visual cueusually vertical line on your screenthat shows you where these limits are note appendix shows you how to configure your text editor so it always inserts four spaces each time you press the tab key and shows vertical guideline to help you follow the -character limit blank lines to group parts of your program visuallyuse blank lines you should use blank lines to organize your filesbut don' do so excessively by following the examples provided in this bookyou should strike the right balance for exampleif you have five lines of code that build listand then another three lines that do something with that listit' appropriate to place blank line between the two sections howeveryou should not place three or four blank lines between the two sections blank lines won' affect how your code runsbut they will affect the readability of your code the python interpreter uses horizontal indentation to interpret the meaning of your codebut it disregards vertical spacing other style guidelines pep has many additional styling recommendationsbut most of the guidelines refer to more complex programs than what you're writing at this point as you learn more complex python structuresi'll share the relevant parts of the pep guidelines working with lists
97
- pep look through the original pep style guide at dev/peps/pep- you won' use much of it nowbut it might be interesting to skim through it - code reviewchoose three of the programs you've written in this and modify each one to comply with pep use four spaces for each indentation level set your text editor to insert four spaces every time you press tabif you haven' already done so (see appendix for instructions on how to do thisuse less than characters on each lineand set your editor to show vertical guideline at the th character position don' use blank lines excessively in your program files summary in this you learned how to work efficiently with the elements in list you learned how to work through list using for loophow python uses indentation to structure programand how to avoid some common indentation errors you learned to make simple numerical listsas well as few operations you can perform on numerical lists you learned how to slice list to work with subset of items and how to copy lists properly using slice you also learned about tupleswhich provide degree of protection to set of values that shouldn' changeand how to style your increasingly complex code to make it easy to read in you'll learn to respond appropriately to different conditions by using if statements you'll learn to string together relatively complex sets of conditional tests to respond appropriately to exactly the kind of situation or information you're looking for you'll also learn to use if statements while looping through list to take specific actions with selected elements from list
98
if tat me programming often involves examining set of conditions and deciding which action to take based on those conditions python' if statement allows you to examine the current state of program and respond appropriately to that state in this you'll learn to write conditional testswhich allow you to check any condition of interest you'll learn to write simple if statementsand you'll learn how to create more complex series of if statements to identify when the exact conditions you want are present you'll then apply this concept to listsso you'll be able to write for loop that handles most items in list one way but handles certain items with specific values in different way
99
the following short example shows how if tests let you respond to special situations correctly imagine you have list of cars and you want to print out the name of each car car names are proper namesso the names of most cars should be printed in title case howeverthe value 'bmwshould be printed in all uppercase the following code loops through list of car names and looks for the value 'bmwwhenever the value is 'bmw'it' printed in uppercase instead of title casecars py cars ['audi''bmw''subaru''toyota' for car in carsif car ='bmw'print(car upper()elseprint(car title()the loop in this example first checks if the current value of car is 'bmwu if it isthe value is printed in uppercase if the value of car is anything other than 'bmw'it' printed in title caseaudi bmw subaru toyota this example combines number of the concepts you'll learn about in this let' begin by looking at the kinds of tests you can use to examine the conditions in your program conditional tests at the heart of every if statement is an expression that can be evaluated as true or false and is called conditional test python uses the values true and false to decide whether the code in an if statement should be executed if conditional test evaluates to truepython executes the code following the if statement if the test evaluates to falsepython ignores the code following the if statement checking for equality most conditional tests compare the current value of variable to specific value of interest the simplest conditional test checks whether the value of variable is equal to the value of interestu car 'bmwv car ='bmwtrue
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
48
Edit dataset card