Python files

From OpenHatch wiki
Jump to: navigation, search

Treasure map.png

(Estimated completion time: 15 - 30 minutes)

[edit] Goal #1: practice reading and running Python files

Until now we've been using the interactive Python interpreter. This is great for learning and experimenting, but you can't easily save or edit your work. For bigger projects, we'll write our Python code in a file. Let's get some practice with this!

  1. Download the file http://mit.edu/jesstess/www/BostonPythonWorkshop8/nobel.py by right-clicking on it and saying to save it as a ".py" file to your Desktop. The ".py" extension hints that this is a Python script.
  2. Open a terminal prompt, and use the navigation commands (dir and cd on Windows, ls, pwd, and cd on OS X and Linux) to navigate to your Desktop directory. See navigating from a terminal for a refresher on those commands.
  3. Once you are in your Desktop directory, execute the contents of nobel.py by typing
    python nobel.py
    

    at the terminal prompt.

    nobel.py introduces two new concepts: comments and multiline strings.
  4. Open nobel.py in your text editor (see preparing your text editor for a refresher on starting the editor).
  5. Read through the file in your text editor carefully and check your understanding of both the comments and the code.

Study the script until you can answer these questions:

  1. How do you comment code in Python?
  2. How do you print just a newline?
  3. How do you print a multi-line string so that whitespace is preserved?


[edit] Goal #2: more practice with Python files

For each of the following Python programs (folks often call these "scripts"), please do the following:

  1. Download the script and save it to your Desktop. Be sure to save it as a .py file.
  2. Open the script in your text editor.
  3. Read through the script. Don't worry about understanding every last detail. Instead focus on:
    • Overall, what does this script do?
    • What variables and data types are used? Where are the strings, integers, and floats?
    • What functions are used, and why?
    • Where are the comments, and what do they tell you?
  4. Once you have a good sense of what the script does, open a terminal, navigate to the directory where you saved the script, and run it. Does it do what you expected?
  5. Think about one way that you could extend the script to make it more useful. How would you make that change in code?

Here are you scripts to read and run. Have fun with them!

Personal tools