Scripts

Note

Be sure to change directories to the python_class folder. You will need to do this every time you open a new command/terminal window for this class.

Command-Line Scripts

We've typed all of our code at the REPL up to now, which is pretty limiting. So let's move on to making Python programs!

A "program" is a file with code in it that you can run to get something done. A "script" is cute name for a small program. We'll be making command-line scripts, which are just scripts that we run from your computer's command-line.

In the python_class folder you downloaded earlier, there's a file called greetings.py which contains the following code:

"Hello world!"

To run this program we can go to our terminal window, and type:

$ python3 greetings.py

Huh. That didn't do anything. The "Hello world!" string in the file isn't printing. That's because running code in in the REPL automatically prints it out for us, but when we're writing a script we have to tell Python what to do with the string, or it'll do nothing. Let's make a little tweak to the file so it'll print out.

print("Hello world!")
$ python3 greetings.py
Hello world!

Script Exercises

Roll Die

Download rand.py and modify if to print the variable x so you can see what it contains. Run the program multiple times to see how x changes and see if you can guess what it represents.

Now copy the contents of rand.py to roll.py and turn that into a Python program that prints a random number from 1 to 6 (representing a random die roll).

Meditative Breathing Guide

Copy rand.py and make a program breathe.py which helps users breathe one breathe every 12 seconds by printing out "Breath in", waiting 6 seconds, then saying "Breath out", waiting 6 seconds, and then repeating. It should do this for 2 minutes.