Skip to content
Merged

V2 #1

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ index.pdf
EPUB/index.epub
*.epub
*.pdf
.DS_Store
Binary file added PythonBookv2-cover.pages
Binary file not shown.
54 changes: 27 additions & 27 deletions appendixb.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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]
----
Expand All @@ -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"
Expand All @@ -47,7 +47,7 @@ def gameHeader():
return s


def getHeader():
def get_header():
s = ""
s = s + "\nTime\t"
s = s + "Speed\t\t"
Expand All @@ -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):
Expand All @@ -86,34 +86,34 @@ 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']) \
+ " \t\t" + str(vehicle['Fuel']) + " \t\t" + str(vehicle['Height'])
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++):
Expand All @@ -135,41 +135,41 @@ vehicle = {


# main game loop
def runGame(burns):
def run_game(burns):
status = ""

# Set initial vehicle parameters
h = randomheight()
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)

----
92 changes: 92 additions & 0 deletions appendixc.adoc
Original file line number Diff line number Diff line change
@@ -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.
Loading