diff --git a/.gitignore b/.gitignore index bffb888..267fa6e 100755 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ index.pdf EPUB/index.epub *.epub *.pdf +.DS_Store diff --git a/PythonBookv2-cover.pages b/PythonBookv2-cover.pages new file mode 100755 index 0000000..d172d59 Binary files /dev/null and b/PythonBookv2-cover.pages differ diff --git a/appendixb.adoc b/appendixb.adoc index 312caed..40dc1af 100644 --- a/appendixb.adoc +++ b/appendixb.adoc @@ -8,7 +8,7 @@ Meant as an example of a longer program (159 lines) to get you thinking, it's re The general idea is you have a series of "burns" in a list, and the game (or simulator, if you will) steps through the list applying each burn. If you run out of altitude (or height) while you're going too fast, you will crash. -The tricky bit would be for you to figure out what `burnArray` would be used to safely land at a vehicle speed 1 or 2. That could be hard. +The tricky bit would be for you to figure out what `burn_array` would be used to safely land at a vehicle speed 1 or 2. That could be hard. [source] ---- @@ -35,7 +35,7 @@ def randomheight(): return (r % 15000 + 4000) -def gameHeader(): +def game_header(): s = "" s = s + "\nMars Lander - Version " + version + "\n" s = s + "This is a computer simulation of an Apollo Mars landing capsule.\n" @@ -47,7 +47,7 @@ def gameHeader(): return s -def getHeader(): +def get_header(): s = "" s = s + "\nTime\t" s = s + "Speed\t\t" @@ -63,11 +63,11 @@ def getHeader(): -def computeDeltaV(vehicle): +def compute_delta_v(vehicle): return (vehicle['Speed'] + GRAVITY - vehicle['Burn']) -def checkStatus(vehicle): +def check_status(vehicle): s = "" if (vehicle['Height'] <= 0): if (vehicle['Speed'] > 10): @@ -86,26 +86,26 @@ def checkStatus(vehicle): return s -def adjustForBurn(vehicle): - # save previousHeight +def adjust_for_burn(vehicle): + # save previous_height vehicle['PrevHeight'] = vehicle['Height'] # compute new velocity - vehicle['Speed'] = computeDeltaV(vehicle) + vehicle['Speed'] = compute_delta_v(vehicle) # compute new height of vehicle vehicle['Height'] = vehicle['Height'] - vehicle['Speed'] # subtract fuel used from tank vehicle['Fuel'] = vehicle['Fuel'] - vehicle['Burn'] -def stillFlying(): +def still_flying(): return (vehicle['Height'] > 0) -def outOfFuel(vehicle): +def out_of_fuel(vehicle): return (vehicle['Fuel'] <= 0) -def getStatus(vehicle): +def get_status(vehicle): # create a string with the vehicle status on it. s = "" s = str(vehicle['Tensec']) + "0 \t\t" + str(vehicle['Speed']) \ @@ -113,7 +113,7 @@ def getStatus(vehicle): return s -def printString(string): +def print_string(string): # print long strings with new lines the them. # a = string.split(/\r?\n/) #for (i = 0 i < a.length i++): @@ -135,7 +135,7 @@ vehicle = { # main game loop -def runGame(burns): +def run_game(burns): status = "" # Set initial vehicle parameters @@ -143,33 +143,33 @@ def runGame(burns): vehicle['Height'] = h vehicle['PrevHeight'] = h - burnIdx = 0 + burn_idx = 0 - printString(gameHeader()) - printString(getHeader()) + print_string(game_header()) + print_string(get_header()) - while (stillFlying() == True): - status = getStatus(vehicle) - vehicle['Burn'] = burns[burnIdx] - printString(status + "\t\t" + str(vehicle['Burn'])) - adjustForBurn(vehicle) - if (outOfFuel(vehicle) == True): + while (still_flying() == True): + status = get_status(vehicle) + vehicle['Burn'] = burns[burn_idx] + print_string(status + "\t\t" + str(vehicle['Burn'])) + adjust_for_burn(vehicle) + if (out_of_fuel(vehicle) == True): break vehicle['Tensec'] += 1 - burnIdx += 1 + burn_idx += 1 - status = checkStatus(vehicle) - printString(status) + status = check_status(vehicle) + print_string(status) # these are the series of burns made each 10 secs by the lander. # change them to see if you can get the lander to make a soft landing. # burns are between 0 and 200. This burn array usually crashes. -burnArray = [100, 100, 200, 200, 100, 100, 0, 0, 200, 100, 100, 0, 0, 0, 0] +burn_array = [100, 100, 200, 200, 100, 100, 0, 0, 200, 100, 100, 0, 0, 0, 0] -runGame(burnArray) +run_game(burn_array) ---- \ No newline at end of file diff --git a/appendixc.adoc b/appendixc.adoc new file mode 100644 index 0000000..2ace707 --- /dev/null +++ b/appendixc.adoc @@ -0,0 +1,92 @@ + + +[appendix] +== Virtual Environments and `-m venv` + +Throughout this book, we've mostly run small snippets in a REPL, or a single standalone file. But the moment you start writing real projects - and especially once you start installing packages other people have written - you'll run into a very common problem: different projects on the same computer often need *different versions* of the same package. Python's answer to keeping projects from tripping over each other is called a *virtual environment*. + +=== The Problem: One Shared, Global Python + +Normally, when you install a package (using a tool called `pip`, Python's package installer), it gets installed *globally* - shared by your entire computer, available to every Python program you run. That sounds convenient, until you have two different projects that each need a different version of the same package. Upgrade it for one project, and you might quietly break the other one. + +=== What Is a Virtual Environment? + +A virtual environment is a private, self-contained folder that holds its own separate copy of Python and its own separate collection of installed packages - completely walled off from your computer's main Python installation, and from every other project's virtual environment. + +Think of it like this: instead of every project reaching into one shared, communal toolbox (where someone might swap out a tool you were relying on), each project gets its *own* toolbox, set up exactly the way that project needs it. + +=== Creating One with `-m venv` + +The good news: you don't need to install anything extra to make one. Python already ships with the tool for this, called `venv`, built right in. From a terminal, inside your project's folder, run: + +[source,bash] +---- +python3 -m venv myenv +---- + +That `-m` flag tells `python3`: "don't run a file - run the built-in module named `venv` as a program instead." `myenv` is just the name you're giving this new virtual environment; you'll commonly see it named `venv` or `.venv` in real projects. + +After that command finishes, you'll notice a new folder has appeared, named `myenv`, sitting right there next to your code. + +=== Activating It + +Just creating the environment doesn't put you "inside" it yet - you have to *activate* it, and you'll need to do this again each time you open a fresh terminal window to work on that project. + +[source,bash] +---- +source myenv/bin/activate +---- + +NOTE: On Windows, the activation command looks a little different: `myenv\Scripts\activate`. + +Once it's activated, you'll usually see the environment's name show up right inside your terminal prompt, something like `(myenv) $`, letting you know, at a glance, that you're "inside" it. + +=== Installing Packages Inside It + +With the environment activated, anything you install with `pip install` gets installed *only* inside that environment - not system-wide, and not visible to any other project's environment. + +[source,bash] +---- +pip install requests +---- + +Now `requests` lives only inside `myenv`. A completely different project, with its own separate virtual environment, won't see it at all, unless you install it there too. + +=== Leaving the Environment + +When you're done working, one simple command returns you to your regular, system-wide Python. + +[source,bash] +---- +deactivate +---- + +=== Sharing a Project Without Sharing the Folder + +Here's an important habit: when you share your code with someone else, or move it to a new computer, you almost never copy the `myenv` folder itself along with it - it's often huge, and tied specifically to the machine it was created on. Instead, Python programmers list out *which* packages a project depends on in a plain text file, usually named `requirements.txt`. + +[source,bash] +---- +pip freeze > requirements.txt +---- + +That command writes out everything currently installed in your active virtual environment into `requirements.txt`. Then, anyone else working on the project - on their own computer - creates their own fresh virtual environment and installs everything from that same list: + +[source,bash] +---- +pip install -r requirements.txt +---- + +That way, everyone working on a project ends up with the exact same packages installed, without ever having to share the environment folder itself. + +[TIP] +==== +* In a terminal, `cd` into a new, empty folder +* Run `python3 -m venv venv` to create a virtual environment +* Activate it, and notice your terminal prompt change +* Run `pip install requests`, and notice it installs without needing any special permissions +* Run `pip freeze > requirements.txt` and take a look at what got written into that file +* Run `deactivate` when you're finished +==== + +Virtual environments might feel like unnecessary ceremony while you're working through small examples in this book. But the moment you start building real, multi-package projects - which won't be long now - you'll find that almost every professional Python project you ever touch uses one. It's one of those habits well worth building early. diff --git a/appendixd.adoc b/appendixd.adoc new file mode 100644 index 0000000..83a8d08 --- /dev/null +++ b/appendixd.adoc @@ -0,0 +1,170 @@ + + +[appendix] +== Four Essential Packages to Know + +Back in the venv appendix, we talked about `pip install`-ing packages other people have written. PyPI - the *Python Package Index* - hosts hundreds of thousands of these, but a small handful show up in an enormous share of real-world Python projects. Let's meet four of the most popular: `requests`, `pydantic`, `SQLAlchemy`, and `FastAPI`. + +We're not going to make you an expert in any of these - that's well beyond a beginner's book. The goal here is just *recognition*: when you see one of these names later in your coding life, you'll already know roughly what it does and why people reach for it. + +=== requests: Talking to the Web + +Almost every program eventually needs to fetch data from somewhere out on the internet - checking the weather, pulling stock prices, hitting some company's API. Python's built-in tools for this are clunky. `requests` makes it feel almost as simple as `print()`. + +[source,bash] +---- +pip install requests +---- + +[source] +---- +import requests + +response = requests.get("https://api.github.com") + +print(response.status_code) # -> 200, meaning "OK, success!" +print(response.json()) # -> a dictionary, parsed straight from the response +---- + +That `.get()` call reaches out over the internet and fetches whatever's at that address - the same basic thing your web browser does every time you visit a page, just done from your own code. `.status_code` tells you whether it worked (`200` means success; you'll also see `404` for "not found," and others), and `.json()` conveniently turns the response straight into a Python dictionary, ready to use. + +Sending data works about the same way, using `.post()` instead of `.get()`: + +[source] +---- +new_player = {"name": "Sam", "health": 100} + +response = requests.post("https://example.com/players", json=new_player) + +print(response.status_code) # -> 201, meaning "Created!" +---- + +If `requests` has one core lesson, it's this: your program isn't limited to the data sitting on your own computer. It can reach out and talk to almost anything on the web. + +=== pydantic: Data You Can Trust + +Remember type hints, from a few chapters back? We mentioned that Python doesn't actually *enforce* them - they're just polite suggestions. `pydantic` is a package built entirely around fixing that: it uses your type hints to *actually validate* data, at the moment your program receives it. + +[source,bash] +---- +pip install pydantic +---- + +You describe your data's shape once, as a class, using the same type hints you already know: + +[source] +---- +from pydantic import BaseModel + +class Player(BaseModel): + name: str + health: int = 100 + +sam = Player(name="Sam", health=87) +print(sam.health) # -> 87 +---- + +That looks a lot like the classes from the Objects chapter, except we didn't have to write our own `+++__init__+++`. `BaseModel`, the class we inherited from, builds one for us automatically, based entirely on the type hints we wrote. + +Here's the real payoff - what happens when the data is *wrong*: + +[source] +---- +bad_player = Player(name="Sam", health="a lot") +# pydantic.ValidationError: 1 validation error for Player +# health +# Input should be a valid integer +---- + +`pydantic` looked at our hint, `health: int`, and refused to accept the string `"a lot"` in its place. Instead of your program silently accepting bad data and crashing later, somewhere confusing, `pydantic` stops it immediately, right at the door, with a clear error explaining exactly what went wrong. + +=== SQLAlchemy: Talking to a Database + +Most real programs need to remember things even after they stop running - player accounts, orders, inventory. That's what a *database* is for. `SQLAlchemy` lets you work with a database using ordinary Python classes and objects, instead of writing raw database query language by hand. + +[source,bash] +---- +pip install sqlalchemy +---- + +[source] +---- +from sqlalchemy import create_engine, Column, Integer, String +from sqlalchemy.orm import declarative_base, Session + +Base = declarative_base() + +class Player(Base): + __tablename__ = "players" + id = Column(Integer, primary_key=True) + name = Column(String) + health = Column(Integer) + +engine = create_engine("sqlite:///game.db") +Base.metadata.create_all(engine) +---- + +NOTE: That `+++__tablename__+++` looks a lot like the dunder methods from a few chapters back, but it isn't one - it's not a method Python itself ever calls. It's just a special *attribute* name that `SQLAlchemy` itself looks for, as part of its own class-building machinery, to know what to name the table. Still handy to recognize the double-underscore naming pattern showing up again, in a different context. + +Once that `Player` class exists, we can save new players and look them back up, all with ordinary-looking Python: + +[source] +---- +with Session(engine) as session: + session.add(Player(name="Sam", health=100)) + session.commit() + + sam = session.query(Player).filter_by(name="Sam").first() + print(sam.health) # -> 100 +---- + +Notice we never wrote a single line of raw database query syntax. `SQLAlchemy` translated `session.query(Player).filter_by(name="Sam")` into the appropriate database query behind the scenes, and handed us back a real `Player` object - the very same kind of class we defined ourselves, complete with a `.health` attribute we can just read. + +=== FastAPI: Building Your Own Web API + +`requests` let us *call* someone else's web service. `FastAPI` flips that around - it's for *building your own*. It's one of the most popular ways to build a web API in Python today, largely because it leans so heavily on type hints and `pydantic`, both of which you already know. + +[source,bash] +---- +pip install fastapi uvicorn +---- + +NOTE: `uvicorn` is a second package you install alongside `FastAPI` - it's the actual program that runs your API and listens for incoming requests. `FastAPI` describes *what* your API does; `uvicorn` is what keeps it running. + +[source] +---- +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + +class Player(BaseModel): + name: str + health: int = 100 + +@app.get("/") +def read_root(): + return {"message": "Welcome to the dungeon API!"} + +@app.post("/players") +def create_player(player: Player): + return {"greeting": "Welcome, " + player.name + "!"} +---- +_main.py_ + +That `@app.get("/")` line is a *decorator* - something we haven't covered in this book, but you can read it simply as "run the function right below this when someone visits this address." The second one, `@app.post("/players")`, does the same thing for incoming data - and notice the parameter, `player: Player`. That type hint isn't just documentation here; `FastAPI` and `pydantic` team up to automatically validate every incoming request against our `Player` model, before our function even runs. + +You'd start this API from a terminal with: + +[source,bash] +---- +uvicorn main:app --reload +---- + +and `FastAPI` even generates interactive, browsable documentation for your API automatically, for free, just from your type hints - no extra work required. + +=== How These Four Fit Together + +Picture a simple game server. `FastAPI` handles incoming web requests; `pydantic` (working right alongside `FastAPI`) validates that the data in each request actually makes sense; `SQLAlchemy` saves and retrieves player data from a real database; and some *other* program, maybe even one you write yourself, uses `requests` to call your finished API from the outside, the exact same way it might call anyone else's. + +Four different jobs, four different packages - and every single one of them is built on ideas you already know: classes, type hints, dictionaries, and dunder-style naming conventions. That's really the whole point of a solid beginner's foundation: once you have it, even "advanced" packages like these turn out to be built from pieces you already recognize. diff --git a/appendixe.adoc b/appendixe.adoc new file mode 100644 index 0000000..8b8880b --- /dev/null +++ b/appendixe.adoc @@ -0,0 +1,179 @@ + + +[appendix] +== The Shell Pattern: Setup, Loop, Ending + +Here's something fun: a number-guessing game, a game of Hangman, and a little terminal calculator all have almost nothing in common - and yet, underneath, they're all built from the exact same skeleton. Once you learn to see that skeleton, you can build your own terminal programs just by filling in the blanks. Programmers sometimes call this the *shell* pattern, since everything else gets built inside this one reusable shape. + +=== The Three Phases + +Every simple terminal program breaks into three phases, in this exact order: + +[cols=",,",options="header",] +|=== +|Phase |Runs |Typical Jobs +|*Setup* |Once, before anything else happens |Create your variables, generate the secret, print a welcome message +|*Loop* |Repeatedly, until the program is done |Get input, check it, update the game's state, give feedback +|*Ending* |Once, after the loop breaks |Announce the result, reveal the answer, offer to go again +|=== + +That's really it. Setup happens once. The loop happens over and over. Ending happens once. Let's build a real one. + +=== A Worked Example: Too High / Too Low + +We'll build a classic: the computer picks a secret number between 1 and 100, and the player has 7 guesses to find it, with a hint of "too high" or "too low" after each try. + +==== Setup + +[source] +---- +import random + +# ---------- SETUP (runs once) ---------- +secret = random.randint(1, 100) +guesses_left = 7 +game_over = False +player_won = False + +print("Welcome to Too High / Too Low!") +print("I'm thinking of a number between 1 and 100. You have 7 guesses.") +---- + +Notice everything here happens *before* the player has done anything at all: we pick the secret number, set up our tracking variables, and print the instructions. None of this needs to happen again once the game is underway. + +==== Loop + +[source] +---- +# ---------- LOOP (runs until the game ends) ---------- +while not game_over: + guess = int(input("Your guess: ")) + guesses_left -= 1 + + if guess == secret: + player_won = True + elif guess < secret: + print("Too low!") + else: + print("Too high!") + + print(guesses_left, "guesses left.") + + if player_won or guesses_left == 0: + game_over = True +---- + +This is where the game actually lives. Every single time through the loop, we ask for a guess, check it against the secret, print a hint, and then ask one important question at the very bottom: *should we keep going?* That last `if` is the loop's exit check - it's the only thing standing between "keep playing" and "stop." Set `game_over` to `True`, and the `while not game_over:` condition at the top goes false, and the loop ends. + +==== Ending + +[source] +---- +# ---------- ENDING (runs once, after the loop stops) ---------- +if player_won: + print("You got it! The number was", secret) +else: + print("Out of guesses. The number was", secret) +---- + +Once the loop breaks, we never go back into it. We just look at what happened - did `player_won` end up `True` or not? - and print one final message. + +Put all three pieces together, one after another in a single file, and you have a complete, playable game. + +=== Playing Again, Without Repeating Yourself + +Most games ask "play again?" when they're done. The cleanest way to do that is to wrap your whole Setup/Loop/Ending shell inside a function, and then call that function from a *second*, outer loop. + +[source] +---- +def play_round(): + # ---------- SETUP ---------- + secret = random.randint(1, 100) + guesses_left = 7 + game_over = False + player_won = False + + print("Welcome to Too High / Too Low!") + print("I'm thinking of a number between 1 and 100. You have 7 guesses.") + + # ---------- LOOP ---------- + while not game_over: + guess = int(input("Your guess: ")) + guesses_left -= 1 + + if guess == secret: + player_won = True + elif guess < secret: + print("Too low!") + else: + print("Too high!") + + print(guesses_left, "guesses left.") + + if player_won or guesses_left == 0: + game_over = True + + # ---------- ENDING ---------- + if player_won: + print("You got it! The number was", secret) + else: + print("Out of guesses. The number was", secret) + + +playing = True +while playing: + play_round() + again = input("Play again? (y/n): ") + if again.lower() != "y": + playing = False + +print("Thanks for playing!") +---- + +NOTE: You might come across other versions of this pattern online that have the game's function call *itself* again to restart, instead of using an outer loop like we did. That trick is called *recursion* - a function calling itself - and it's a genuinely useful technique, but it's a bit further down the road than this book goes. The outer `while playing:` loop above gets you the exact same "play again" behavior, using only tools you already have. + +=== A Decision Guide: What Goes Where? + +Whenever you're not sure which of the three phases a piece of code belongs in, ask yourself these questions, in order: + +* *Does it happen exactly once, before the player does anything?* → Setup. +* *Does it need to happen again on every single turn?* → The loop's body. +* *Does it decide whether the loop should keep going, or stop?* → The loop's exit check. +* *Does it only make sense after the game is completely finished?* → Ending. + +If you can answer one of those confidently, you already know exactly where that code belongs. + +=== The Same Shell, Different Games + +Here's the real payoff: this shell isn't specific to number-guessing at all. Swap out what happens *inside* each phase, and the very same three-part shape builds an entirely different program. + +Take Hangman: + +* *Setup* - pick a secret word, set `lives = 6`, start an empty list of guessed letters, and display the word as a row of blanks. +* *Loop* - show the word's current progress, ask for a letter, reveal it if it's in the word (or subtract a life if it isn't), and check whether the player has run out of lives or guessed the whole word. +* *Ending* - announce a win or a loss, reveal the secret word, and ask to play again. + +Or think back to the calculator programs from the Simple Calculation Programs chapter. Turn one into an interactive, REPL-style calculator, and it fits this exact same shell too: + +* *Setup* - print a welcome banner, and set up an empty `history` list to remember past calculations. +* *Loop* - print a `calc>` prompt, read in an operation and some numbers, compute the result, add it to `history`, and print it - checking each time whether the player typed `"quit"`. +* *Ending* - print "Goodbye!" and maybe show the full history of everything that was calculated. + +Different game, different calculator, same three-part skeleton underneath. The player becomes the user; the guess becomes a math operation; the secret number becomes a computed result. The shape never changes. + +[TIP] +==== +* Pick either Hangman or the REPL calculator described above +* Sketch out, in plain English, what belongs in *your* Setup, Loop, and Ending +* Then write the actual code, one phase at a time, using the Too High / Too Low example above as your model +==== + +=== Key Takeaways + +* Every simple terminal program follows the same shape: *Setup → Loop → Ending* +* The loop is the heart of the program - it keeps running until some condition breaks it +* For any piece of code, ask: does this run *once* (Setup or Ending), or does it run *every turn* (the Loop)? +* This shell works for games *and* for tools - calculators, quizzes, unit converters, anything with a "keep going until the user is done" feel to it +* Naming your boolean variables clearly - `game_over`, `player_won` - makes the whole thing dramatically easier to read later + +Learn this one shape well, and you'll find yourself reusing it constantly. Build the pattern once, and you can adapt it to almost anything. diff --git a/arithmeticexpr.adoc b/arithmeticexpr.adoc index 07c5a4d..2eda4a1 100644 --- a/arithmeticexpr.adoc +++ b/arithmeticexpr.adoc @@ -78,7 +78,7 @@ The word trigonometry comes from the Greek words, trigonon ("triangle") + metron We use trigonometry to find angles, distances and areas. For example, if we wanted to find the area of a triangular piece of land, we could use the -equation *AreaOfaTriangle = height * base / 2* +equation *area_of_a_triangle = height * base / 2* Therefore we just need to create variables for each and use the operators to calculate the area. @@ -94,8 +94,8 @@ Formula: A = h * b / 2 ---- height = 20 base = 10 -areaOfaTriangle = height * base / 2 -print(areaOfaTriangle) # -> 100 +area_of_a_triangle = height * base / 2 +print(area_of_a_triangle) # -> 100 ---- diff --git a/booleanexpr.adoc b/booleanexpr.adoc index 38744aa..7cc4238 100644 --- a/booleanexpr.adoc +++ b/booleanexpr.adoc @@ -14,17 +14,17 @@ This idea of a condition that is either TRUE or FALSE, is known as a *boolean ex Boolean expressions can be very complex, or very simple: **** -playerOne.isAlive() == true +player_one.is_alive() == true **** might be a key thing to know inside of a game. But it might be more complicated: **** -player[1].isAlive() == true +player[1].is_alive() == true and -player[2].isAlive() == true +player[2].is_alive() == true and -spaceStation.hasAir() == true +space_station.has_air() == true **** All three things need to be true to continue the game. Using boolean expressions, we can build very powerful tests to make sure everything is just as we need it to be. @@ -35,11 +35,11 @@ We also need more kinds of boolean expressions when we are programming. Things l [source, Python] ---- -healthScore = 5 +health_score = 5 ---- -We need a way to ask about expressions like "is healthScore less than 7?? (very healthy)" or -"is healthScore greater than or equal to 3?? (maybe barely alive?)" +We need a way to ask about expressions like "is health_score less than 7?? (very healthy)" or +"is health_score greater than or equal to 3?? (maybe barely alive?)" To do that we need a bunch of *comparison operators*. @@ -61,14 +61,14 @@ Each of these can be used to make it very clear to someone reading your code wha altitude > 500.0 # high enough to not hit any trees! airspeed >= 85.0 # fast enough to stay in the air. -fuelAvailable <= 5.0 # need to land to refuel! +fuel_available <= 5.0 # need to land to refuel! -totalCargoWeight < 6.0 # more than 6 tons and we can't take off! +total_cargo_weight < 6.0 # more than 6 tons and we can't take off! -pilot.isAlive() and copilot.isAlive() # everything is fine, keep flying. +pilot.is_alive() and copilot.is_alive() # everything is fine, keep flying. ---- -Like the ANDs in the examples above or this last boolean expression with the `and`` in it, we have in Python the ability to combine expressions into larger more complex expressions using `and` and `or`. +Like the ANDs in the examples above or this last boolean expression with the `and` in it, we have in Python the ability to combine expressions into larger more complex expressions using `and` and `or`. == Logical Operators @@ -77,7 +77,7 @@ The *logical operators* are AND and OR, except in Python we use *and* for AND an [cols=",,",options="header",] |=== |Operator |Description | -|and |Logical AND |playerOneStatus == 'alive' and spacecraft.hasAir() +|and |Logical AND |player_one_status == 'alive' and spacecraft.has_air() |or |Logical OR |room.Temp > 70 or room.Temp < 75 |=== @@ -110,16 +110,16 @@ use lots of different comparisons, and combine them with and and or. # deep in a cash machine application... (customer.balance() <= 20.00 \ and \ -customer.hasOverDraftProtection() == true) \ +customer.has_over_draft_protection() == true) \ or \ (customer.savings.balance() > 20.0 \ and \ -customer.canTransferFromSavings() ) +customer.can_transfer_from_savings() ) ---- See how these conditions could line up to allow a customer to get cash from the cash machine? Again, this is *why* boolean expressions are important and powerful and -why coders need to be able to use them to get the software *just right*. +why programmers need to be able to use them to get the software *just right*. [TIP] @@ -133,13 +133,13 @@ Here is an example: [source] ---- -houseTemp = 67.0 -thermostatSetting = 70.0 +house_temp = 67.0 +thermostat_setting = 70.0 -print(houseTemp >= 55.0) -print(houseTemp <= thermostatSetting) -print(thermostatSetting != 72.0) -print(houseTemp > 65.0 and thermostatSetting == 68.0) +print(house_temp >= 55.0) +print(house_temp <= thermostat_setting) +print(thermostat_setting != 72.0) +print(house_temp > 65.0 and thermostat_setting == 68.0) ---- These print statements should produce True, True, True and False. diff --git a/break.adoc b/break.adoc index 4199ad0..6e5e364 100644 --- a/break.adoc +++ b/break.adoc @@ -23,7 +23,7 @@ Another place pass can be used is as a place-holder for a function or conditiona [source] ---- -def isPlayerAlive(*args): +def is_player_alive(*args): pass # you'll program this later ---- diff --git a/builtins.adoc b/builtins.adoc new file mode 100644 index 0000000..524d42e --- /dev/null +++ b/builtins.adoc @@ -0,0 +1,203 @@ + + +== Built-in Functions + +You've already met a few of Python's *built-in functions* without me making a big deal about it. `print()`, `len()`, `type()`, `range()` - these have been showing up in almost every chapter so far. That's because Python ships with a whole toolbox of these ready-made functions, sitting there waiting for you to use them, no importing required. + +Think of built-in functions as the tools that came in the toolbox when you bought it, versus tools you'd have to go buy separately (that's what _modules_ are for, which we'll get to). You don't have to build a hammer before you can hammer a nail. Python already handed you the hammer. + +We're not going to cover *all* of them - there are over 70 in Python - but let's round up the ones you'll reach for every single day. + +=== The Everyday Ones + +These are the built-ins you'll type without even thinking about it, mostly for looking at what's going on inside your program. + +[cols=",",options="header",] +|=== +|Function |What it does +|`print()` |Sends text or a value out to the screen +|`len()` |Tells you how many items are in a string, list, tuple, dictionary, or set +|`type()` |Tells you what kind of thing a variable actually is +|`input()` |Pauses your program and waits for the human to type something +|=== + +You already know `print()` and `len()` well. `type()` showed up back when we talked about data types - it's your go-to when you're not sure what you're holding. + +[source] +---- +donut_count = 12 +print(type(donut_count)) # -> +---- + +`input()` is new, and it's a fun one, because it's the first time your program actually *listens* to a human being instead of just talking at them. + +[source] +---- +player_name = input("What's your character's name? ") +print("Welcome to the dungeon, " + player_name + "!") +---- + +Whatever the person types gets handed back to you *as a string*, every single time - even if they type a number. + +[source] +---- +age = input("How old is your character? ") +print(type(age)) # -> , even though they typed "25" +---- + +NOTE: If you need that input as an actual number, you have to convert it yourself, which brings us to our next set of tools. + +=== Converting Between Types + +`str()`, `int()`, `float()`, and `bool()` let you convert a value from one data type into another. You've actually already seen `str()` back when we talked about joining a number onto a string. + +[source] +---- +hours_worked = 12 +report = "Hours worked: " + str(hours_worked) +---- + +The reverse trick works too. Remember how `input()` always hands you back a string? Here's how you turn that string into a real number you can do math with. + +[source] +---- +age_text = input("How old is your character? ") +age = int(age_text) + +print(age + 1) # works! age is now a real number. +---- + +[source] +---- +print(int("42")) # -> 42 +print(float("3.14")) # -> 3.14 +print(bool(0)) # -> False +print(bool(1)) # -> True +print(bool("")) # -> False, an empty string is "falsy" +print(bool("hello")) # -> True, almost anything else is "truthy" +---- + +There are four more constructors just like these, except they build *data structures* instead of simple values: `list()`, `dict()`, `set()`, and `tuple()`. We met `set()` this way back in the Sets chapter, turning a list with duplicates into a set with none. + +[source] +---- +weapons_picked = ["sword", "bow", "sword", "axe", "bow"] + +unique_weapons = set(weapons_picked) +print(unique_weapons) # -> {'sword', 'bow', 'axe'} + +back_to_a_list = list(unique_weapons) +print(back_to_a_list) # -> ['sword', 'bow', 'axe'] +---- + +Each of these constructors is handy any time you need an empty starting point, too - `[]` and `list()` do the same job, but sometimes writing `list()` makes your intention clearer to someone reading your code. + +=== Looping Like a Pro + +We introduced `range()` back in the For Loop chapter, so you already know it generates a sequence of numbers to loop over. Now let's meet a couple of its cousins that make loops even more powerful. + +`enumerate()` solves a really common headache: needing *both* an item from a list *and* its index, at the same time, without writing your own counter variable. + +[source] +---- +donut_flavors = ["chocolate", "glazed", "jelly"] + +for index, flavor in enumerate(donut_flavors): + print(index, "-", flavor) + +# output is +# 0 - chocolate +# 1 - glazed +# 2 - jelly +---- + +Before `enumerate()`, you'd have had to do something clunkier, like looping over `range(len(donut_flavors))` and indexing in yourself. `enumerate()` just hands you both pieces, gift-wrapped, every time through the loop. + +`zip()` is for when you've got two (or more) lists that go together, item by item, and you want to walk through them side by side. + +[source] +---- +player_names = ["Sam", "Jade", "Sadie"] +player_health_scores = [100, 87, 42] +player_data = zip(player_names, player_health_scores) +print(type(player_data)) # -> + +for name, health in player_data: + print(name, "has", health, "health points.") + +# output is +# Sam has 100 health points. +# Jade has 87 health points. +# Sadie has 42 health points. +---- + +`zip()` pairs up the first item of each list, then the second item of each, and so on - like a zipper on a jacket, pulling two rows of teeth (data) together one pair at a time. That's actually where it gets its name. + +Finally, `sorted()` hands you back a *brand new* sorted list, and - importantly - it leaves your original list completely untouched. + +[source] +---- +player_health_scores = [100, 87, 42, 100, 65] + +ranked = sorted(player_health_scores) +print(ranked) # -> [42, 65, 87, 100, 100] +print(player_health_scores) # -> [100, 87, 42, 100, 65], unchanged! +---- + +Want it the other way around, highest to lowest? Just add `reverse=True`. + +[source] +---- +ranked = sorted(player_health_scores, reverse=True) +print(ranked) # -> [100, 100, 87, 65, 42] +---- + +=== Doing Math Without the `math` Module + +A handful of built-ins handle simple math jobs so commonly needed that Python doesn't even make you `import` anything for them. + +[source] +---- +weekday_scores = [88, 92, 79, 95, 100] + +print(sum(weekday_scores)) # -> 454 +print(max(weekday_scores)) # -> 100 +print(min(weekday_scores)) # -> 79 +---- + +`sum()`, `max()`, and `min()` all work on any list (or tuple, or set) full of numbers. `max()` and `min()` also work if you just hand them a plain old comma-separated list of values, no brackets needed. + +[source] +---- +print(max(4, 19, 7)) # -> 19 +print(min(4, 19, 7)) # -> 4 +---- + +`abs()` gives you the *absolute value* of a number - meaning, it strips away any negative sign and hands you back the positive version. + +[source] +---- +altitude_change = -350 + +print(abs(altitude_change)) # -> 350 +---- + +Why would you want that? Imagine our Mars Lander from the Appendix, tracking how far off course it drifted. Sometimes it drifts left (negative), sometimes right (positive), but for a warning light, you often just care *how much* it drifted, not which direction. + +[source] +---- +drift = -12.5 + +if abs(drift) > 10: + print("Warning: lander has drifted too far off course!") +---- + +[TIP] +==== +* Make a list of five numbers, some positive and some negative +* Use `sum()` to add them all up +* Use `max()` and `min()` to find the highest and lowest +* Use `abs()` on the lowest one to see how "big" it really is, ignoring its sign +==== + +We've covered the built-ins you'll reach for constantly, in almost every program you write. Once these feel comfortable in your hands, head on to the next chapter, where we'll take a closer look at lambdas - small, throwaway functions that pair up with a few more built-in functions you're about to meet. diff --git a/builtinsadvanced.adoc b/builtinsadvanced.adoc new file mode 100644 index 0000000..21cae5f --- /dev/null +++ b/builtinsadvanced.adoc @@ -0,0 +1,115 @@ + + +== Advanced Built-in Functions + +A couple of chapters back, we covered the built-in functions you'll use constantly, without much thought. And in the last chapter, you got comfortable with lambdas - those small, throwaway, one-line functions. Now let's put lambdas to work, alongside a handful of built-in functions that let you test or transform an *entire collection* in one line, instead of writing out a `for` loop by hand every time. + +These aren't harder to use than what you've already seen, they're just a bit less obvious *why* you'd want them, until you've hit the problem they solve. So let's hit those problems. + +=== Testing a Whole Collection at Once + +`any()` and `all()` save you from writing a bunch of `and`/`or` chains by hand, when what you really want to know is something about a *whole group* of true/false values. + +`all()` checks whether *every single item* in a collection is `True`. If even one item is `False`, the whole thing is `False`. + +[source] +---- +players_alive = [True, True, True] +print(all(players_alive)) # -> True, everybody made it! + +players_alive = [True, False, True] +print(all(players_alive)) # -> False, someone didn't make it. +---- + +`any()` checks whether *at least one* item is `True`. It only comes back `False` if every single item is `False`. + +[source] +---- +players_alive = [False, False, True] +print(any(players_alive)) # -> True, at least one player survived! + +players_alive = [False, False, False] +print(any(players_alive)) # -> False, nobody made it. Game over. +---- + +These come in especially handy paired with a quick list of boolean expressions, so you can check a whole batch of conditions in one line instead of writing them all out with `and` or `or`. + +[source] +---- +checks = [ + fuel_available > 0, + altitude > 0, + pilot.is_alive() +] + +if all(checks): + print("Cleared for takeoff!") +---- + +=== Applying a Function to an Entire List + +`map()` takes a function and a list, and runs that function on *every single item* in the list, handing you back the results. It saves you from writing out a `for` loop just to transform each item the same way. + +[source] +---- +player_health_scores = [100, 87, 42] + +def apply_shield_bonus(score): + return score + 10 + +boosted_scores = list(map(apply_shield_bonus, player_health_scores)) +print(boosted_scores) # -> [110, 97, 52] +---- + +Notice we had to wrap it in `list()`. That's because `map()` doesn't hand you back a list directly - it hands you back something called a *map object*, which is really just a promise to compute those values when you actually ask for them. Wrapping it in `list()` says "okay, compute them now, and give me a real list." + +You'll often see `map()` paired with a `lambda`, since the function you're applying is frequently a small, throwaway one. + +[source] +---- +donut_prices = [1.50, 1.75, 2.00] + +prices_with_tax = list(map(lambda price: price * 1.06, donut_prices)) +print(prices_with_tax) # -> [1.59, 1.855, 2.12] +---- + +=== Filtering a List + +`filter()` is a close cousin of `map()`. Instead of transforming every item, it *keeps only the items that pass a test*, throwing the rest away. + +[source] +---- +player_health_scores = [100, 87, 0, 42, 0] + +def is_still_alive(score): + return score > 0 + +survivors = list(filter(is_still_alive, player_health_scores)) +print(survivors) # -> [100, 87, 42] +---- + +Just like `map()`, `filter()` needs a function that returns `True` or `False` for each item, and just like `map()`, you'll usually wrap the result in `list()` to see it plainly. And just like `map()`, a `lambda` often does the job without needing a separate named function at all. + +[source] +---- +donut_flavors = ["chocolate", "glazed", "jelly", "chocolate glaze"] + +chocolatey_ones = list(filter(lambda flavor: "chocolate" in flavor, donut_flavors)) +print(chocolatey_ones) # -> ['chocolate', 'chocolate glaze'] +---- + +Between `map()` (transform everything) and `filter()` (keep only some things), you can do an enormous amount of list-wrangling without ever writing a manual `for` loop. + +[TIP] +==== +* Start with a list of five player health scores, mixing in a couple of zeros for "fallen" players +* Use `filter()` to build a list of only the survivors +* Use `map()` on that survivor list to give everyone a `+5` health bonus +* Use `all()` to check whether every remaining survivor now has more than 50 health +==== + +=== Keep Exploring + +Between the last chapter and this one, we've covered a solid dozen of Python's built-in functions, but there are dozens more out there, quietly waiting to make your life easier. The real lesson isn't "memorize this list." It's this: *before you write ten lines of code to solve a problem, check if Python already gave you a built-in function that does it in one.* More often than you'd think, it already has. + +Coming up next, we'll look at *comprehensions* - Python's even shorter, and arguably more popular, way to do what `map()` and `filter()` just did for us. diff --git a/consolelog.adoc b/consolelog.adoc index 4498b4d..fcbc195 100644 --- a/consolelog.adoc +++ b/consolelog.adoc @@ -13,18 +13,19 @@ This program just prints "Hello, World!". footnote:[And while you might _not yet Printing goes to "standard output", a place Python uses to communicate with a user (in this case, us, the programmers.) -And if you haven't done it yet, go to https://code.zipcode.rocks/python/ and make a browser bookmark for yourself. Once that's done, you can use that Python REPL footnote:[a REPL is short for "read-evaluate-print loop", a special kind of computer program that lets you run code of a given language.] as a place where you can type in the code from this book and run it to see what each code snippet does. -We run `python3` in this book. -Don't use python version 2. `python3` is what the pros use. +And if you haven't done it yet, go to https://code.zipcode.rocks/python/ and make a browser bookmark for yourself. Once that's done, you can use that Python REPL footnote:[a REPL is short for "read-evaluate-print loop", a special kind of computer program that lets you run code of a given language.] as a place where you can type in the code from this book and run it to see what each code snippet does. +We run `python3` (and let's get specific, v2 of this book relies on *at least* python 3.14 in this book.) +Don't use python version 2. +`python3` is what the pros use. We will use `print` to do a lot in the coming pages. -Here's your second Python program: +Here's your second Python program: [source] ---- -milesPerHour = 55.0 -print("Car's Speed: ", milesPerHour) +miles_per_hour = 55.0 +print("Car's Speed: ", miles_per_hour) ---- If you typed into your REPL and clicked the "Run" button, you should have seen this as your output: @@ -35,13 +36,13 @@ Car's Speed: 55 as the program's output. -Cool, huh? The ability to communicate with you is one of Python's most fundamental capabilities. And you've run two Python programs. Congratulations, you're a coder. (Well, at least for today you are.) +Cool, huh? The ability to communicate with you is one of Python's most fundamental capabilities. And you've run two Python programs. Congratulations, you're a programmer. (Well, at least for today you are.) == Comments While you're not thinking about the long term, or about large Python programs, there is a powerful thing in Python that helps with tracking comments and notes about the code. -In your program, you can write stuff that Python will ignore, it's just there for you (or readers of your code). +In your program, you can write stuff that Python will ignore, it's just there for you (or readers of your code). We use a 'hash character' to start a comment, and the comment goes to the end of the line. Python will ignore anything on a line after a hash character. "#" @@ -57,25 +58,25 @@ Often, you'll see something like this in this book. [source] ---- -flourAmount = 3.5; +flour_amount = 3.5; -print(flourAmount); # -> 3.5 +print(flour_amount); # -> 3.5 ---- That comment at the end of the print line is showing what you can expect to see in the output. Here it would be "3.5" printed by itself. Try it in your bookmarked Repl. -We can also add useful stuff to the .log call. +We can also add useful stuff to the .log call. [source] ---- -flourAmount = 3.5; +flour_amount = 3.5; -print("We need", flourAmount, "cups of flour."); # -> We need 3.5 cups of flour. +print("We need", flour_amount, "cups of flour."); # -> We need 3.5 cups of flour. ---- See how Python types it all out as a useful phrase? That proves to be very handy in a million-plus (or more) cases. -Comments can be used to explain tricky bits of code, or describe what you should see in output. Comments are your friend. +Comments can be used to explain tricky bits of code, or describe what you should see in output. Comments are your friend. == Statements and Expressions @@ -91,34 +92,37 @@ An *expression* is something that needs to be computed to find out the answer. H speed > 55.0 -regularPrice * (1.0 - salePercentOff) +regular_price * (1.0 - sale_percent_off) ---- Each of these lines is something we'd like Python to *compute* for us. That computation is often referred to as "evaluation" or "evaluate the expression" to get to the answer. There are two kinds of expressions in Python, _arithmetic expressions_ and _boolean expressions_. *Arithmetic expressions* are, as their name implies, something that require arithmetic to get the answer. An expression like "5 + 8 - 3" gets _evaluated_ to 10. -*Boolean expressions* result in either a True or a False value. Example: "maxSpeed > 500.0" - this is either true or false depending on the value of maxSpeed. +*Boolean expressions* result in either a True or a False value. Example: "max_speed > 500.0" - this evaluates to either true or false depending on the value of max_speed. === Statements A *statement* is just a line of Python. +All python statements have very specific patterns. [source] ---- # at the Grocery -salesTaxRate = 0.06 +sales_tax_rate = 0.06 -totalGroceries = 38.99 -salesTax = totalGroceries * salesTaxRate +total_groceries = 38.99 +sales_tax = total_groceries * sales_tax_rate -chargeToCard = totalGroceries + salesTax +charge_to_card = total_groceries + sales_tax ---- And this is what a Python program looks like. It's just a list of statements, one after the other, that get computed from the top down. -Some of the statements have expressions in them (like totalGroceries * salesTaxRate), while some are just simple *assignment* statements (like totalGroceries = 38.99, where we assign the variable 'totalGroceries' the value 38.99). -Don't panic. These are just some simple examples of Python to give you a feel for it. +This is referred to control flow. The first statement is executed, then the second, and so on, until the program reaches the end. + +Some of the statements have expressions in them (like total_groceries * sales_tax_rate), while some are just simple *assignment* statements (like total_groceries = 38.99, where we assign the variable 'total_groceries' the value 38.99). +Don't panic. These are just some simple examples of Python to give you a feel for it. We'll go thru each of these kinds of things slowly in sections ahead. === Multi-line Statements @@ -129,9 +133,9 @@ In this book, you may see that the code used in examples is longer than can fit ---- k = h * kph - (rest / 60) -kilometersCycled = numberOfHoursPedalled \ - * kilometersPerHour \ - - (totalMinutesOfRest / 60) +kilometers_cycled = number_of_hours_pedalled \ + * kilometers_per_hour \ + - (total_minutes_of_rest / 60) ---- When you come across code that goes onto multiple lines, do like Python does, look for the backslash, when you find it, think of the line being spread out. @@ -140,29 +144,31 @@ When you come across code that goes onto multiple lines, do like Python does, lo Very often in Python, we will see a *block* of statements. It is a list of statements _indented_ the same amount. (Yes, unlike many languages, in Python, _white space is important_.) It acts like a container to make clear what statements are included in the block. -It is _so important_ that indentation, and making sure you have everything aligned properly, is one of the most important thing to learn about Python when you are a beginner. -Many a beginner discovers that the braces _{ }_ that other languages use to manage the way code is grouped together are missing from Python. Java, JavaScript, and many other languages use braces to handle how code gets grouped together. - -Not Python, that's why is _SO_ very important to get it right. +It is _so important_ that *indentation* and *making sure you have everything aligned properly* is *one of the most important things to learn* about Python when you are a beginner. +Many beginners discover that the braces _{ }_ that other languages use to manage the way code is grouped together are missing from Python. Java, JavaScript, and many other languages use braces to handle how code gets grouped together. [source] ---- -if (magePower > 120.0): - maxMagic = 500.0 - lifeSpan = 800.0 - maxWeapons = magePower / maxPowerPerWeapon - if (maxWeapons < 150): +if (mage_power > 120.0): + max_magic = 500.0 + life_span = 800.0 + max_weapons = mage_power / max_power_per_weapon + if (max_weapons < 150): print('You have too many weapons!') else: backpack.load() # some more code -print(magePower, "is your Mage's Power rating.") +print(mage_power, "is your Mage's Power rating.") ---- -See those SPACES (and confusingly, they might be TABs but you cannot tell that by looking at the line). +**Python does not use braces to group code together. Instead, it uses indentation.** + +Not Python, that's why is _SO_ *very important* to get it right. + +See those SPACES (and confusingly, they might be TABs but you cannot tell that by looking at the line). All the indented lines below the IF statement are part of what gets run when the IF is True. -Then you also see a nested IF below that, one that has an _else_ statement. +Then you also see a nested IF below that, one that has an _else_ statement. But the key thing is to look at the lines of code and notice how they are _indented_, because that tells what you need to know about how the program works, and what gets done depending on the states of the variables. (Don't worry, we will be going into all this a lot more carefully later.) @@ -175,4 +181,3 @@ So, the wise Python beginner spends a fair amount of time making sure the detail Making sure code is indented correctly is part of being a Pythonista. Indentation is rejected as inconsistent if the code mixes tabs and spaces it gets flagged as an error in the code; a TabError is raised in that case. - diff --git a/controlflow.adoc b/controlflow.adoc index 7b9184f..8175d3d 100644 --- a/controlflow.adoc +++ b/controlflow.adoc @@ -15,16 +15,16 @@ When programs start to get more sophisticated, the _control flow_ can be changed [source] ---- -peoplePerTable = 5 +people_per_table = 5 tables = 8 -maximumRoomOccupancy = tables * peoplePerTable +maximum_room_occupancy = tables * people_per_table # up to this point we just stepped line by line -if (bridesDesiredPartySize > maximumRoomOccupancy): - canHandleThisReception = False +if (brides_desired_party_size > maximum_room_occupancy): + can_handle_this_reception = False else: - canHandleThisReception = True + can_handle_this_reception = True ---- See how the IF statement can change a variable based on a decision about another variable? diff --git a/dictcomprehension.adoc b/dictcomprehension.adoc new file mode 100644 index 0000000..bd97f0a --- /dev/null +++ b/dictcomprehension.adoc @@ -0,0 +1,109 @@ + + +== Dictionary Comprehensions + +Now that list comprehensions feel familiar, let's reuse that exact same idea to build a *dictionary* instead of a list. Not surprisingly, this is called a *dictionary comprehension*. + +=== Building a Dictionary the Old Way + +Remember `zip()`, from the Built-in Functions chapter? We used it to pair up player names with their health scores and loop over both together. + +[source] +---- +player_names = ["Sam", "Jade", "Sadie"] +player_health_scores = [100, 87, 42] + +health_lookup = {} +for name, health in zip(player_names, player_health_scores): + health_lookup[name] = health + +print(health_lookup) +# output is +# {'Sam': 100, 'Jade': 87, 'Sadie': 42} +---- + +We're building an empty dictionary, then looping and adding one key:value pair at a time. It works, but just like with lists, there's a shortcut. + +=== The Dictionary Comprehension Way + +[source] +---- +player_names = ["Sam", "Jade", "Sadie"] +player_health_scores = [100, 87, 42] + +health_lookup = {name: health for name, health in zip(player_names, player_health_scores)} + +print(health_lookup) +# output is +# {'Sam': 100, 'Jade': 87, 'Sadie': 42} +---- + +Same result, one line. The pattern looks almost exactly like a list comprehension, except it's wrapped in curly braces `{}` (just like a dictionary itself), and instead of one expression, you provide *two*, separated by a colon - a key and a value. + +[source] +---- +{key_expression: value_expression for item in iterable} +---- + +* `key_expression` - what becomes the key for this pair +* `value_expression` - what becomes the value for this pair +* `item` - the name for whatever you're pulling out of `iterable`, one at a time + +=== A Simpler Example + +Let's build a dictionary that maps each donut flavor to the length of its name - no `zip()` required this time, just one list. + +[source] +---- +donut_flavors = ["chocolate", "glazed", "jelly"] + +flavor_lengths = {flavor: len(flavor) for flavor in donut_flavors} + +print(flavor_lengths) +# output is +# {'chocolate': 9, 'glazed': 6, 'jelly': 5} +---- + +Here, `flavor` is both the key *and* used to compute the value (`len(flavor)`). The key and the value don't have to come from different places - they can both be built from the very same item. + +=== Filtering, Same as Before + +Just like list comprehensions, you can tack an `if` onto the end to only include certain pairs. + +[source] +---- +player_health_scores = {"Sam": 100, "Jade": 87, "Sadie": 0} + +survivors_only = {name: health for name, health in player_health_scores.items() if health > 0} + +print(survivors_only) +# output is +# {'Sam': 100, 'Jade': 87} +---- + +NOTE: To loop over an *existing* dictionary's key:value pairs, you call `.items()` on it, which is what hands you both `name` and `health` together, one pair at a time. + +=== Transforming an Existing Dictionary + +Dictionary comprehensions are also great for building a *new, changed* version of a dictionary you already have, without touching the original. + +[source] +---- +player_health_scores = {"Sam": 100, "Jade": 87, "Sadie": 42} + +boosted = {name: health + 10 for name, health in player_health_scores.items()} + +print(boosted) # -> {'Sam': 110, 'Jade': 97, 'Sadie': 52} +print(player_health_scores) # -> {'Sam': 100, 'Jade': 87, 'Sadie': 42}, unchanged! +---- + +[TIP] +==== +* Start with a dictionary mapping three donut flavors to their prices +* Build a new dictionary, using a comprehension, with 6% sales tax added to every price +* Now build a second comprehension that only keeps the flavors priced under $2.00 +==== + +Dictionary comprehensions come in handy any time you're building a lookup table from some other collection of data - which, now that you're thinking in Python, turns out to be *very* often. + +There's one more comprehension left to meet. Let's finish this trio by building a set. diff --git a/dictionary.adoc b/dictionary.adoc index 82bcf14..e99647d 100644 --- a/dictionary.adoc +++ b/dictionary.adoc @@ -25,7 +25,7 @@ Modifying a dictionary and getting values from them is very easy. [source] ---- # get Sam's number -currentPhone = phonenumbers["Sam"] +current_phone = phonenumbers["Sam"] # we can also update a value phonenumbers['Jade'] = 6551439 @@ -60,10 +60,10 @@ And one of the very cooler aspects is the testing of whether or not a key is in [source] ---- if 'Sam' in phonenumbers: # -> True - doSomething() + do_something() if 'Guido' not in phonenumbers: # -> False - figureOutWhyNot() + figure_out_why_not() ---- We could use them to hold information about some object we're holding data about. diff --git a/dundermethods.adoc b/dundermethods.adoc new file mode 100644 index 0000000..2d781f8 --- /dev/null +++ b/dundermethods.adoc @@ -0,0 +1,154 @@ + + +== Dunder Methods + +In the last chapter, our `Spacecraft` class had two methods that looked a little strange: `+++__init__+++` and `+++__str__+++`. Those double underscores on both sides aren't a typo, and they aren't decoration. They're Python's way of marking a method as special. Programmers call these *dunder methods* - short for "Double UNDERscore" - and this chapter is all about what they are and why they matter. + +=== What Makes a Method a "Dunder" + +Any method whose name starts and ends with two underscores, like `+++__init__+++` or `+++__str__+++`, is a dunder method. You don't invent these names yourself - Python has a fixed list of them, and each one has a specific job. What makes them special is that you almost never call them directly. Instead, *Python calls them for you*, automatically, in response to something else you do to the object - creating it, printing it, comparing it, and so on. + +Think of dunder methods as hooks. You write the hook, and Python promises to pull it at just the right moment. + +=== `+++__init__+++`: The Constructor You Already Know + +You met this one last chapter, but let's call it out by name: `+++__init__+++` is called automatically the *instant* you create a new object. It's where you set up all of an object's starting values. + +[source] +---- +class Spacecraft: + def __init__(self, name, topspeed): + self.name = name + self.topspeed = topspeed + self.current_speed = 0 + +enterprise = Spacecraft("Enterprise", 9.9) +print(enterprise.name) # -> Enterprise +print(enterprise.topspeed) # -> 9.9 +---- + +Notice we didn't have to set `enterprise.name = "Enterprise"` on a separate line afterward, like we did before `+++__init__+++` showed up. Passing `"Enterprise"` and `9.9` straight into `Spacecraft(...)` hands them right to `+++__init__+++`, which tucks them away on `self`. `+++__init__+++` is a dunder, but it's such a common one you'll write it in almost every class you ever build. + +=== `+++__str__+++`: Controlling How print() Sees You + +You also met `+++__str__+++` last chapter. It's the hook that Python pulls whenever your object needs to be turned into a readable string - most commonly, when you `print()` it. + +[source] +---- +class Spacecraft: + def __init__(self, name, topspeed): + self.name = name + self.topspeed = topspeed + + def __str__(self): + return "Starship " + self.name + +enterprise = Spacecraft("Enterprise", 9.9) +print(enterprise) +# -> Starship Enterprise +---- + +Without `+++__str__+++`, `print(enterprise)` would spit out something ugly and unhelpful, like `<+++__main__+++.Spacecraft object at 0x103013100>`. With it, you decide exactly what shows up. + +=== `+++__eq__+++`: Teaching Python What "Equal" Means + +By default, Python considers two objects equal only if they are *literally the same object* in memory - not just similar, but the exact same one. + +[source] +---- +enterprise = Spacecraft("Enterprise", 9.9) +enterprise_copy = Spacecraft("Enterprise", 9.9) + +print(enterprise == enterprise_copy) # -> False, even though they look identical! +---- + +That's often not what we want. If two spacecraft have the same name, we probably want `==` to say they're equal. That's what `+++__eq__+++` is for. + +[source] +---- +class Spacecraft: + def __init__(self, name, topspeed): + self.name = name + self.topspeed = topspeed + + def __eq__(self, other): + return self.name == other.name + +enterprise = Spacecraft("Enterprise", 9.9) +enterprise_copy = Spacecraft("Enterprise", 9.9) + +print(enterprise == enterprise_copy) # -> True now! +---- + +`+++__eq__+++` takes two things to compare: `self` (the object on the left of `==`) and `other` (the object on the right). Whatever expression you return becomes the answer to "are these equal?" + +=== `+++__len__+++`: Letting Your Object Work With len() + +Remember `len()`, from way back in the Built-in Functions chapter? It works on strings, lists, dicts, and sets - and it can work on *your own* classes too, if you define `+++__len__+++`. + +[source] +---- +class Fleet: + def __init__(self, ships): + self.ships = ships + + def __len__(self): + return len(self.ships) + +home_fleet = Fleet(["Enterprise", "Constellation", "Defiant"]) + +print(len(home_fleet)) # -> 3 +---- + +Whatever number `+++__len__+++` returns is exactly what `len()` hands back to whoever calls it. This is a small example of a bigger idea: dunder methods are how your *own* classes get to plug into Python's built-in functions and operators, instead of only working with Python's built-in types. + +=== `+++__add__+++`: Teaching Python What "+" Means for You + +That same idea applies to operators, not just functions. `+++__add__+++` controls what happens when your object is used on the left side of a `+`. + +[source] +---- +class Fleet: + def __init__(self, ships): + self.ships = ships + + def __add__(self, other): + return Fleet(self.ships + other.ships) + + def __len__(self): + return len(self.ships) + +home_fleet = Fleet(["Enterprise", "Constellation"]) +reserve_fleet = Fleet(["Defiant"]) + +combined_fleet = home_fleet + reserve_fleet + +print(len(combined_fleet)) # -> 3 +---- + +Without `+++__add__+++`, writing `home_fleet + reserve_fleet` would just crash with an error, since Python has no idea how to "add" two `Fleet` objects together. With it, you decide what `+` should mean for your own class. + +=== A Quick Reference + +[cols=",,",options="header",] +|=== +|Dunder Method |Gets Called When... |Common Use +|`+++__init__+++` |An object is created |Setting up starting values +|`+++__str__+++` |The object is printed, or turned into a string |A friendly, readable description +|`+++__eq__+++` |Two objects are compared with `==` |Deciding what "equal" means for your class +|`+++__len__+++` |`len()` is called on the object |Reporting some meaningful "size" +|`+++__add__+++` |Two objects are combined with `+` |Deciding what "adding" means for your class +|=== + +[TIP] +==== +* Add a `+++__len__+++` method to a `Player` class that returns how many items are in that player's inventory list +* Add an `+++__eq__+++` method that considers two players equal if they have the same name +* Try `len(player)` and `player_one == player_two` and see your dunder methods kick in +==== + +=== Why This Matters + +Here's the big idea to walk away with: dunder methods are the bridge between *your own* custom classes and all the built-in syntax and functions you've already learned throughout this book - `print()`, `len()`, `==`, `+`, and plenty more we haven't shown here. You're not learning a pile of odd, unrelated tricks. You're learning the *one mechanism* Python uses, over and over, to let your objects behave like they belong in the language, right alongside strings, lists, and dictionaries. + +You won't need most dunder methods most of the time. But `+++__init__+++` and `+++__str__+++` will show up in nearly every class you write from here on out, so make sure those two, at least, feel like old friends. diff --git a/forloop.adoc b/forloop.adoc index 50e68b8..a13a698 100644 --- a/forloop.adoc +++ b/forloop.adoc @@ -5,7 +5,7 @@ The *for* loop is more complex, but it’s also the most commonly used loop. In Python, the for loop is very powerful. It has a number of different forms, including one which is remarkably simple. -Maybe we have a list of donuts. +Maybe we have a list of donuts. And we want to print out each one. [source] @@ -39,7 +39,7 @@ for index in range(len(list_of_donuts)): Here the index was set to 0 and then 1, and then 2, and the index was used to retrieve from the list the donut name at the index. list_of_donuts[1] is "glazed". This example's out is the same as the for-each loop above. -Let's use range() is much more common usage. +Let's use *range()* is much more common usage. Here's one where we go from 0 to 4. @@ -58,12 +58,12 @@ Now say we wanted to print out the sum of all the numbers from 1 to 10. ---- # performing sum of 1 to 10 sum = 0 -for i in range(1, 11): - sum = sum + i +for i in range(1, 11): + sum = sum + i print("Sum of first 10 natural numbers is ", sum) ---- -Wait! Notice how we have to ask range to *one beyond* the last number we want added to the sum! +Wait! Notice how we have to ask range to *one beyond* (11) the last number we want added to the sum! That's because the range starts at 0 and includes every whole number up to, but *not including*, the number that you have provided as the stop number. There are three versions to the range()'s mechanism. @@ -103,3 +103,10 @@ Look, we had to range(10, 0, -1) to get the one to print. Otherwise if we had ha The *range()* function gets used a lot in Python, and is the envy of many programmers in other languages who have use the *for* loop that was handed down from the C programming language. So use it widely, and don't gloat -- too much :-) +=== A Quick Word: Iterables + +Notice that we've now written `for donut in list_of_donuts:` and `for j in range(5):` - two very different-looking things sitting after that `in`. Python has a name for anything that's allowed to sit there: an *iterable*. Something is iterable if a `for` loop knows how to walk through it, one item at a time. + +Lists and ranges are iterables. So are strings - that's exactly what let us loop over "hello" letter by letter, back in the Strings chapter. As you meet more data structures later in this book - dictionaries, sets, tuples - you'll find every single one of them is iterable too, which means `for thing in that_data_structure:` will always just work. + +You don't need to know *how* Python pulls this off yet - just get comfortable with the word "iterable," since we'll use it constantly from here on. Much later in the book, in a chapter called Iterators, we'll open the hood and see exactly what makes something iterable in the first place. diff --git a/functionparams.adoc b/functionparams.adoc new file mode 100644 index 0000000..86de58f --- /dev/null +++ b/functionparams.adoc @@ -0,0 +1,149 @@ + + +== Flexible Function Parameters + +Back in the Functions chapter, every parameter we wrote was required - the caller had to hand over exactly the right number of values, in exactly the right order, every single time. That works fine for simple functions, but real programs often need more flexibility: an optional parameter with a sensible fallback, or a function that has no idea in advance how many values it's about to receive. Python gives you three tools for exactly this: *default parameter values*, `+++*args+++`, and `+++**kwargs+++`. + +=== Default Parameter Values + +A default parameter value is a fallback - a value Python uses automatically if the caller doesn't bother providing one. + +[source] +---- +def greet_user(username, greeting="Hello"): + return greeting + ", " + username + "!" + +print(greet_user("Mike Jones")) # -> Hello, Mike Jones! +print(greet_user("Mike Jones", "Welcome back")) # -> Welcome back, Mike Jones! +---- + +Notice `greeting` has `="Hello"` right in the function definition. If the caller only passes one argument, Python fills in `"Hello"` for `greeting` automatically. But if the caller *does* provide a second argument, that value wins instead, overriding the default. + +Here's one for our dungeon game: + +[source] +---- +def take_damage(player, amount=10): + player["health"] = player["health"] - amount + +sam = {"name": "Sam", "health": 100} + +take_damage(sam) # uses the default, amount=10 +print(sam["health"]) # -> 90 + +take_damage(sam, 25) # overrides the default +print(sam["health"]) # -> 65 +---- + +NOTE: Default parameters must come *after* any required ones in your function's parameter list. `def take_damage(amount=10, player):` would confuse Python - it wouldn't know if a lone argument was meant for `amount` or `player`. Required parameters always come first, defaults come last. + +=== Accepting Any Number of Arguments: `+++*args+++` + +Sometimes you genuinely don't know, ahead of time, how many values a function needs to accept. Maybe you're totaling up hits from an unpredictable, chaotic battle - sometimes there are two hits, sometimes there are seven. That's what `+++*args+++` is for. + +[source] +---- +def total_damage(*hits): + return sum(hits) + +print(total_damage(5, 10, 3)) # -> 18 +print(total_damage(5, 10, 3, 20)) # -> 38 +print(total_damage()) # -> 0 +---- + +That single `+++*+++` in front of `hits` tells Python: "scoop up *any* number of extra positional arguments, and gather them together." And gather them into what, exactly? A *tuple* - the very thing we covered a couple chapters back. + +[source] +---- +def show_me(*hits): + print(type(hits)) + print(hits) + +show_me(5, 10, 3) +# output is +# +# (5, 10, 3) +---- + +Since it's just a tuple, everything you already know about tuples - indexing, slicing, looping over it - works on `+++*args+++` too. You can also mix `+++*args+++` with regular parameters, as long as the regular ones come first. + +[source] +---- +def introduce_party(leader, *members): + print(leader, "is leading the party.") + for member in members: + print(member, "is along for the ride.") + +introduce_party("Sam", "Jade", "Sadie", "Marcus") +# output is +# Sam is leading the party. +# Jade is along for the ride. +# Sadie is along for the ride. +# Marcus is along for the ride. +---- + +NOTE: The name `args` is just a convention, not a rule - you could call it `+++*hits+++` or `+++*members+++` or `+++*anything_you_want+++`. It's the single `+++*+++` in front that makes it special to Python, not the word "args" itself. + +=== Accepting Any Number of Keyword Arguments: `+++**kwargs+++` + +`+++**kwargs+++` is a close cousin of `+++*args+++`, except instead of gathering up a bunch of unnamed positional arguments, it gathers up *named* ones - the `key=value` style of arguments - into a dictionary. + +[source] +---- +def build_character(**traits): + for key, value in traits.items(): + print(key, "->", value) + +build_character(name="Katniss", district=12, weapon="bow") +# output is +# name -> Katniss +# district -> 12 +# weapon -> bow +---- + +Just like `+++*args+++` gathers extras into a tuple, `+++**kwargs+++` gathers extras into a dictionary - which is why we can loop over it with `.items()`, exactly like we learned in the Dictionaries chapter. + +[source] +---- +def show_me(**traits): + print(type(traits)) + print(traits) + +show_me(name="Katniss", district=12) +# output is +# +# {'name': 'Katniss', 'district': 12} +---- + +Again, `kwargs` is just a common convention for the name - the double `**` is what actually matters to Python. + +=== Putting It All Together + +You can combine regular parameters, default parameters, `+++*args+++`, and `+++**kwargs+++` in a single function - but Python insists they show up in this order: regular parameters first, then defaults, then `+++*args+++`, then `+++**kwargs+++` last. + +[source] +---- +def cast_spell(caster, spell="fireball", *targets, **effects): + print(caster, "casts", spell, "on", targets) + for effect, value in effects.items(): + print(" ", effect, "->", value) + +cast_spell("Gandalf", "lightning bolt", "Orc1", "Orc2", damage=50, stun=True) +# output is +# Gandalf casts lightning bolt on ('Orc1', 'Orc2') +# damage -> 50 +# stun -> True +---- + +You won't need all four at once very often, but now you'll recognize each piece when you see it. + +[TIP] +==== +* Write a function `order_donuts(customer, *flavors, **extras)` +* `customer` is a required, regular parameter +* `+++*flavors+++` should collect any number of donut flavor names +* `+++**extras+++` should collect optional named details, like `sprinkles=True` or `dozen=True` +* Call it a few different ways, and print out everything the function received +==== + +Between default values, `+++*args+++`, and `+++**kwargs+++`, your functions can now flex to fit however they're called, instead of demanding one rigid, fixed shape every time. diff --git a/functions.adoc b/functions.adoc index 4237e66..8091708 100644 --- a/functions.adoc +++ b/functions.adoc @@ -26,39 +26,39 @@ You end up with a function named 'add' that takes two parameters and adds them, [source] ---- -def greetUser(username): +def greet_user(username): print( "Hello " + username) return # calling/Invoking the function -greetUser("Mike Jones"); # "Hello Mike Jones" +greet_user("Mike Jones"); # "Hello Mike Jones" ---- === Invoking Functions Functions are meant to be _invoked_. So you can have one function call another function which calls a third function and so on; it's very common. -Imagine we have a program that gets an airplane ready for flight. We can imagine a whole series of functions we'd have to write. Things like 'loadPassengers', 'loadBaggage', 'loadFuel', 'checkTirePressures', and so on. Then we might have a 'higher level' functions which brings all these pieces together: +Imagine we have a program that gets an airplane ready for flight. We can imagine a whole series of functions we'd have to write. Things like 'load_passengers', 'load_baggage', 'load_fuel', 'check_tire_pressures', and so on. Then we might have a 'higher level' functions which brings all these pieces together: [source] ---- -def prepFlight(airplane): - loadBaggage(airplane) - loadPassengers(airplane) +def prep_flight(airplane): + load_baggage(airplane) + load_passengers(airplane) - loadFuel(airplane) - performPreflightChecklist(airplane[copilot]) - askTowerToDepart(airplane[pilot]) - departGate(airplane) + load_fuel(airplane) + perform_preflight_checklist(airplane[copilot]) + ask_tower_to_depart(airplane[pilot]) + depart_gate(airplane) - taxiToRunway(airplane, mainRunway90) + taxi_to_runway(airplane, main_runway_90) takeoff(airplane[pilot], airplane) return ---- -You can see how functions you perform different things in a particular order, and while you might have no idea _how_ 'loadBaggage' does what it does, you can see how the program preps the airplane object for flight and makes sure everything important is done. Each of the functions from 'loadBaggage' to 'takeoff' is invoked and returns so the next one can be invoked. This is the power of functions - the ability to take some code and put it a function so that it much easier to understand. +You can see how functions you perform different things in a particular order, and while you might have no idea _how_ 'load_baggage' does what it does, you can see how the program preps the airplane object for flight and makes sure everything important is done. Each of the functions from 'load_baggage' to 'takeoff' is invoked and returns so the next one can be invoked. This is the power of functions - the ability to take some code and put it a function so that it much easier to understand. === Lambda Functions @@ -86,10 +86,10 @@ Once Python reaches a return statement, the function will stop executing. Functi [source] ---- -def greetUser(username): +def greet_user(username): return "Hello " + username -result = greetUser("Welcome back, Mike Jones") +result = greet_user("Welcome back, Mike Jones") print(result); # will print "Hello Welcome back, Mike Jones" ---- @@ -97,7 +97,7 @@ Or like this: [source] ---- -def determineWinner(home, visitor): +def determine_winner(home, visitor): if (home[score] > visitor[score]): return "Home Team Wins! Let's have a Parade!" elif (home[score] < visitor[score]): @@ -121,10 +121,10 @@ visitor = { 'score': 0 } -playGame(home, visitor) # a lot of work done in this function(!) +play_game(home, visitor) # a lot of work done in this function(!) # game is done -result = determineWinner(home, visitor) +result = determine_winner(home, visitor) # and then print the result.. print(result) @@ -136,10 +136,10 @@ As you just saw, functions can also take parameters to be used within a function [source] ---- -def addThreeNumbers(a, b, c): +def add_three_numbers(a, b, c): return (a + b + c) -def determineWinner(home, visitor): +def determine_winner(home, visitor): if (home['score'] > visitor['score']): return "Home Team Wins! Let's have a Parade!"; elif (home['score'] < visitor['score']): @@ -147,7 +147,7 @@ def determineWinner(home, visitor): return "It's a Tie!" -def makeNegative(number): +def make_negative(number): if (number > 0): return -(number) # already negative, it's less than 0 @@ -177,7 +177,7 @@ Try to write a function that will perform the following requirements: [TIP] ==== -* Create a function called zipCoder +* Create a function called zip_coder * Your function takes one parameter of type number * Your function checks and does the following * If parameter is divisible by 3 and 5 (15). Print ZipCoder @@ -207,15 +207,15 @@ Well, here's one solution: ---- # Function ZipCoder -def zipCoder(aNumber): - if (aNumber % 15 == 0): +def zip_coder(a_number): + if (a_number % 15 == 0): print("ZipCoder") - elif (aNumber % 3 == 0): + elif (a_number % 3 == 0): print("Zip") - elif (aNumber % 5 == 0): + elif (a_number % 5 == 0): print("Coder") -zipCoder(45) # -> ZipCoder +zip_coder(45) # -> ZipCoder ---- diff --git a/generators.adoc b/generators.adoc new file mode 100644 index 0000000..7a19679 --- /dev/null +++ b/generators.adoc @@ -0,0 +1,137 @@ + + +== Generators + +That `Countdown` class from the last chapter worked, but notice how much ceremony it took: a `+++__init__+++` to set up state, a `+++__iter__+++` that just returned `self`, and a `+++__next__+++` that had to manually track `self.current` and remember to raise `StopIteration` at exactly the right moment. That's a lot of bookkeeping for something as simple as "count down from 3 to 0." Python has a much shorter way to write the same thing, called a *generator*. + +=== A Simpler Way: The `yield` Keyword + +Here's `Countdown`, rewritten as a plain function: + +[source] +---- +def countdown(start): + current = start + while current >= 0: + yield current + current -= 1 + +for count in countdown(3): + print(count) + +# output is +# 3 +# 2 +# 1 +# 0 +---- + +Same result, in a fraction of the code, and no class in sight. The magic word is `yield`. The moment a function contains `yield` anywhere in its body, Python treats it completely differently from a regular function - it becomes a *generator function*. + +=== What `yield` Actually Does + +When you call `countdown(3)`, the function body *doesn't run yet*. Instead, you get back a special generator object - one that already knows how to act as an iterator, with `+++__iter__+++` and `+++__next__+++` built in for you automatically. No writing those dunders yourself; Python hands you a working iterator just by seeing `yield` in your function. + +Each time something calls `next()` on it, the function runs until it hits `yield`, hands back that value, and then *pauses* - completely frozen, remembering every local variable exactly as it was. The next time `next()` is called, it picks up right where it left off, continuing the loop, right after that `yield` line. + +[source] +---- +def countdown(start): + current = start + while current >= 0: + yield current + current -= 1 + +counter = countdown(2) + +print(next(counter)) # -> 2 +print(next(counter)) # -> 1 +print(next(counter)) # -> 0 +print(next(counter)) # -> StopIteration +---- + +When the function finally falls off the end (here, once the `while` condition goes false), Python automatically raises `StopIteration` for you too - just like the manual iterator from last chapter, except you never had to write that part yourself. + +=== Generators Are Lazy (In a Good Way) + +Here's the real payoff. A list comprehension builds its *entire* result, all at once, sitting in memory. + +[source] +---- +squares = [x * x for x in range(1000000)] +---- + +That line immediately creates a list with a million numbers in it, whether you ever use all of them or not. A generator, on the other hand, produces values *one at a time, only when asked*. Nothing gets computed until `next()` actually calls for it. + +[source] +---- +def squares_up_to(limit): + x = 0 + while x < limit: + yield x * x + x += 1 + +for square in squares_up_to(1000000): + if square > 100: + break + print(square) +---- + +Even though `squares_up_to` could technically go all the way to a million, we only ever computed the handful of squares we actually printed before `break` stopped things. This "produce only what's needed, only when it's needed" behavior is called being *lazy*, and it can save a serious amount of memory and time once your data gets large. + +=== Generator Expressions + +Remember comprehensions? Generators have their own version of that shorthand too, called a *generator expression* - it looks just like a list comprehension, but with parentheses instead of square brackets. + +[source] +---- +squares = (x * x for x in range(1000000)) + +print(type(squares)) # -> +---- + +Nothing gets computed yet - `squares` is just a generator, waiting patiently to be asked for values. You can loop over it like anything else iterable: + +[source] +---- +squares = (x * x for x in range(5)) + +for square in squares: + print(square) + +# output is +# 0 +# 1 +# 4 +# 9 +# 16 +---- + +You'll often see a generator expression used directly inside a function call, with the parentheses left off entirely. + +[source] +---- +total = sum(x * x for x in range(1000000)) +print(total) +---- + +That computes the sum of a million squares without ever holding all million of them in memory at the same time - each one gets produced, added to the running total, and thrown away, one at a time. + +[TIP] +==== +* Rewrite the `HealthDrain` class from the last chapter's exercise as a generator function using `yield` +* Compare how many lines it took as a class versus as a generator function +* Then write a generator expression that produces the squares of only the *even* numbers from 0 to 20 +==== + +=== Iterators and Generators, Side by Side + +[cols=",,",options="header",] +|=== +| |Iterator (a class) |Generator (a function) +|How you build one |Write `+++__init__+++`, `+++__iter__+++`, `+++__next__+++` |Write a function using `yield` +|State tracking |You manage it yourself, on `self` |Python remembers it for you automatically +|Typical amount of code |More |Much less +|=== + +Both approaches produce the exact same thing from the outside - something you can hand to a `for` loop, or to `next()`, one value at a time. Now that you've built one the hard way with a class, and the easy way with `yield`, you'll recognize both wherever they show up in real Python code - and you'll almost always reach for `yield`. diff --git a/if.adoc b/if.adoc index f8aa461..b407470 100644 --- a/if.adoc +++ b/if.adoc @@ -2,42 +2,43 @@ == Conditional Statements We have been seeing programs which consist of a list of statements, one after another, where the "flow of control" goes from one line to the next, top to bottom, and so on to the end of the list of lines. + There are more useful ways of breaking up the "control flow" of a program. Python has several conditional statements that the programmer do things based on conditions in the data. === If statement -The first conditional statement is the *if* statement. +The first conditional statement is the *if* statement. [source] ---- if (something-is-true): - doSomething() + do_something() ---- Here are a few simple examples. [source] ---- -if (speed > speedLimit) : - driver.getsATicket() +if (speed > speed_limit) : + driver.gets_a_ticket() if (x <= -1) : print("Cannot have negative numbers!") -if (account.balance >= amountRequested) : - subtract(account, amountRequested) - produceCash(amountRequested) - printReceipt(amountRequested) +if (account.balance >= amount_requested) : + subtract(account, amount_requested) + produce_cash(amount_requested) + print_receipt(amount_requested) ---- -Python also has an *else* part to the *if* statement. When the *if* condition is False, the else part gets run. Here, if the account doesn't have enough money to fulfill the amountRequested, the else part of the statement gets run, and the customer gets an insufficient funds receipt. +Python also has an *else* part to the *if* statement. When the *if* condition is False, the else part gets run. Here, if the account doesn't have enough money to fulfill the amount_requested, the else part of the statement gets run, and the customer gets an insufficient funds receipt. [source] ---- -if (account.balance >= amountRequested): +if (account.balance >= amount_requested): # customer has the money else: - printReceipt("Sorry, you don't have enough money in your account!") + print_receipt("Sorry, you don't have enough money in your account!") ---- Python can also "nest" if statements, making them very flexible for complicated situations. You can also see here how the `elif` works. @@ -45,22 +46,22 @@ There can be zero or more `elif` parts, and the `else` part is optional. [source] ---- -timeOfDay = "Afternoon" +time_of_day = "Afternoon" -if (timeOfDay === "Morning"): +if (time_of_day === "Morning"): print("Time to eat breakfast") - eatCereal() -elif (timeOfDay === "Afternoon"): + eat_cereal() +elif (time_of_day === "Afternoon"): print("Time to eat lunch") - haveASandwich() + have_a_sandwich() else: print("Time to eat dinner") - makeDinner() - eatDinner() - doDishes() + make_dinner() + eat_dinner() + do_dishes() ---- -Notice how this becomes a 3-way choice, depending on the timeOfDay. +Notice how this becomes a 3-way choice, depending on the time_of_day. [TIP] ==== @@ -76,10 +77,10 @@ Finally, make sure to change the value of the age variable in the repl, to outpu [source] ---- -userAge = 17 -if userAge < 18: +user_age = 17 +if user_age < 18: print("Cannot party with us") -elif userAge >= 18: +elif user_age >= 18: print("Party over here") else: print("I do not recognize your age") diff --git a/index.adoc b/index.adoc index 0d8f2e9..9fc4567 100644 --- a/index.adoc +++ b/index.adoc @@ -1,7 +1,7 @@ :title-page: = Zip Code Wilmington's Programming in Python Kristofer Younger -v1.1.6, 2023-09-05 +v2.0.3, 2026-09-28 :doctype: book :imagesdir: images :pdf-theme: pypreptheme.yml @@ -9,8 +9,8 @@ v1.1.6, 2023-09-05 :rouge-style: github :source-language: python :icons: font -:homepage: https://zipcodewilmington.com/pyprep -:pdf-page-size: [5.5in, 8.5in] +:homepage: https://zipcodewilmington.com +:pdf-page-size: [7.0in, 9.0in] :toc: [colophon] @@ -19,32 +19,31 @@ v1.1.6, 2023-09-05 Zip Code Wilmington's Programming in Python by Kristofer Younger -Copyright (C) 2020 - 2023 by Zip Code Wilmington. All Rights Reserved. - -Cover Design: Janelle Bowman +Copyright (C) 2020 - 2027 by Zip Code Wilmington. All Rights Reserved. Published in the U.S.A. May 2021: First Edition +October 2026: Second Edition While the publisher and author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. -Use of the information and instructions in this work is at your own risk. If any code samples or other information this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. +Use of the information and instructions in this work is at your own risk. If any code samples or other information this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. [preface] == Preface This book is a cousin of the same text for JavaScript. Many of the Java programmers we've trained at ZipCodeWilmington look at Python as a possible second 'main' language, one that'd be good to pick up and have on the resume. I'd agree. Python has been good to me, as I first learned it when I got back into coding about 2007, I've written a *lot* of python, and consider it an old friend. -I especially wish to thank Mikaila Akeredolu: without his brilliant javascript prep session slides as the starting point for the javascript version of this book, I would never have thought a small book on the basic fundamentals of programming would be possible or even useful. +I especially wish to thank Mikaila Akeredolu: without his brilliant javascript prep session slides as the starting point for the javascript version of this book, I would never have thought a small book on the basic fundamentals of programming would be possible or even useful. Zip Code Wilmington is a non-profit coding boot-camp in Delaware for people who wish to change their lives by becoming proficient at coding. Find out more about us at https://zipcodewilmington.com == About this book -This book's aim is to provide you with the most basic of fundamentals regarding Python, one of the most popular programming languages available. -It springs from the Javascript preparation sessions we often give prospective Zip Code applicants on how to do well on the Zip Code application coding assessment. -To someone who has spent some time with programming languages, this might be just a breezy intro to Python. +This book's aim is to provide you with the most basic of fundamentals regarding Python, one of the most popular programming languages available. +It springs from the Javascript preparation sessions we often give prospective Zip Code applicants on how to do well on the Zip Code application coding assessment. +To someone who has spent some time with programming languages, this might be just a breezy intro to Python. If you have almost any serious coding experience, this book is probably too elementary for you. You might, however, find the ideas in the Appendices interesting. There I've added some material that have a few advanced ideas in them, plus there is a full code listing of a Mars Lander simulation. @@ -61,45 +60,45 @@ Python also has the advantage that one can learn to use it without a lot of setu ==== Focuses on coding -Finally, because in this book all we aim to teach you is "programming in the small", Python is great for that. Many of the examples here are significantly less that 20 lines in length. We want you to get better at looking at small blocks of code to see how they work. These smaller examples and concepts are a core building block as you become proficient in coding. +Finally, because in this book all we aim to teach you is "programming in the small", Python is great for that. Many of the examples here are significantly less that 20 lines in length. We want you to get better at looking at small blocks of code to see how they work. These smaller examples and concepts are a core building block as you become proficient in coding. ==== You'll learn it eventually -The truth is, in today's coding world, all of us eventually learn to do things with Python. (I've said this about JavaScript too.) +The truth is, in today's coding world, all of us eventually learn to do things with Python. (I've said this about JavaScript too.) And as of 2023, it's perhaps the world's most popular programming language. -So, start early, get comfortable with it, and then go on and study other computer languages like Java or JavaScript. -Python will always be there, waiting patiently for you to return. +So, start early, get comfortable with it, and then go on and study other computer languages like Java or JavaScript. +Python will always be there, waiting patiently for you to return. And hey, if you've already learned Java, you might find this book helpful - bridging languages is a great skill for a developer to have. -=== Coding _The Hard Way_. +=== Coding _The Hard Way_. Zed A. Shaw is a popular author of several books where he describes learning a programming language _The Hard Way_. Zed suggests, and we at Zip Code agree with him whole-heartedly, that the best, most impactful, highest return for your investment when learning to code, is *type the code using your own fingers* footnote:[check out his terrific work: https://learncodethehardway.org] That's right. Whether you are a "visual learner", a "video learner", or someone who can read textbooks like novels (are there any more of these out there?), the best way to learn to code is *to code* and *to code by typing out the code with your own fingers*. This means you DO NOT do a lot of copy and paste of code blocks; you really put in the work, making your brain better wired to code by *coding with your own typing of the code.* -You're here, reading this, because you're thinking (or maybe you know) that you want to become a coder. It's pretty straight-forward. +You're here, reading this, because you're thinking (or maybe you know) that you want to become a programmer. It's pretty straight-forward. You may have heard a friend wistfully dream of making a career at writing. "Oh," they say, "I wish I had time to write a great novel, I want to be a writer someday". -So you can ask them: Did you write _today_? _How many words?_ +So you can ask them: Did you write _today_? _How many words?_ And the excuses flow: "Oh, I have to pick up the kids" "Ran out of time, I'm so busy at work." "I had to cut the grass" and so on. Well, I'm here to tell you that all the excuses in the world don't stop a real writer from writing. They just sit down and do it. As often as they can, sometimes even when they can't (or shouldn't). -Coding, like writing, isn't something you can do when all your other chores, obligations, and entertainments are done. If you're serious about learning coding, you must make time for coding. +Coding, like writing, isn't something you can do when all your other chores, obligations, and entertainments are done. If you're serious about learning coding, you must make time for coding. -Watching hours of YouTube videos _will not_ make you a coder. +Watching hours of YouTube videos _will not_ make you a programmer. -Reading dozens of blog posts, Medium articles, and books _will not_ make you a coder. +Reading dozens of blog posts, Medium articles, and books _will not_ make you a programmer. -Following along with endless step-by-step tutorials _will not_ make you a coder. +Following along with endless step-by-step tutorials _will not_ make you a programmer. -The only way you're going to learn to code is by doing it. Trying to solve a problem. Making mistakes, fixing them, learning from what worked and what didn't at the keyboard. +The only way you're going to learn to code is by doing it. Trying to solve a problem. Making mistakes, fixing them, learning from what worked and what didn't at the keyboard. -Many have heard my often-repeated admonition: *If you coded today, you're a coder. If not, you're not a coder.* It really is as simple as that. +Many have heard my often-repeated admonition: *If you coded today, you're a programmer. If not, you're not a programmer.* It really is as simple as that. === Dedication to the mission -I happen to be among those who feel anyone can learn to code. It's a 21st century superpower. When you code, you can change the world. Being proficient at coding can be a life-changing skill that impacts your life, your family's life and your future forever. +I happen to be among those who feel anyone can learn to code. It's a 21st century superpower. When you code, you can change the world. Being proficient at coding can be a life-changing skill that impacts your life, your family's life and your future forever. Time and time again, I've seen that the ability to learn to code is evenly distributed across the population, but the _opportunity to learn to code is not_. So, we run Zip Code to give people a shot at learning a 21st century superpower, no matter where you come from. And fortune favors the prepared. Some day, you may be working at a great company, making a decent living, working with professionals in a great technical job. Your friends may say "You are so lucky!" @@ -108,16 +107,16 @@ And you will think: *Nope. It wasn't luck.* You'll know that truly. You got ther As many know, getting a spot in a Zip Code cohort is a hard thing to do. Many try but only a few manage it. I often get asked "what can I do to prepare to get into Zip Code?" -The best way is to start solving coding problems on sites like https://hackerrank.com - HackerRank (among others) has many programming assignments, from extremely simple to very advanced. You login, and just do exercise after exercise, relieving you of one of the hardest of coding frustrations, that of trying to figure out *what* to code. Solving programming assignments is a good way to start to cultivate a coding mindset. Such a mindset is based on your ability to pay very close attention to detail, a desire to continually learn, and being able to stay focused on problem solving even if it takes a lot of grit and dedication. +The best way is to start solving coding problems on sites like https://hackerrank.com - HackerRank (among others) has many programming assignments, from extremely simple to very advanced. You login, and just do exercise after exercise, relieving you of one of the hardest of coding frustrations, that of trying to figure out *what* to code. Solving programming assignments is a good way to start to cultivate a coding mindset. Such a mindset is based on your ability to pay very close attention to detail, a desire to continually learn, and being able to stay focused on problem solving even if it takes a lot of grit and dedication. Spending even 20 minutes a day, making progress on a programming task can make all the difference. Day after day your skills will grow, and before long you'll look back on the early things you did and be astonished as to how simple the assignments were. You may even experience embarrassment at remembering how hard these simple exercises seemed at the time you did them. (It's okay, we've all felt it. It's part of the gig.) -Working on code every day makes you a coder. And coding everyday will help with your ability to eventually score high enough on the Zip Code admissions assessment that you get asked to group and potentially final interviews. And then, well, then you get to learn Java or Python and work yourself to exhaustion doing so. Lots and lots more hours. +Working on code every day makes you a programmer. And coding everyday will help with your ability to eventually score high enough on the Zip Code admissions assessment that you get asked to group and potentially final interviews. And then, well, then you get to learn Java or Python and work yourself to exhaustion doing so. Lots and lots more hours. -Why? +Why? -You do that hard work, you put in those hours, you create lots of great code, -you'll make your own luck, and someone will be impressed and they will offer you a job. +You do that hard work, you put in those hours, you create lots of great code, +you'll make your own luck, and someone will be impressed and they will offer you a job. And that is the point, right? A job, doing what you love, coding. Right? RIGHT? You're Welcome, @@ -126,7 +125,7 @@ _-Kristofer_ Ready? -Okay, let's go. +Okay, let's go. :sectnums: @@ -173,14 +172,50 @@ include::return.adoc[] include::dictionary.adoc[] +include::sets.adoc[] + +include::tuples.adoc[] + +include::functionparams.adoc[] + +include::typehints.adoc[] + +include::builtins.adoc[] + +include::lambdas.adoc[] + +include::builtinsadvanced.adoc[] + +include::listcomprehension.adoc[] + +include::dictcomprehension.adoc[] + +include::setcomprehension.adoc[] + include::modules.adoc[] +include::runvsimport.adoc[] + include::objectsmethods.adoc[] +include::dundermethods.adoc[] + +include::iterators.adoc[] + +include::generators.adoc[] + +include::mixins.adoc[] + include::appendixa.adoc[] include::appendixb.adoc[] +include::appendixc.adoc[] + +include::appendixd.adoc[] + +include::appendixe.adoc[] + [appendix] == Additional Python Resources @@ -193,4 +228,3 @@ Some Python sites for you to explore: If you're looking for more of a professional code tool, use an IDE like vscode: https://code.visualstudio.com (Many people use this these days.) It has all sorts of tools to help you create Python programs. - diff --git a/iterators.adoc b/iterators.adoc new file mode 100644 index 0000000..ca01b31 --- /dev/null +++ b/iterators.adoc @@ -0,0 +1,105 @@ + + +== Iterators + +Back in the Loops chapter, we introduced the word *iterable* - anything a `for` loop knows how to walk through, one item at a time. We've used plenty of iterables since then: lists, strings, ranges, dictionaries, sets, tuples. Now that you know classes and dunder methods, we can finally open the hood and see exactly what makes something iterable in the first place. + +=== Iterable vs. Iterator + +These two words look almost identical, and that trips people up, so let's be precise: + +* An *iterable* is anything you *can* loop over - a list, a string, a range. +* An *iterator* is the actual object doing the walking - it remembers exactly where it currently is, and knows how to fetch the *next* item. + +Here's the relationship: an iterable doesn't walk itself. When a `for` loop wants to walk through one, it first asks the iterable for an iterator, and *that* iterator is what actually keeps track of position and hands back values, one at a time. + +=== Getting an Iterator by Hand + +You can do this yourself, without a `for` loop at all, using two built-in functions: `iter()` and `next()`. + +[source] +---- +donut_flavors = ["chocolate", "glazed", "jelly"] + +flavor_iterator = iter(donut_flavors) + +print(next(flavor_iterator)) # -> chocolate +print(next(flavor_iterator)) # -> glazed +print(next(flavor_iterator)) # -> jelly +---- + +`iter()` takes an iterable and hands you back its iterator. Each call to `next()` moves that iterator forward by one and gives you the next value. What happens if you call `next()` one time too many, once there's nothing left? + +[source] +---- +print(next(flavor_iterator)) +# StopIteration +---- + +Python raises a `StopIteration` error. That's not really a "problem" - it's the iterator's official way of saying "I'm out of items, we're done here." + +=== What a `for` Loop Is Really Doing + +Here's the secret: a `for` loop is just doing exactly what we did above, automatically, and quietly catching `StopIteration` for you so your program doesn't crash. + +[source] +---- +donut_flavors = ["chocolate", "glazed", "jelly"] + +flavor_iterator = iter(donut_flavors) + +while True: + try: + flavor = next(flavor_iterator) + except: + break + print(flavor) +---- + +That clunky `while True` / `try` / `except` mess is precisely what `for donut in donut_flavors:` is doing behind the scenes, every single time you write it. This is why `for` works identically on a list, a string, a dictionary, or anything else iterable - they all agree to answer `iter()` and `next()` the same way, so `for` never needs to know or care what kind of thing it's actually looping over. + +=== Making Your Own Class Iterable + +Since `+++__iter__+++` and `+++__next__+++` are just two more dunder methods, you can add them to any class you write, and suddenly a `for` loop will work on your own objects too. + +[source] +---- +class Countdown: + def __init__(self, start): + self.current = start + + def __iter__(self): + return self + + def __next__(self): + if self.current < 0: + raise StopIteration + value = self.current + self.current -= 1 + return value + +for count in Countdown(3): + print(count) + +# output is +# 3 +# 2 +# 1 +# 0 +---- + +Let's break down the two dunders doing the work here: + +* `+++__iter__+++` needs to return *an iterator* - here, we just return `self`, since our `Countdown` object is perfectly capable of tracking its own position and handing back its own next value. +* `+++__next__+++` does the real work: it computes the next value, and once there's nothing left to give, it raises `StopIteration` itself, exactly like the built-in iterators did. + +Because `Countdown` defines both, Python's `for` loop is happy to walk right through it, exactly like it would a list or a range. + +[TIP] +==== +* Write a class `HealthDrain` that starts a player at some health value and counts *down by 5* each time, stopping once health reaches 0 +* Give it `+++__init__+++`, `+++__iter__+++`, and `+++__next__+++` +* Use it in a `for` loop and print each health value along the way +==== + +All of this - `iter()`, `next()`, `StopIteration`, `+++__iter__+++`, `+++__next__+++` - is the real machinery under every `for` loop you've ever written. It's a little bit of ceremony to write by hand, though. In the next chapter, we'll meet *generators* - Python's much shorter way to build your own iterator, without writing a whole class at all. diff --git a/lambdas.adoc b/lambdas.adoc new file mode 100644 index 0000000..dde1d04 --- /dev/null +++ b/lambdas.adoc @@ -0,0 +1,122 @@ + + +== Lambdas + +Back in the Functions chapter, you got a quick glimpse of something called a *lambda*. Let's slow down and really look at it, because you're about to see lambdas everywhere, especially in the next chapter. + +=== What Is a Lambda? + +A lambda is just a *function without a name*. That's really it. It's a small, one-line function you can write right where you need it, without going through the whole `def` ceremony. + +[source] +---- +double = lambda x: x * 2 + +print(double(5)) # -> 10 +---- + +Compare that to writing it the regular way: + +[source] +---- +def double(x): + return x * 2 + +print(double(5)) # -> 10 +---- + +Same result. The lambda version is just shorter - one line instead of two, no `def`, no `return`. Python quietly adds the `return` for you; whatever the expression evaluates to is automatically handed back. + +=== The Lambda Recipe + +Every lambda follows the same simple pattern: + +[source] +---- +lambda parameters: expression +---- + +* `lambda` - the keyword that says "I'm making a tiny function" +* `parameters` - whatever inputs it needs, just like a normal function (zero, one, or several) +* `expression` - one single calculation, whose result gets returned automatically + +[source] +---- +add2 = lambda p1, p2: p1 + p2 +print(add2(5, 7)) # -> 12 + +shout = lambda word: word.upper() + "!" +print(shout("watch out")) # -> WATCH OUT! + +always_true = lambda: True +print(always_true()) # -> True +---- + +Notice there's no name for the function itself in the `lambda` line - that's the "anonymous" part. We only gave it a name (`add2`, `shout`) by assigning it to a variable, the same way we'd name any other value. + +=== Why Bother? + +Fair question. If `def` already works, why does Python give you a second way to write functions? + +The honest answer: *lambdas exist for quick, throwaway functions you only need for a moment*, usually because some other function needs a little function handed to it as an argument. Writing out a whole `def`, giving it a name you'll never reuse, just to use it once, is a lot of ceremony for a one-off job. + +Think about `sorted()`, which you met in the Built-in Functions chapter. By default it sorts numbers and strings in their normal order. But what if we want to sort a list of players by their health score, where each player is a dictionary? + +[source] +---- +players = [ + {"name": "Sam", "health": 42}, + {"name": "Jade", "health": 100}, + {"name": "Sadie", "health": 87}, +] + +ranked = sorted(players, key=lambda player: player["health"]) + +for p in ranked: + print(p["name"], p["health"]) + +# output is +# Sam 42 +# Sadie 87 +# Jade 100 +---- + +That `key=lambda player: player["health"]` is telling `sorted()` exactly *what to look at* on each player when deciding the order. We needed a tiny function just for this one call - we're never going to reuse "look up a player's health" anywhere else in the program. A lambda lets us hand that logic straight to `sorted()` without ever giving it a name. + +=== The Catch + +Lambdas are deliberately limited, and that's on purpose: + +* A lambda can only hold *one expression* - no `if` statements with multiple lines, no loops, no several lines of logic. +* A lambda always returns the result of that one expression - you never write the word `return` yourself. +* If what you're trying to do needs more than a single simple calculation, that's Python's way of telling you: *just write a regular function with `def` instead.* + +[source] +---- +# fine for a lambda - one simple expression +square = lambda x: x * x + +# too much for a lambda - write a real function instead +def grade_test(score): + if score >= 90: + return "A" + elif score >= 80: + return "B" + else: + return "C" +---- + +Trying to cram the `grade_test` logic into a lambda would just make your code harder to read, which defeats the entire purpose of using one. + +[TIP] +==== +* Write a lambda called `is_even` that takes a number and returns `True` if it's even +* Try it with a couple of numbers, printing the result each time +* Now write the same thing as a regular `def` function, and compare how each one reads +==== + +=== A Quick Rule of Thumb + +Use a `def` function when you're naming something you'll call again, or when the logic takes more than one line to express. Reach for a `lambda` when you need a tiny, use-once function, usually as an argument being passed straight into something else, like `sorted()`. + +Keep that rule of thumb in mind, because in the next chapter, you're going to see lambdas paired constantly with two more built-in functions: `map()` and `filter()`. diff --git a/listcomprehension.adoc b/listcomprehension.adoc new file mode 100644 index 0000000..862d5a5 --- /dev/null +++ b/listcomprehension.adoc @@ -0,0 +1,111 @@ + + +== List Comprehensions + +Remember `map()` and `filter()` from the last chapter? They're powerful, but let's be honest - wrapping everything in `list(map(...))` and `list(filter(...))` gets a little wordy. Python has a shorter, more popular way to do the exact same jobs, called a *list comprehension*. + +=== Building a List the Old Way + +Let's go back to our dungeon game. We want to double every player's health score, the same problem we solved with `map()` last chapter. + +[source] +---- +player_health_scores = [100, 87, 42] + +boosted_scores = [] +for score in player_health_scores: + boosted_scores.append(score + 10) + +print(boosted_scores) # -> [110, 97, 52] +---- + +Four lines just to build a new list. Nothing wrong with it, but Python programmers found themselves typing this same shape - "make an empty list, loop over something, append a transformed value" - so often that they built a shortcut right into the language. + +=== The List Comprehension Way + +Here's the exact same result, in one line: + +[source] +---- +player_health_scores = [100, 87, 42] + +boosted_scores = [score + 10 for score in player_health_scores] + +print(boosted_scores) # -> [110, 97, 52] +---- + +That's a *list comprehension*. It follows this pattern: + +[source] +---- +[expression for item in iterable] +---- + +* `expression` - what you want to happen to each item, before it lands in the new list +* `item` - the name you're giving each thing as you pull it out, one at a time +* `iterable` - the list (or string, or range, or anything else you can loop over) you're pulling items from + +Read it out loud almost like English: "give me `score + 10`, *for* each `score` *in* `player_health_scores`." That's really all a list comprehension is - a `for` loop and an `append()`, squeezed into a single line, wrapped in square brackets. + +=== Filtering, Too + +Comprehensions can also do what `filter()` does - keep only the items that pass a test - by tacking an `if` onto the end. + +[source] +---- +player_health_scores = [100, 87, 0, 42, 0] + +survivors = [score for score in player_health_scores if score > 0] + +print(survivors) # -> [100, 87, 42] +---- + +The pattern grows just slightly: + +[source] +---- +[expression for item in iterable if condition] +---- + +Only items where `condition` comes out `True` get run through `expression` and added to the new list. Everything else gets skipped entirely. + +Here's one more, using our donut flavors: + +[source] +---- +donut_flavors = ["chocolate", "glazed", "jelly", "chocolate glaze"] + +chocolatey_ones = [flavor for flavor in donut_flavors if "chocolate" in flavor] + +print(chocolatey_ones) # -> ['chocolate', 'chocolate glaze'] +---- + +Compare that to the `filter()` version from the last chapter - same result, but no `lambda`, no `list()` wrapper needed. + +=== Combining Transform and Filter + +You can do both at once - transform *and* filter - in the very same comprehension. + +[source] +---- +player_health_scores = [100, 87, 0, 42, 0] + +boosted_survivors = [score + 5 for score in player_health_scores if score > 0] + +print(boosted_survivors) # -> [105, 92, 47] +---- + +Notice the order: the `if` at the end decides *who gets in*, and the expression at the front decides *what happens to them* once they're in. Zeros never even make it to the `+ 5` part. + +[TIP] +==== +* Start with a list of five donut prices +* Build a new list, using a comprehension, that adds 6% sales tax to each price +* Now build a second comprehension that only keeps the donuts priced under $2.00 (before tax) +==== + +=== map()/filter() or a Comprehension? + +Both do the same job. Most Python programmers reach for a list comprehension first, since it tends to read more clearly, especially once you're used to the pattern. `map()` and `filter()` aren't wrong, and you'll still see them out in the wild - now you'll recognize both styles when you run into them. + +Lists aren't the only thing you can build this way. Next up, we'll use this exact same idea to build dictionaries. diff --git a/lists.adoc b/lists.adoc index 17a77d4..f5fbfcd 100644 --- a/lists.adoc +++ b/lists.adoc @@ -8,24 +8,24 @@ Let's start with *why* we need them. Imagine you have a small number of things you want to track. Let's use our vague computer game we've been using for an example. The game has 5 players, friends that get together over the internet to play a dungeon game. -Now, if you're the coder of this game you could keep track of each player's healthScore by have 5 different variables. (for players Zero to Four) +Now, if you're the programmer of this game you could keep track of each player's health_score by have 5 different variables. (for players Zero to Four) [source] ---- -playerZeroHealthScore = 100 -playerOneHealthScore = 100 -playerTwoHealthScore = 100 -playerThreeHealthScore = 100 -playerFourHealthScore = 100 +player_zero_health_score = 100 +player_one_health_score = 100 +player_two_health_score = 100 +player_three_health_score = 100 +player_four_health_score = 100 ---- If we setup these 5 variables, our game can track 5 players! But *we'd have to change the game's code to track SIX players.* Well, that not good. Kind of silly actually. -To get around this kind of problem we use a *list*. We could ask, "how many players are playing?", and then make the list that size. We know we need to track each player's healthScore, so we create an list: +To get around this kind of problem we use a *list*. We could ask, "how many players are playing?", and then make the list that size. We know we need to track each player's health_score, so we create an list: [source] ---- -playerHealthScores = [100, 100, 100, 100, 100] +player_health_scores = [100, 100, 100, 100, 100] ---- Now, like a _string_, list indexes start at zero. @@ -33,7 +33,7 @@ Now, like a _string_, list indexes start at zero. [source] ---- # 0 1 2 3 4 -playerHealthScores = [100, 100, 100, 100, 100]; +player_health_scores = [100, 100, 100, 100, 100]; ---- This list is a *data structure* - a way for us to keep track of lots of data in a controlled fashion. @@ -42,25 +42,25 @@ If we need to deduct health points from one of the players, we can do something [source] ---- -majorHit = 50 +major_hit = 50 -playerHealthScores[2] = 67 # player 2 just took a hit! +player_health_scores[2] = 67 # player 2 just took a hit! -playerHealthScores[1] = 105 # player one is getting stronger. +player_health_scores[1] = 105 # player one is getting stronger. -playerHealthScores[3] = playerHealthScores[3] - majorHit +player_health_scores[3] = player_health_scores[3] - major_hit # the list now is [100, 105, 67, 0, 100] ---- The best way to think about a list is like all those postal boxes at the post office. Each box has a number on it, and things get put in the box depending on the box number. -Lists are *indexed* like that. Each list spot has an index number, starting at zero. See how we use the number 2 to _index_ into the playerHealthScore list? +Lists are *indexed* like that. Each list spot has an index number, starting at zero. See how we use the number 2 to _index_ into the player_health_score list? Lists: * Can store multiple values in a single variable * Start counting from index position zero -* Elements can be primitive data types or/and Objects +* Elements can be builtin data types or/and Objects So let's think about an list of donuts for the following examples. @@ -72,9 +72,9 @@ Declaring and initializing some lists in Python: ---- donuts = ["chocolate", "glazed", "jelly" -listofLetters = ['c','h','r','i','s'] +list_of_letters = ['c','h','r','i','s'] -mixedData = ['one', 2, True] # a string, a number and a boolean! +mixed_data = ['one', 2, True] # a string, a number and a boolean! ---- === Accessing elements of an List diff --git a/mixins.adoc b/mixins.adoc new file mode 100644 index 0000000..cdcb381 --- /dev/null +++ b/mixins.adoc @@ -0,0 +1,59 @@ + +== Mixins + +Sometimes several classes need the same small piece of behavior. You could copy the same methods into each class, but then a change to that behavior means editing every copy. A *mixin* lets you write that behavior once and add it to classes through inheritance. + +A mixin is usually a small class that provides a focused capability. It is not generally meant to represent a complete thing on its own. For example, a mixin can give different kinds of objects the ability to take damage: + +[source] +---- +class DamageMixin: + def take_damage(self, amount): + self.health = max(0, self.health - amount) + +class Spacecraft: + def __init__(self, name, health): + self.name = name + self.health = health +---- + +`DamageMixin` defines a method that uses `self.health`. It does not create or set up that attribute; the class using the mixin is responsible for providing it. + +=== Combining Behaviors + +To add the mixin's behavior to `Spacecraft`, list it as a parent class: + +[source] +---- +class DamageMixin: + def take_damage(self, amount): + self.health = max(0, self.health - amount) + +class RepairMixin: + def repair(self, amount): + self.health = min(self.max_health, self.health + amount) + +class Spacecraft(DamageMixin, RepairMixin): + def __init__(self, name, health): + self.name = name + self.health = health + self.max_health = health + +enterprise = Spacecraft("Enterprise", 100) +enterprise.take_damage(30) +print(enterprise.health) # -> 70 + +enterprise.repair(10) +print(enterprise.health) # -> 80 +---- + +`Spacecraft` gets both `take_damage()` and `repair()` without defining either method itself. `DamageMixin` and `RepairMixin` each contribute a separate behavior, while `Spacecraft` supplies the data those behaviors need. + +Mixins work best when they stay focused and have clear expectations about what the class using them provides. If multiple parent classes define methods with the same name, Python's method resolution order determines which one is used. For now, give each mixin its own methods and avoid name clashes. + +[TIP] +==== +* Create an `InventoryMixin` with an `add_item(item)` method +* Add it to a `Player` class that initializes an empty `inventory` list +* Create a player, add two items, and print the inventory +==== diff --git a/modules.adoc b/modules.adoc index e665af8..2ae4d5b 100644 --- a/modules.adoc +++ b/modules.adoc @@ -1,39 +1,108 @@ + == Modules -In Python, modules allow for code to loaded into a program only if it is needed. Modules are one of the advanced topics in Python that we won't spend too much time on, but here are the basics. +Every code example so far in this book has lived in one single file, or one single REPL session. That's fine while you're learning, but real programs grow. Once a program gets big enough, you don't want every function and variable crammed into one giant file - you want to split things up, and *reuse* code you already wrote instead of retyping it into every new program. + +That's exactly the problem *modules* solve. + +=== What Is a Module? + +Here's the good news: you've already been creating modules this whole time, without realizing it. *Any Python file you write is automatically a module.* If you save some code in a file named `greetings.py`, you now have a module named `greetings`, and any other Python file can borrow the things defined inside it. + +Let's make that real with two files. + +[source] +---- +def greet_user(username): + return "Hello, " + username + "!" +---- +_greetings.py_ + +That's our module - just a plain `.py` file with one function in it, sitting in the same folder as the program we're about to write. + +=== Importing a Module + +The first, most basic way to use another file's code is the plain `import` statement. + +[source] +---- +import greetings + +message = greetings.greet_user("Mike Jones") +print(message) # -> Hello, Mike Jones! +---- +_main.py_ + +Notice the pattern: `import greetings` loads up the whole `greetings.py` file, and then we reach *into* it using a dot, `greetings.greet_user(...)`, the same way we've been reaching into objects and their methods. This is a genuinely good habit to get into, because it's always crystal clear, just by reading the code, exactly *where* `greet_user` came from - it's right there in the name, `greetings.greet_user`. + +=== Importing Just What You Need + +Sometimes you don't want to type the module name every single time, especially if you're going to use a function over and over. That's what `from ... import ...` is for. + +[source] +---- +from greetings import greet_user + +message = greet_user("Mike Jones") +print(message) # -> Hello, Mike Jones! +---- +_main.py_ + +This time, we pulled `greet_user` directly into `main.py`, so we can call it plain, with no `greetings.` in front. Shorter to type, and often reads a little cleaner. + +You can even import several names from the same module this way, separated by commas. + +[source] +---- +from greetings import greet_user, greet_admin +---- + +NOTE: There's also a *from greetings import ** form, which grabs *everything* out of a module at once. It's tempting, but most Python programmers avoid it - once you've done that a few times from a few different modules, it gets hard to tell, just by looking at your code, which module any given function actually came from. -If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. -Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. -This is known as creating a script. -As your program gets longer, you may want to split it into several files for easier maintenance. -You may also want to use a handy function that you’ve written in several programs without copying its definition into each program. +=== Which Style Should You Use? -To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. -Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode). +Neither style is "wrong" - it's mostly a judgment call. -A module is a file containing Python definitions and statements. -The file name is the module name with the suffix .py appended. -Within a module, the module’s name (as a string) is available as the value of the global variable __name__. +* Use `import module_name` when you're using a few different things from that module, or when you like being able to see exactly where a function came from at a glance. +* Use `from module_name import name` when you only need one or two things from a module and you'll be using them a lot, and typing the module name every time would get repetitive. -Most of your Python programs are fairly small when you are creating solutions to HackerRank type problems. +Just be a little careful with the second style: if you `from` import a function named `greet_user` from _two different_ modules, the second import silently replaces the first one. `import module_name` never has that problem, since everything stays safely namespaced behind the module's name. + +=== Modules from Python's Standard Library + +Modules aren't just for files you write yourself. Python ships with a huge collection of modules already built in, ready for you to `import` - this is called the *standard library*. You've likely already seen the `math` module mentioned in passing; it works exactly the same way as our homemade `greetings` module. + +[source] +---- +import math + +print(math.sqrt(64)) # -> 8.0 +print(math.pi) # -> 3.141592653589793 +---- + +Or, using the second style: [source] ---- -print("Hello, World!"); +from math import sqrt, pi + +print(sqrt(64)) # -> 8.0 +print(pi) # -> 3.141592653589793 ---- -_helloworld.py_ -If your program is much larger, it might be split into different files to keep it all more organized or readable. -All those files might be kept in a folder all together, as a project. -But again, this is beyond what you need to know to do HackerRank Python problems. +Same functions, same values - just a different way of reaching for them. + +[TIP] +==== +* Create a file named `mathhelpers.py` with a function `double(number)` that returns `number * 2` +* In a second file, `import mathhelpers` and call `mathhelpers.double(21)` +* Now rewrite that second file using `from mathhelpers import double` instead, and call `double(21)` directly +* Notice both versions print the same answer, just written a little differently +==== -Modules are also used to import code others have written that you wish to take advantage of. -You've seen examples of this when we've used "import math" to get access to function definitions within the math module. -There are millions of chunks of Python you can find and use in your code. -A lot of it is used by many, many people, and it's important to know where the code you use comes from. -It can be dangerous to use someone else's code that isn't trustworthy. +=== A Word of Caution -See https://docs.python.org/3/tutorial/modules.html for more on modules! -Look for information on "import" to see how modules interact with your code. +Modules also let you import code that *other* people have written - there are millions of these floating around for Python, doing everything imaginable. That's an enormous amount of free help. But it also means it's important to know where the code you're importing actually comes from. Not everything you find is trustworthy, and importing someone else's module means running their code, right alongside yours. Stick to well-known, widely-used packages, especially while you're still learning to tell the difference yourself. +See https://docs.python.org/3/tutorial/modules.html for a deeper dive into everything modules can do. diff --git a/objectsmethods.adoc b/objectsmethods.adoc index 2dd1d5c..2865250 100644 --- a/objectsmethods.adoc +++ b/objectsmethods.adoc @@ -1,16 +1,27 @@ -== Objects +== Objects/Instances -There are only a few data types in Python. All but one of them are called “primitive” data types, because their values contain only a single thing (be it a string or a number or whatever). +There are a series if key data types pre-defined (builtin) to Python. The key primaries: *"int", "float", "str", "bool", "None"*. -Python is an object oriented programming language. -Almost everything in Python is an object, with its properties and methods. -A Class is like an object constructor, or a "blueprint" for creating objects. +And there are the "sequence" types: *"list", "tuple", "range"*. -So you write "classes", and then when you run the code, Python then creates the objects to be used by the code. +Several can also be thought of as "container" types: *"list", "tuple","dict", "set", "frozenset"*. -Objects are used to collect and organize data - and that data can be variable values, functions and other things. -Objects can also contain other objects(!), in kind of a "nesting" way. +All of these are actually Classes in Python. +They are all built-in classes, and are available to use without any special syntax. +And `type()` will tell you the class of an object. +Any object at all. + +Moreover, Python is an object oriented programming language. +Everything in Python is an object, with its properties/attributes and methods. +A Class is an object constructor, or a "blueprint" for creating objects. + +So you write "classes", and then when you run the code, Python then creates the objects/instances to be used by the code. + +NOTE: You'll see both words used - *object* and *instance* - and they mean the same thing. When you create an object from a class, programmers usually say you've "created an instance of that class." So "object" and "instance" are really just two names for the same idea, and you'll see both used throughout this book (and in Python's own error messages). + +Objects are used to collect and organize data - and that data can be variable values, functions and other things. +Objects can also contain other objects(!), in kind of a "nesting" way. This allows for large data structures to be built using a very simple and elegant mechanism. @@ -19,14 +30,14 @@ This allows for large data structures to be built using a very simple and elegan class Spacecraft: name = "" type = 'warp starship' - topspeed = 9.9 + topspeed = 9.9 ---- === Object Creation -We can imagine an object as a container where everything is collected about some thing in the program: +We can imagine an object - an instance of a class - as a container where everything is collected about some thing in the program: [source] ---- @@ -41,14 +52,16 @@ Which isn't very helpful, is it? We need to create a _method_ in our class. One [source] ---- class Spacecraft: - name = "" - type = 'warp starship' - topspeed = 9.9 - + def __init__(self): + self.name = "" + self.type = 'warp starship' + self.topspeed = 9.9 + self.current_speed = 0 + def __str__(self): return "Starship " + self.name - def speed(self): + def tp_speed(self): return self.topspeed enterprise = Spacecraft() @@ -59,7 +72,9 @@ print(enterprise) # we get: Starship Enterprise ---- -There a few things to point out in this class. First, notice how the __str__ function is indented? It's defined _inside_ the class. That makes the function a _method_; objects have methods. You can call a method on a particular object. +There a few things to point out in this class. First, notice how the functions are indented? Those functions are defined _inside_ the class. That makes the function a _method_; objects have methods. You can call a method on a particular object. + +Also notice that first parameter, `self`, on every method. `self` is how a method knows *which instance* it's being called on - when you call `enterprise.tp_speed()`, Python quietly hands `tp_speed` the `enterprise` instance as `self`, so `self.topspeed` reaches into that specific instance's data, not some other spacecraft's. [source] ---- @@ -77,14 +92,4 @@ cts = constellation.speed() # ets will be 9.9, cts will be 9.2 ---- -This example also shows how you use a class to create multiple objects. It helps with making code simpler, and easier to follow when reading it. - -=== Follow Ons - -There are a number of very powerful things we have left out of this discussion about Python objects. -We have not covered the ideas of *inheritance* or the idea of *subclassing*. -And there is much more in Python about objects. -Master what we've written about here and then forge ahead into more complicated and powerful capabilities. - -There is a lot more to learn about Python. - +This example also shows how you use a class to create multiple objects. `enterprise` and `constellation` are two separate *instances* of `Spacecraft` - each one built from the very same blueprint, but each holding its own, independent set of values. Changing `constellation.topspeed` had no effect at all on `enterprise`. Using a class this way helps with making code simpler, and easier to follow when reading it. diff --git a/operators.adoc b/operators.adoc index 0c7a34b..96e341a 100644 --- a/operators.adoc +++ b/operators.adoc @@ -1,7 +1,12 @@ == Arithmetic Operators -Python can do math. And many early programming problems you will come across deal with doing fairly easy math. There are ways to do lots of useful things with numbers. +Python can do math. + +That should not surprise you. + +And many early programming problems you will come across deal with doing fairly easy math. +There are ways to do lots of useful things with numbers. === Basics @@ -12,6 +17,7 @@ Python can do math. And many early programming problems you will come across dea |- |Subtraction |Subtract one from another |* |Multiplication |Multiply 2 values |/ |Division |Divide 2 numbers +|// |Floor Division |Divide 2 numbers |% |Modulus |returns the remainder |=== @@ -55,18 +61,43 @@ print(L2) # -> 3 print(L3) # -> 10 ---- -=== Division and Remainder +=== Division(s) and Remainder -We know that we can do regular division. If have a simple program like this, we know -what to expect: +There are *two* types of division in Python: regular division and floor division. Plus, there is the remainder operator. + +We know that we can do regular division. +If we have a simple program like this, we know what to expect: ---- -a = 6 / 3 # -> 2 -a = 12 / 3 # -> 4 -a = 15 / 3 # -> 5 +a = 6 / 3 # -> 2.0 +a = 12 / 3 # -> 4.0 +a = 15 / 3 # -> 5.0 a = 10 / 4 # -> 2.5 ---- +Division always returns a floating-point number. It never returns an integer. + +=== Floor Division + +Floor division is the same as regular division, but it rounds down to the nearest integer. It always returns an integer. *Always*. + +It is sometimes called Integer Division. + +---- +a = 6 // 3 # -> 2 +a = 13 // 3 # -> 4 +a = 17 // 3 # -> 5 +a = 10 // 4 # -> 2 +---- + +It's important to note that last one; `10 // 4` is 2. +Why? +Floor division is the same as regular division, but it rounds down to the nearest integer. + +For example, `10 / 4` is 2.5, but `10 // 4` is 2. + +=== Remainder Operator + But sometimes, we have a need to know what the remainder of a division is. The remainder operator %, despite its appearance, is not related to percents. @@ -79,7 +110,7 @@ Now what's this about '%' (the remainder) operator? [source, js] ---- -a = 3 +a = 3 b = 2 # Modulus (Remainder) answer = a % b @@ -129,15 +160,15 @@ Please Excuse My Dear Aunt Sally * Parenthesis ( ) * Exponents 2^3^ -* Multiplication * and Division / -* Addition + and Subtraction - +* Multiplication * and Division / +* Addition + and Subtraction - **** [WARNING] ==== Divide and Multiply rank equally (and go left to right) So, if we have "6 * 3 / 2", we would multiply first and then divide. -"6 * 3 / 2" is 9 +"6 * 3 / 2" is 9.0 Add and Subtract rank equally (and go left to right) So if we have "9 - 6 + 5", we subtract first and then add. @@ -159,9 +190,9 @@ result = 30 + 6 * 2 print(result) ---- -This gives us 42. +This gives us 42. -Now there is another way to force Python to do things "out of order" with parenthesis. +Now there is another way to force Python to do things "out of order" with parenthesis. [TIP] ==== @@ -193,9 +224,9 @@ math.ceil(4.7) # returns 5 math.floor(4.4) # returns 4 x = 5 y = 3 -math.pow(x, y) # the value of x to the power of y - x^y^ +math.pow(x, y) # the value of x to the power of y -> x^y^ math.pow(8, 2) # returns 64.0 -math.sqrt(x) # returns the square root of x - 2.2360... +math.sqrt(x) # returns the square root of x -> 2.2360... math.sqrt(64) # returns 8 ---- @@ -207,12 +238,12 @@ When we ask a 'function' like sqrt to do some work for us, we have to code somet [source] ---- -squareRootTwo = math.sqrt(2.0) -print(squareRootTwo) +square_root_two = math.sqrt(2.0) +print(square_root_two) ---- -We will get "1.4142135623730951" twice in the output. That number (squareRootTwo) -is the square root of 2, and it is +We will get "1.4142135623730951" twice in the output. That number (square_root_two) +is the square root of 2, and it is the result of the function and _what the function sqrt "returns"'_. ==== @@ -237,13 +268,12 @@ then add 36 + 5 = 41. [source] ---- -squareRootTwo = math.pow(2, 0.5) -print(squareRootTwo) +square_root_two = math.pow(2, 0.5) +print(square_root_two) ---- And notice, when we raise a number to the _0.5_ power, it's *the same as taking its square root!*. And that can be handy sometimes. -You'll learn a lot more about working with numbers in your career as a coder. +You'll learn a lot more about working with numbers in your career as a programmer. This is really just the very basics of the very beginnings. - diff --git a/patterns.adoc b/patterns.adoc index 39023c0..5f10bfe 100644 --- a/patterns.adoc +++ b/patterns.adoc @@ -1,7 +1,7 @@ == Code Patterns -Any experienced coder would say that the ability to see patterns in code, remember them, and learn from them when creating code is another kind of 'superpower'. +Any experienced programmer would say that the ability to see patterns in code, remember them, and learn from them when creating code is another kind of 'superpower'. The following samples are really simple techniques, but they show some common ways of doing things that you should think about and study. In almost all these examples, there may be some missing variable declarations. Just roll with it. @@ -110,7 +110,7 @@ for i in range(1, n): === List Patterns -Lists are often something that confuses beginning coders. Let's look at some code patterns with lists that you see how lists and loops can work together to get a lot of work pretty easily. +Lists are often something that confuses beginning programmers. Let's look at some code patterns with lists that you see how lists and loops can work together to get a lot of work pretty easily. The list we are going to use in all these cases is pretty simple. It's a list of 7 numbers. diff --git a/return.adoc b/return.adoc index 3b93cc6..04c865b 100644 --- a/return.adoc +++ b/return.adoc @@ -7,18 +7,18 @@ As you have seen, _functions_ are used to make code more understandable, cleaner [source] ---- -minorHit = 3 -majorHit = 7 +minor_hit = 3 +major_hit = 7 -def adjustHealth(player, hit): +def adjust_health(player, hit): player[health] = player[health] - hit - if (isAlive(player) == false): - return playerDead + if (is_alive(player) == false): + return player_dead - return playerAlive + return player_alive -def isAlive(player, hit): +def is_alive(player, hit): if (player[health] >= 20): return true else: # player has died! @@ -31,13 +31,13 @@ If someplace in our code we were to do something like: [source] ---- # big hit! -continuePlaying = adjustHealth(playerOne, majorHit) +continue_playing = adjust_health(player_one, major_hit) -if (continuePlaying == playerDead): - endGame() +if (continue_playing == player_dead): + end_game() ---- -You can see how when we call the function "adjustHealth()" it returns either playerAlive or playerDead, and we make a decision to end the game if the player has died. +You can see how when we call the function "adjust_health()" it returns either player_alive or player_dead, and we make a decision to end the game if the player has died. Notice too, you can have multiple return statements in functions, and each one can return a different value if that's what you need. diff --git a/runvsimport.adoc b/runvsimport.adoc new file mode 100644 index 0000000..4ae09aa --- /dev/null +++ b/runvsimport.adoc @@ -0,0 +1,108 @@ + + +== Loading vs. Running a File + +In the Modules chapter, we split code across two files and used `import` to borrow a function from one file into another. That raises a fair question, though: when Python "imports" a file, does it actually *run* that file's code, or just quietly *load* the function definitions sitting inside it? The answer, a little surprisingly, is: it runs *all* of it, every time - and once you understand that, a strange-looking line you'll see constantly in real Python code, `+++if __name__ == "__main__":+++`, stops being a mystery. + +=== Every File Gets Run, Top to Bottom + +Whether you run a file directly, or another file imports it with `import`, Python does the exact same first step: it executes every top-level statement in that file, in order, from top to bottom. + +[source] +---- +print("Loading greetings module...") + +def greet_user(username): + return "Hello, " + username + "!" +---- +_greetings.py_ + +[source] +---- +import greetings + +print("Now in main.py") +---- +_main.py_ + +Now run `main.py`. Here's the output, in order: + +[source] +---- +Loading greetings module... +Now in main.py +---- + +That first `print()`, sitting in `greetings.py`, ran the *instant* `main.py` imported it - well before that second `print()`, the one actually sitting in `main.py`, ever got a turn. That's the "run" half of "loading vs. running": importing a file isn't some special, gentler process that skips over code. It's the exact same thing as running that file, just triggered by another file asking for it instead of you typing its name at a terminal. + +=== The Hidden Variable: `+++__name__+++` + +Every Python file, while it's actually running, has access to a hidden variable named `+++__name__+++` that tells it exactly *how* it's currently being used. + +* If you run a file *directly* - typing something like `python3 greetings.py` at a terminal - Python sets that file's `+++__name__+++` to the special string `+++"__main__"+++`. +* If a file gets *imported* instead, Python sets its `+++__name__+++` to the module's own name, as a string - so `greetings.py`, when imported, sees `+++__name__+++` equal to `"greetings"`. + +[source] +---- +print("This file's name is:", __name__) +---- +_greetings.py_ + +Run it straight from the terminal, `python3 greetings.py`, and you'll see: + +[source] +---- +This file's name is: __main__ +---- + +But add `import greetings` to the top of `main.py` and run *that* instead, and inside `greetings.py`, that very same line prints something different: + +[source] +---- +This file's name is: greetings +---- + +Same file, same line of code - but `+++__name__+++` tells it which situation it's actually in. + +=== The `+++if __name__ == "__main__":+++` Pattern + +Once you know `+++__name__+++` changes like that, this extremely common pattern stops looking so mysterious: + +[source] +---- +def greet_user(username): + return "Hello, " + username + "!" + +if __name__ == "__main__": + print(greet_user("Mike Jones")) +---- +_greetings.py_ + +Read it exactly as it's written: if this file's name is `+++__main__+++`, that means *this exact file* is the one that got launched directly - so run the code indented underneath. + +* Run `python3 greetings.py` directly, and `+++__name__+++` really is `+++"__main__"+++`, so the `print()` fires: `Hello, Mike Jones!` +* But have `main.py` do `import greetings` instead, and inside `greetings.py`, `+++__name__+++` is `"greetings"`, not `+++"__main__"+++` - so that whole `if` block gets skipped entirely. `main.py` still gets the `greet_user` function, ready to use, but that test/demo `print()` never runs on its own. + +=== Why This Matters + +This pattern lets a single file do double duty: it can be a reusable module, full of functions other files are meant to `import` and borrow, *and* a standalone, runnable script with its own little demo or test code - all without those two jobs interfering with each other. Without the `+++if __name__ == "__main__":+++` guard, importing a module would also, unavoidably, run every last one of its "just testing this" print statements and demo calls, every single time. + +Remember the Mars Lander program from the appendix? Its very last line just calls `run_game(burn_array)` directly, with no guard at all. That's fine as a single, standalone program - but it does mean if you ever wanted to `import` those Mars Lander functions into a *different* program, just to reuse `compute_delta_v()` or `check_status()`, you'd immediately launch an entire, uninvited simulation the moment your `import` line ran. Wrapping that final call like this would fix it: + +[source] +---- +if __name__ == "__main__": + run_game(burn_array) +---- + +Now the simulation only launches when you run that file directly - and anyone who wants to `import` just a function or two from it can do so safely, without triggering a whole game. + +[TIP] +==== +* Take the `greetings.py` file from the Modules chapter +* Add an `+++if __name__ == "__main__":+++` block at the bottom with a test call or two to `greet_user` +* Run `greetings.py` directly, and confirm your test calls print +* Then, from a second file, `import greetings` and confirm those same test calls *don't* print this time +==== + +You'll see `+++if __name__ == "__main__":+++` at the bottom of an enormous number of real Python files out in the wild. Now you know exactly what it's checking, and why it's there. diff --git a/setcomprehension.adoc b/setcomprehension.adoc new file mode 100644 index 0000000..c7227d4 --- /dev/null +++ b/setcomprehension.adoc @@ -0,0 +1,86 @@ + + +== Set Comprehensions + +We've built lists and dictionaries with comprehensions. Let's round out the trio with the *set comprehension* - and by now, the pattern should feel very familiar. + +=== Building a Set the Old Way + +Back in the Sets chapter, we cleaned up a list of duplicate weapon picks using `set()`. + +[source] +---- +weapons_picked = ["sword", "bow", "sword", "axe", "bow"] + +unique_weapons = set(weapons_picked) + +print(unique_weapons) # -> {'sword', 'bow', 'axe'} +---- + +That works great when you just want the unique items, unchanged. But what if you want to *transform* each item on the way in, the same way we did with list and dictionary comprehensions? + +=== The Set Comprehension Way + +[source] +---- +donut_flavors = ["Chocolate", "GLAZED", "jelly", "chocolate"] + +lowercase_flavors = {flavor.lower() for flavor in donut_flavors} + +print(lowercase_flavors) +# output is +# {'chocolate', 'glazed', 'jelly'} +---- + +Look closely at what happened. We had four flavors, two of them really the same flavor just typed with different capitalization. By lowercasing each one *and* dropping it into a set, we ended up with exactly three truly unique flavors. A plain `for` loop building a list wouldn't have caught that duplicate on its own - the set part is doing real work here. + +The pattern looks just like a list comprehension, but wrapped in curly braces `{}` with a single expression, no colon: + +[source] +---- +{expression for item in iterable} +---- + +That curly-brace syntax is shared with dictionary comprehensions, so how does Python know which one you mean? It comes down to whether you write one expression (a set) or two, separated by a colon (a dictionary). + +[source] +---- +{x for x in range(5)} # a set: {0, 1, 2, 3, 4} +{x: x * x for x in range(5)} # a dict: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} +---- + +=== Filtering Into a Set + +Just like the other two comprehensions, you can add an `if` to only keep certain items. + +[source] +---- +player_health_scores = [100, 87, 0, 42, 0, 87] + +unique_survivor_scores = {score for score in player_health_scores if score > 0} + +print(unique_survivor_scores) # -> {100, 87, 42} +---- + +Notice the `87` only shows up once in the result, even though it appeared twice in the original list. That's the set doing what sets do best - guaranteeing uniqueness, automatically, even while you're transforming and filtering at the same time. + +[TIP] +==== +* Start with a list of donut flavor names, with a few duplicates typed in different cases (like "Jelly" and "jelly") +* Use a set comprehension to build a set of the unique flavors, all lowercased +* Now add an `if` so only flavors longer than 5 letters make it into the set +==== + +=== Three Comprehensions, One Idea + +You've now seen the same core idea three times over: + +[cols=",,",options="header",] +|=== +|Comprehension |Brackets |Produces +|List |`[ ]` |An ordered collection, duplicates allowed +|Dictionary |`{ }` with a `key: value` |Key:value pairs, unique keys +|Set |`{ }` with one expression |Unique values, no particular order +|=== + +Once "expression, for, in, and maybe an if" clicks for one of them, it clicks for all three. That's the real payoff here - you're not learning three separate tricks, you're learning one very reusable way of thinking about building a new collection from an old one. diff --git a/sets.adoc b/sets.adoc new file mode 100644 index 0000000..bddfbec --- /dev/null +++ b/sets.adoc @@ -0,0 +1,124 @@ + + +== Sets + +We just talked about dictionaries and their key:value pairs. Now let's talk about their cousin, the *set*. + +A set is a collection, like a list, but with one big difference: *a set will not allow duplicates.* Every item in a set is unique. Think of a set as a bag of marbles where, no matter how many times you try to drop in a second red marble, the bag just quietly refuses to hold two. There's only ever one red marble in there. + +Sets also don't care about order. If a list is like the post office boxes we talked about earlier - numbered and in a row - a set is more like a junk drawer. Everything's in there, but nobody's keeping track of what's "first." + +=== Creating a Set + +You make a set with curly braces, much like a dictionary, but without the `key:value` pairs - just values. + +[source] +---- +donut_flavors = {"chocolate", "glazed", "jelly"} +---- + +Here's the fun part. What happens if we try to sneak in a duplicate? + +[source] +---- +donut_flavors = {"chocolate", "glazed", "jelly", "chocolate"} + +print(donut_flavors) +# output is +# {'chocolate', 'glazed', 'jelly'} +---- + +See that? We tried to add "chocolate" twice, and the set just kept the one copy. That's the whole point of a set: it *guarantees uniqueness* for you, automatically, without you having to write any code to check for it yourself. + +NOTE: An empty pair of curly braces, `{}`, actually creates an empty *dictionary*, not an empty set. To make an empty set, you have to use `set()`. + +[source] +---- +empty_set = set() +---- + +=== Adding and Removing Items + +You add items to a set with `.add()`, and remove them with `.remove()`. + +[source] +---- +donut_flavors = {"chocolate", "glazed", "jelly"} + +donut_flavors.add("sprinkled") +print(donut_flavors) +# output is +# {'chocolate', 'glazed', 'jelly', 'sprinkled'} + +donut_flavors.remove("jelly") +print(donut_flavors) +# output is +# {'chocolate', 'glazed', 'sprinkled'} +---- + +If you try to add something that's already there, nothing bad happens - Python just shrugs and leaves the set exactly as it was. + +[source] +---- +donut_flavors.add("chocolate") # already there, no change +---- + +=== Testing Membership + +Just like with dictionaries, we can use `in` and `not in` to ask a set whether it holds something. + +[source] +---- +donut_flavors = {"chocolate", "glazed", "jelly"} + +if "jelly" in donut_flavors: + print("Good, we have jelly donuts!") + +if "cronut" not in donut_flavors: + print("No cronuts here, sadly.") +---- + +This is actually one of the best reasons to use a set. Checking "is this thing in here?" on a big set is very fast, much faster than checking a big list one item at a time. + +=== Where Sets Really Shine: Removing Duplicates + +Let's say five friends are playing our dungeon game, and each one picked a favorite weapon. We want to know how *many different* weapons were picked, not how many friends picked each one. + +[source] +---- +weapons_picked = ["sword", "bow", "sword", "axe", "bow"] + +unique_weapons = set(weapons_picked) + +print(unique_weapons) +# output is +# {'sword', 'bow', 'axe'} + +print(len(unique_weapons)) # -> 3 +---- + +We took a list, which allowed duplicates, and turned it into a set with one line of code. Just like that, the duplicates vanished, and we're left with only the unique weapons. + +=== Combining Sets + +Sets have a few operators borrowed straight from math class, back when you drew those overlapping circles (Venn diagrams, if you remember the name). The two you'll use most are *union* (everything from both sets, combined) and *intersection* (only what's in both sets). + +[source] +---- +players_with_sword = {"Sam", "Jade", "Sadie"} +players_with_shield = {"Jade", "Sadie", "Marcus"} + +# union: everyone who has a sword OR a shield (or both) +print(players_with_sword | players_with_shield) +# output is +# {'Sam', 'Jade', 'Sadie', 'Marcus'} + +# intersection: only the players who have BOTH +print(players_with_sword & players_with_shield) +# output is +# {'Jade', 'Sadie'} +---- + +You don't need to memorize every set operation Python offers. Just remember that `|` glues two sets together (removing duplicates along the way, of course), and `&` finds what they have in common. + +Sets are a handy tool to keep in your back pocket. Whenever you find yourself needing to guarantee "no duplicates allowed" or asking "is this thing in that collection?" over and over, a set is very likely the right data structure for the job. diff --git a/simplecalc.adoc b/simplecalc.adoc index 3ea4860..0f987c6 100644 --- a/simplecalc.adoc +++ b/simplecalc.adoc @@ -18,13 +18,13 @@ How long will it take us to drive all those miles? **** What do we need figure out? We need a variable for our -result: totalMilesDriven. So we start our program this way... +result: total_miles_driven. So we start our program this way... ---- -totalMilesDriven = 0 +total_miles_driven = 0 # print result of computation -print(totalMilesDriven) +print(total_miles_driven) ---- It's often good to start with a very simple template. If we run that, we will see 0 (zero) as the result, right? @@ -32,39 +32,39 @@ It's often good to start with a very simple template. If we run that, we will se Next step, let's add the variables we know. ---- -totalMilesDriven = 0 -totalHoursTaken = 0 +total_miles_driven = 0 +total_hours_taken = 0 -totalGasGallons = 12.0 -milesPerGallon = 22.0 -milesPerHour = 55.0 +total_gas_gallons = 12.0 +miles_per_gallon = 22.0 +miles_per_hour = 55.0 # print result of computation -print(totalMilesDriven) +print(total_miles_driven) ---- Okay, good. We've added all the stuff we know about the computation. Well, except the part of the _actual computation_. -You probably know that if you multiply the milesPerGallon by the totalGasGallons, -that will give you totalMilesDriven. -And if you divide the totalMilesDriven by the milesPerHour, you will get the totalHoursTaken. +You probably know that if you multiply the miles_per_gallon by the total_gas_gallons, +that will give you total_miles_driven. +And if you divide the total_miles_driven by the miles_per_hour, you will get the total_hours_taken. So let's add those as Python statements. ---- -totalMilesDriven = 0 -totalHoursTaken = 0 +total_miles_driven = 0 +total_hours_taken = 0 -totalGasGallons = 12.0 -milesPerGallon = 22.0 -milesPerHour = 55.0 +total_gas_gallons = 12.0 +miles_per_gallon = 22.0 +miles_per_hour = 55.0 -totalMilesDriven = milesPerGallon * totalGasGallons -totalHoursTaken = totalMilesDriven / milesPerHour +total_miles_driven = miles_per_gallon * total_gas_gallons +total_hours_taken = total_miles_driven / miles_per_hour # print result of computation -print(totalMilesDriven, totalHoursTaken) +print(total_miles_driven, total_hours_taken) ---- We get as a result 264 miles driven in 4.8 hours. @@ -92,19 +92,19 @@ we then know that we need 365 cans of food. So we can describe that as [source] ---- -totalCost = 0 -cansNeeded = 365 -costPerCan = 2.0 / 3.0 +total_cost = 0 +cans_needed = 365 +cost_per_can = 2.0 / 3.0 -totalCost = cansNeeded * costPerCan # right? +total_cost = cans_needed * cost_per_can # right? -monthsPerYear = 12 -costPerMonth = totalCost / monthsPerYear +months_per_year = 12 +cost_per_month = total_cost / months_per_year # print result of computation -print(totalCost, costPerMonth) +print(total_cost, cost_per_month) ---- -What's going to be the answer? footnote:[totalCost will be $243.33 and $20.28 per month.] Run it in your Repl window to work it all out. +What's going to be the answer? footnote:[total_cost will be $243.33 and $20.28 per month.] Run it in your Repl window to work it all out. And let's do one more. @@ -114,10 +114,10 @@ A cell phone company charges a monthly rate of $12.95 and $1.00 a gigabyte of da [source] ---- -dataUsed = 0.0 +data_used = 0.0 # print result of computation -print("total data used (GB)", dataUsed) +print("total data used (GB)", data_used) ---- Let's add what we know: that the monthly base charge (for calls, and so on) is $12.95 @@ -127,31 +127,31 @@ that written down. [source] ---- -dataUsed = 0.0 -costPerGB = 1.0 -monthlyRate = 12.95 +data_used = 0.0 +cost_per_gb = 1.0 +monthly_rate = 12.95 -thisBill = 21.20 +this_bill = 21.20 # print result of computation -print("total data used (GB)", dataUsed) +print("total data used (GB)", data_used) ---- -Now we're ready to do the computation. If we subtract the monthlyRate from thisBill, we get the total cost of data. Then, if we divide the total cost of data by the cost per gigabyte, we -will get the dataUsed. +Now we're ready to do the computation. If we subtract the monthly_rate from this_bill, we get the total cost of data. Then, if we divide the total cost of data by the cost per gigabyte, we +will get the data_used. [source] ---- -dataUsed = 0.0 -costPerGB = 1.0 -monthlyRate = 12.95 +data_used = 0.0 +cost_per_gb = 1.0 +monthly_rate = 12.95 -thisBill = 21.20 -totalDataCost = thisBill - monthlyRate +this_bill = 21.20 +total_data_cost = this_bill - monthly_rate -dataUsed = totalDataCost / costPerGB +data_used = total_data_cost / cost_per_gb # print result of computation -print("total data used (GB)", dataUsed) +print("total data used (GB)", data_used) ---- How many GBs of data did we use? Turns out to be 8.25 gigabytes. diff --git a/strings.adoc b/strings.adoc index 2ab9cfa..dbb3439 100644 --- a/strings.adoc +++ b/strings.adoc @@ -99,8 +99,8 @@ This simply means joining strings together using the + operator. We have to turn [source] ---- price = 20 -dollarSign = "$" -priceTag = dollarSign + str(price) # $20 +dollar_sign = "$" +price_tag = dollar_sign + str(price) # $20 ---- @@ -109,10 +109,10 @@ Or perhaps a little more useful example: [source] ---- name = "Mikaila" -hoursWorked = str(12) +hours_worked = str(12) -workReport = "Today, " + name + " worked a total of " + hoursWorked + " hours." -print(workReport) +work_report = "Today, " + name + " worked a total of " + hours_worked + " hours." +print(work_report) ---- The output would be: @@ -133,31 +133,31 @@ It follows this pattern: `end:` The ending index of the substring. The character at this index is NOT included in the substring. If end is not included, or if the value is greater than the string length, it is assumed to be equal to the `len()` of the string by default. -`step:`` Every ‘step’ character after the current character to be included. If the step value is not there, Python sets it to 1. +`step:` Every ‘step’ character after the current character to be included. If the step value is not there, Python sets it to 1. A start position is required, where to begin the extraction (or substring). Remember, first character is at position 0. Characters are extracted from a string between "start" and "end", not including "end" itself. [source] ---- -firstName = "Christopher" +first_name = "Christopher" ---- -Now let's use the 3 substring method-functions on firstName and extract and print out "Chris" +Now let's use the 3 substring method-functions on first_name and extract and print out "Chris" [source] ---- -firstName = "Christopher" +first_name = "Christopher" -print(firstName[0:5]) # "Chris" +print(first_name[0:5]) # "Chris" ---- -We took the `firstName` string and extracted the characters 0 to 4. BUT, let's try to extract the string "stop" from the name. +We took the `first_name` string and extracted the characters 0 to 4. BUT, let's try to extract the string "stop" from the name. [source] ---- -firstName = "Christopher" -print(firstName[4:8]) # -> "stop" +first_name = "Christopher" +print(first_name[4:8]) # -> "stop" ---- Let's try a little harder idea... @@ -166,9 +166,9 @@ Let's try a little harder idea... ==== [source] ---- -firstName = "Christopher" +first_name = "Christopher" ---- -- Your turn to use the string slicing on firstName +- Your turn to use the string slicing on first_name - Extract and print out "STOP" from inside the string above - And make it uppercase! ("stop" to "STOP") footnote:[You could google how to do this, try "python string make upper case"] ==== @@ -177,8 +177,8 @@ Well? [source] ---- -firstName = "Christopher" -print(firstName[4:8].upper()) +first_name = "Christopher" +print(first_name[4:8].upper()) ---- Want to bet there is also a ".lower()" method-function as well? @@ -215,7 +215,7 @@ This is a powerful way to handle strings in Python. === Reverse a String -Now, using the `firstName` variable again, let's reverse the string "STOP" to say "POTS". +Now, using the `first_name` variable again, let's reverse the string "STOP" to say "POTS". [TIP] ==== @@ -234,12 +234,12 @@ Solution [source] ---- -firstName = "Christopher" -res = firstName[4: 8].upper() # -> "STOP" +first_name = "Christopher" +res = first_name[4: 8].upper() # -> "STOP" rev = res[::-1] # -> POTS print(rev) # -> POTS ---- -Strings are perhaps the most important data type in almost any language. Being able to manipulate them easily and do powerful things with them in Python, makes you a better coder. +Strings are perhaps the most important data type in almost any language. Being able to manipulate them easily and do powerful things with them in Python, makes you a better programmer. diff --git a/tuples.adoc b/tuples.adoc new file mode 100644 index 0000000..6d43640 --- /dev/null +++ b/tuples.adoc @@ -0,0 +1,113 @@ + + +== Tuples + +We've talked about lists, and how they're a great way to store a bunch of things in order. Now, let's meet the list's more stubborn sibling: the *tuple*. + +A tuple looks a lot like a list, and acts a lot like a list... except for one very important thing: *once you create a tuple, you cannot change it.* No adding, no removing, no swapping out an item. It's locked, permanently, the moment you create it. Programmers call this *immutable*, which is just a fancy word for "cannot be changed once made." + +Why would you ever want that? Well, imagine you've got some data that should never accidentally get messed with later on in your program - like a person's date of birth, or the (x, y) coordinates of a spot on a map. A tuple is Python's way of saying "this data is locked in, don't touch it." + +=== Creating a Tuple + +You create a tuple with parentheses instead of the square brackets you'd use for a list. + +[source] +---- +coordinates = (10, 20) + +katniss_info = ("Katniss", "Everdeen", 12) +---- + +Just like lists, tuples can hold any mix of data types - strings, numbers, booleans, even other tuples or lists. + +NOTE: If you want a tuple with just *one* item in it, you need a trailing comma, like `(100,)`. Without the comma, Python thinks you just wrote the number `100` inside some plain parentheses, not a tuple at all! + +[source] +---- +not_a_tuple = (100) # this is just the number 100 +single_tuple = (100,) # this IS a tuple with one item +---- + +=== Accessing Items in a Tuple + +Reading from a tuple works exactly like reading from a list. Tuples are indexed starting at zero, just like everything else we've indexed so far. + +[source] +---- +katniss_info = ("Katniss", "Everdeen", 12) + +print(katniss_info[0]) # "Katniss" +print(katniss_info[2]) # 12 +---- + +You can slice a tuple too, the same way you'd slice a list or a string. + +[source] +---- +weekday_scores = (88, 92, 79, 95, 100) + +print(weekday_scores[1:3]) # (92, 79) +print(weekday_scores[-1]) # 100 +---- + +=== You Really Can't Change It + +Let's prove it. If you try to change an item in a tuple, Python will stop you cold with an error. + +[source] +---- +katniss_info = ("Katniss", "Everdeen", 12) + +katniss_info[2] = 13 +# TypeError: 'tuple' object does not support item assignment +---- + +Compare that to a list, where this same kind of line would work just fine. This is the whole reason tuples exist: sometimes you *want* that safety net, so nothing later in your program can accidentally mangle your data. + +=== Unpacking a Tuple + +One of the nicest tricks with tuples is *unpacking* - pulling the items out into their own separate variables, all in one line. + +[source] +---- +katniss_info = ("Katniss", "Everdeen", 12) + +first_name, last_name, home_district = katniss_info + +print(first_name) # "Katniss" +print(last_name) # "Everdeen" +print(home_district) # 12 +---- + +This works because Python matches up each variable on the left with the item in the same position on the right. It's a very clean way to hand out a tuple's contents without writing `katniss_info[0]`, `katniss_info[1]`, and so on. + +You'll also see this used a lot with coordinates: + +[source] +---- +location = (35, 80) + +x, y = location + +print(x) # 35 +print(y) # 80 +---- + +=== Tuples vs. Lists + +So when do you reach for a tuple instead of a list? Here's a simple way to think about it: + +* Use a *list* when you have a collection of things that might change - growing, shrinking, or getting swapped around. +* Use a *tuple* when you have a fixed little bundle of data that should stay exactly as it is - like a coordinate pair, a date, or a record you're just reading from, never editing. + +[source] +---- +player_health_scores = [100, 100, 100, 100, 100] # this will change during the game + +spawn_point = (0, 0) # this should never change +---- + +Tuples aren't as flashy as lists, but they earn their keep. Whenever you find yourself thinking "this data should never change," reach for a tuple, and let Python enforce that promise for you. + +Keep tuples in mind as you move on - they're about to make a surprise appearance in the next chapter, tucked inside one of Python's more flexible function tricks. diff --git a/typehints.adoc b/typehints.adoc new file mode 100644 index 0000000..eb5eb29 --- /dev/null +++ b/typehints.adoc @@ -0,0 +1,126 @@ + + +== Type Hints + +Way back in the Variables chapter, we saw that Python variables are dynamic - a variable can hold a string one moment and a number the next, and Python never complains. That flexibility is one of Python's superpowers. But it comes with a cost: just by glancing at a function, there's often no way to tell what kind of data it expects, or what kind of data it's going to hand back to you. + +*Type hints* are Python's answer to that problem. + +=== What Is a Type Hint? + +A type hint is a little note you add to a function (or a variable) saying what type of data you *expect* to be dealing with. + +[source] +---- +def greet_user(username: str) -> str: + return "Hello, " + username + "!" + +print(greet_user("Mike Jones")) # -> Hello, Mike Jones! +---- + +Two new things showed up here: + +* `username: str` - this says "I expect `username` to be a string." +* `-> str` - this says "this function returns a string." + +Read the whole line almost like a sentence: `greet_user` takes a `username`, which should be a `str`, and returns a `str`. + +=== Important: Hints Are Not Enforced + +Here's the part that trips people up: type hints are *hints*, not rules. Python will not stop you from breaking one. + +[source] +---- +def add_bonus(score: int, bonus: int) -> int: + return score + bonus + +print(add_bonus(50, "10")) +# TypeError: unsupported operand type(s) for +: 'int' and 'str' +---- + +We hinted `bonus` as an `int`, but nothing physically stopped us from calling `add_bonus` with the string `"10"` instead. The program still crashed - but notice *why*. It crashed because `+` genuinely can't combine a number and a string together, the same problem you've run into before with strings and numbers. It did *not* crash because we broke the type hint; Python never even glances at the hint while your program is running. The hint didn't prevent this mistake - it just would have warned a careful reader (or a smart editor) about it *before* the code ever ran. + +NOTE: Type hints are sometimes called "optional" for a good reason - your code runs exactly the same with them or without them. They're there for *people* (including future-you) and for tools, not for the Python interpreter to police. + +=== Why Bother, Then? + +If Python doesn't enforce them, what's the point? A few good reasons: + +* *Readability* - anyone reading `def greet_user(username: str) -> str:` instantly knows what to hand this function, without having to go read the whole function body first. +* *Self-documentation* - the hints live right in the code, so they can't drift out of date the way a separate comment or document sometimes does. +* *Tooling* - modern code editors read your type hints and warn you *immediately*, often as you're typing, if you're about to pass the wrong kind of thing into a function. That catches a whole category of mistakes before you ever hit run. + +As your programs get bigger, and especially once you're working on a team where other people read your code, these small hints save a surprising amount of confusion. + +=== Common Types You'll Hint + +You already know most of these types by name - now you know how to write them as hints. + +[cols=",",options="header",] +|=== +|Hint |Means +|`str` |A string +|`int` |A whole number +|`float` |A decimal number +|`bool` |True or False +|`list` |A list +|`dict` |A dictionary +|`tuple` |A tuple +|`set` |A set +|`None` |Nothing at all +|=== + +[source] +---- +def take_damage(player: dict, amount: int) -> None: + player["health"] = player["health"] - amount +---- + +That `-> None` is a common one - it says "this function doesn't hand anything back." `take_damage` just changes `player` in place and returns nothing, so `None` is the honest, accurate hint. + +=== Hinting What's *Inside* a Collection + +You can get more specific than just "this is a list" - you can say what kind of thing fills that list. + +[source] +---- +def total_damage(hits: list[int]) -> int: + return sum(hits) +---- + +`list[int]` means "a list, and every item inside it should be an `int`." The same trick works for dictionaries, showing both the key type and the value type. + +[source] +---- +def build_health_lookup(names: list[str], scores: list[int]) -> dict[str, int]: + return {name: score for name, score in zip(names, scores)} +---- + +That return hint, `dict[str, int]`, tells us this function hands back a dictionary whose keys are strings and whose values are integers - exactly the kind of dictionary comprehension we built a couple chapters back. + +=== Type Hints and Default Parameters Play Nicely Together + +You can combine everything from the last chapter with type hints, all in the same function signature. + +[source] +---- +def cast_spell(caster: str, spell: str = "fireball", power: int = 50) -> str: + return caster + " casts " + spell + " for " + str(power) + " damage!" + +print(cast_spell("Gandalf")) +# -> Gandalf casts fireball for 50 damage! +---- + +Notice the hint and the default value sit right next to each other: `spell: str = "fireball"` says both "this should be a string" *and* "if you don't provide one, use `'fireball'`." + +[TIP] +==== +* Take the `take_damage(player, amount=10)` function from the last chapter +* Add type hints: `player` should be hinted as a `dict`, `amount` as an `int` +* Give the function a `-> None` return hint, since it doesn't return anything +* Call it once with correct types, and once "incorrectly" (like a string for `amount`) just to see that Python still runs it either way +==== + +=== A Habit Worth Building Now + +You don't have to type-hint every single line of code you write, especially while you're still learning. But it's a genuinely good professional habit to start building early - the kind of thing that makes your code easier for *other* people (and future-you) to pick up and trust at a glance. The more Python you write, the more you'll find yourself reaching for a type hint out of habit, simply because it makes the code that much clearer. diff --git a/variables.adoc b/variables.adoc index ea49f42..44ad0f3 100644 --- a/variables.adoc +++ b/variables.adoc @@ -3,11 +3,19 @@ === Variables -In Python, variables are containers used to store data while the program is running. Variables can be named just about anything, and often are named things that make you think about what you store there. +A variable in Python is best understood as a *name that points at a value* — not a box that contains one. +This distinction sounds pedantic the first time you hear it, and then becomes the thing that saves you from real confusion a few chapters from now, once two different names can point at the *same* value at the same time. +For now, the practical consequence is simpler: a name is just a label, and Python does not care at all what you call something. +It cares what the something *is*.Variables can be named just about anything, and often are named things that make you think about what you store there. -Think of them as little boxes you can put data into, to keep it there and not lose it. +[source] +---- +ratings = [4.5, 3.0, 5.0, 4.0] +cats = 3 +cat_name = 'Fluffy' +---- -There are some rules about variables. +There are some rules about variable names. - All Variables must be named. - Names can contain letters, digits, and underscores @@ -23,17 +31,17 @@ So this means the following are fine for variable names in Python: x AREA height -Width -currentScore -playerOne -playerTwo -sumOfCredits -_lastPlay -isPlayerAlive +width +current_score +player_one +player_two +sum_of_credits +_last_play +is_player_alive ---- And uppercase and lowercase letters are different. -So each of these are DIFFERENT variables even +So each of these are DIFFERENT variables even though they are based on the same word(s). [source] @@ -55,7 +63,7 @@ cats = 3 print(cats) # -> 3 dogs = 1 -print(cats) # -> 1 +print(dogs) # -> 1 player1alive = true carspeed = 55.6 @@ -87,8 +95,8 @@ x = "nineteen" print(x) # -> nineteen ---- -Notice how we assign "nineteen" to _x_. We can assign (re-assign) to a variable as many times as -we might need to. +Notice how we assign "nineteen" to _x_. +We can assign (re-assign) to a variable as many times as we might need to. [source] ---- @@ -100,11 +108,12 @@ age = age + 1 print(age); # -> 5 ---- -Notice here how _age's_ current value is used, added one to it, and re-assigned *back into the variable* _age_. +Notice here how _age's_ current value is used, added one to it, and re-assigned *back to the variable* _age_. -Now, one of the weird (to me anyway) things Python can do is change the type of a variable while the program is running. -A lot of languages won't you do this. But it can be handy in Python. -In Python, variables are dynamic (can contain any data) which means a variable can be a string and later be a number. +Now, one of the weird (to me anyway) things Python can do is a variable to point to *any* kind of item, while the program is running. +A lot of languages won't you do this. +But it can be handy in Python. +In Python, variables are dynamic (can reference any data object) which means a variable can be a string now and later be a number. [source] ---- @@ -117,7 +126,7 @@ print(height) # -> very tall # and then it's a string. ---- -_You can't see it, but I am slowly shaking my head in disbelief. Some day, maybe I'll explain why._ +_You can't see it, but I am slowly shaking my head in disbelief. Some day, maybe I'll explain why. Or maybe you'll explain it to me._ === Constants @@ -131,9 +140,9 @@ GRAVITY = 9.8 ---- They are _usually_ declared in a file named 'constants.py'. -Note: In reality, we don't use constants in Python. -(The language _doesn't_ have them.) -Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment. +Note: In reality, we don't use constants in Python. +(The language _doesn't_ have them.) +Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment. So be careful. @@ -143,48 +152,59 @@ Python can keep track of a number of different kinds of data, and these are know as "data types". Here are a few of them. * *Numeric* - there are two kinds of numbers: integers, floats and complex -** *Integers* are like 0, -4, 5, 6, 1234 -** *Floats* are numbers where the decimals matter like 0.005, 1.7, 3.14159, -1600300.4329 -** *Complex* are, well, if you don't already know, let's ignore them. -* *str* - a _string_ of characters - -** like 'text' or "Hello, World!" -* *Boolean* - is either *True* or *False* -** often used to decide things like isPlayer(1).alive() [True or False?] +** *Whole Numbers* - *int* are like 0, -4, 5, 6, 1234 +** *Decimal Numbers* - *float* are numbers where the decimals matter like 0.005, 1.7, 3.14159, -1600300.4329 +** *Complex* are, well, if you don't already know, let's ignore them. _But, I should make a joke about how there are two kinds of number and then then show three kinds, and mumble something about an 'off-by-one' bug._ +* *Strings* - *str* - a _string_ of characters - +** like 'text' or "Hello, World!" or 'Wow, I really like Python!' +* *Boolean* - *bool* - is either *True* or *False* +** often used to decide things like is_player(1).alive() [True or False?] * *None* - no value at all (nil or null in other languages) It is common for a computer language to want to know if data is a bunch numbers or text. Tracking -what _type_ a piece of data is is very important. And it is the programmer's job to make sure all the -data get handled in the right ways. +what _type_ a piece of data is is very important. And it is the programmer's job to make sure all the +data get handled in the right ways. -So Python has a few fundamental *data types* that it can handle. And we will cover each one in turn. +So Python has a few fundamental *data types* that it can handle. And we will cover each one in turn. +Any variable can be handed to the **type()** builtin functions and it will tell you what type the variable references. + +[source] +---- +x = 42 +print(type(x)) # -> +r = 3.14 +print(type(r)) # -> +s = 'Hello, World!' +print(type(s)) # -> +---- [TIP] ==== -Create variables for each primitive data type: +Create variables for each builtin data type: -- boolean, -- float, -- integer, -- str +- boolean, +- float, +- integer, +- str Store a value in each. ==== [source] ---- -# Here are some samples. +# Here are some samples. # integer x = 0 # boolean -playerOneAlive = True +player_one_alive = True # float -currentSpeed = 55.0 +current_speed = 55.0 # string -playerOneName = 'Rocco' +player_one_name = 'Rocco' ---- Now, you try it. Write down a variable name and assign @@ -192,6 +212,6 @@ a normal value to it. === Data Structures -Python has a series of different _data structures_ built into the language. -Its built-in data structures include lists, tuples, sets, and dictionaries. - +Python has a series of different _data structures_ built into the language. These are also referred to as _collections_. +Its built-in data structures include *lists*, *tuples*, *sets*, and *dictionaries*. +We will cover each one in turn in later chapters. diff --git a/whileloop.adoc b/whileloop.adoc index 9c0d838..ba86d3c 100644 --- a/whileloop.adoc +++ b/whileloop.adoc @@ -1,18 +1,18 @@ == Loops -Loops allow you control over repetitive steps you need to do in your _control flow_. Python has two different kinds of loops we will talk about: *while* loops and *for* loops. +Loops allow you control over repetitive steps you need to do in your _control flow_. Python has two different kinds of loops we will talk about: *while* loops and *for* loops. Either one can be used interchangeably; but, as you will see there are couple cases where using one over the other makes more sense. -The primary purpose of loops is to avoid having lots of repetitive code. +The primary purpose of loops is to avoid having lots of repetition in code. === While Loop -Loop through a block of code (the body) WHILE a condition is true. +Loop through a block of code (the body) WHILE a condition is true. ---- while (condition_is_true): - # execute the code statements + # execute the code statements # in the loop body pass ---- @@ -34,34 +34,33 @@ print("ending at", x) # ? what will print here ? ---- While loops work well in situations where the condition you are testing at the top -of the loop is one that may not be related to a simple number. +of the loop is one that may not be related to a simple number. ---- -while (player[1].isAlive() == True): - player[1].takeTurn() - game.updateStatus(player[1]) +while (player[1].is_alive() == True): + player[1].take_turn() + game.update_status(player[1]) ---- -This will keep letting player[1] take a turn in the game until the player dies. Another way to do something like this is with an _infinite loop_. -(No, infinite loops are not necessarily a bad thing, watch.) +This will keep letting player[1] take a turn in the game until the player dies. Another way to do something like this is with an _infinite loop_. +(No, infinite loops are not necessarily a bad thing, watch.) We're going to use both *continue* and *break* in this example, and we will describe them better after we're done with loops. ---- -player = game.newPlayer() +player = game.new_player() while (true): # <- notice right here, an infinite loop - player.takeTurn() - game.updateScores() - game.advanceTime() + player.take_turn() + game.update_scores() + game.advance_time() - if (player.isAlive() == true): + if (player.is_alive() == true): continue # start at top of loop again. else: break # breaks out of loop and ends game. -game.sayToHuman("Game Over!") +game.say_to_human("Game Over!") ---- Here, we are using the continue statement to force the flow of control to the top of the loop if the player is still alive after the 'take turn' code. We are also using the break statement to break out of the infinite loop when the player dies, letting us do other things after the player has 'died'. -