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.6 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.6 greetings.py
Hello world!

Your Turn: Scripts 🏁

Script Exercises

Random Fun

Copy rand.py to a new file number.py and modify the new file 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.

Meditative Breathing Guide

Copy pause.py and make a program breathe.py which helps users breathe 6.5 breaths per minute by printing out “Breath in”, waiting some time, then saying “Breath out”, then repeating. It should do this for 2 minutes (13 total breaths, each with an in and an out).

Roll Die

Copy the contents of rand.py to roll.py and make a program that prints a random number from 1 to 6.