Lab: Python 1

What we’re doing: Getting started on what past CSC 105 instructors have called “the journey and the joy of learning to write comptuer programs in Python.”

Why we’re doing it: to learn and apply fundamental techniques of algorithmic thinking.

Preparation

Log on to a MathLAN computer and click on th Applications button in bottom left corner. Go to Development and then the program called IDLE 3. (IDLE stands for Integrated Development and Learning Environment.) This will open a window that looks like a terminal window but running Python instead of a file directory. This is called the Shell screen. In it, you interact directly with Python.

First things first: make a mistake.

Enter:

>>>2+

Errors do not break your computer and they do not mean you are dumb. Errors mean what you are asking Python to do is not yet expressed in a way that Python understands how to do it. The number one most common error is probably going to be misspelling or forgetting a quotation mark, parenthesis, etc.

Enter:

>>>2+2

This time, Python could turn what you typed into something it knew how to do, and so now you have four. If that’s what you wanted it to do, you’re all set.

Want to do more? Well then let’s go.

Simple programs

We just saw that Python can add integers. It can do the same thing with strings. A string is data type that consists of characters and spaces, in a specific order. Strings can include numbers, but they won’t be treated as numbers. They’ll be characters in an order.

A few of the things you can do with strings

For example, try:

>>>"2"+"2"

See the difference? Strings in Python are designated by quotation marks at the start and end.

Can Python multiply strings? Try:

>>>"2" * 2

What about:

>>>"2" + 2

What about:

>>>"2" + str(2)

Putting strings together is called concatenation.

Building things with strings

Set two string variables:

>>> day = “Today”

>>> weather = “cold”

Use these two variables as part of another variable:

>>> sentence = day + “ the weather is “ + weather + “.”

Turn these variables into an output:

>>> print(sentence)

Does the output look right? Why or why not?

Calling a function from an external module

Let’s say you wanted to be more specific than “Today” for what day it is. Instead of setting every single variable for our program, we can call on other helper programs called functions. Functions can be stored as part of a larger set of programs called a module.

One of these modules is called datetime. To be able to call upon its functions, we have to tell Python that we want it to have the module available for access. This is called importing or loading the module:

Import the datetime module:

>>> import datetime

Set a variable for the current date:

>>> now = datetime.datetime.now()

Try it out:

>>>print(“Current date and time: “ + str(now))

Note that we’ve put str() around the output of our variable now. What does that tell you about the original output of now?

In the next phase of the lab, we’ll write a script to package all of this up together so that we can run it without having to re-type every step.

Writing a function

A function puts multiple steps together to generate an output. In the Shell, type the following forecast function. Note that Python is very particular about how things are indented; these spaces tell the computer which instructions go with other instructions. When you type one line and the next needs to be indented, type tab to increase the indentation after pressing enter.

def forecast():

    now = datetime.datetime.now()

    day = “Today, “ + now.strftime(‘%A, %B the %dth, %Y’)

    weather = “cold”

    sentence = day + “ the weather is “ + weather + “.”

    print(sentence)

Hit enter twice, then type the following command into the Shell prompt:

>>>forecast()

You should see a much more specific version of sentence. As well, you could run this function tomorrow and get an updated date.

Sidebar: You probably noticed that the day variable changed between the two different versions. It still called on the datetime.now function within the datetime module, but it outputs in the information in a format that makes more sense in a sentence for human beings to read. How does a programmer know what’s possible and how to do it? Well, there’s a couple of ways to start. You could check the documentation. But it is really long and distracts me with deep thoughts like “Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality”, and I only really want to be able to do this one thing. So you could also just look for an example. The example will help me solve the problem I want to solve right now, although it may not help me solve the next problem.

Let’s do another one that will let us practice a basic form of interaction: asking for someone’s name.

>>>def hello():

    name = input(“What’s your name? ")

    print("Good morning, " + name + “.”)

Hit enter twice and run your new function:

>>>hello()

Now run your function back to back with your first one:

>>>hello(), forecast()

Ignore the last line for now–it’s output from Python confirming that you did not put anything into the parentheses.

Writing a module

What if you wanted to be able to run these functions without having to re-type it for every session? You could put them together as part of a module.

In the Shell window, go to File and then New File. This will open up another window which is a different type, an Editor. In this window you are typing code rather than interacting directly with Python. It’s like a text editor, but it has a connection to the Shell so that you can quickly run your programs.

Start your module file with some basic information:

##file: goodmorning.py

##purpose: Have a little good morning chat with Python.

##author: Liz

The hashtag is used to comment the code, which means to add text that is readable by humans but will not be seen by Python as part of the code to execute. Commenting to explain what you’re doing is good practice for coding of any kind.

Now enter:

import datetime

Remember, you need that module’s functions to run your functions.

Now enter your previous functions. You might be able to copy and paste if you use Edit menu drop down rather than the keystrokes or right clicking. Make sure the indentations are maintained.

def hello():

    name = input("What’s your name? ")

    print("Good morning, " + name + ".")

 

def forecast():

    now = datetime.datetime.now()

    day = “Today, “ + now.strftime(‘%A, %B the %dth, %Y’)

    weather = “cold”

    sentence = day + “ the weather is “ + weather + “.”

    print(sentence)

Now go to File and Save your file with the name goodmorning.py

Take note of where it saves.

After you’ve saved, go back to the Editor window and click Run and then Run Module. This will bring up a new Shell prompt. Run your functions from this prompt.

Calling on modules

This next step shows you what’s going on behind the scenes when you have an import statement at the beginning.

Start a new file:

## file: use-goodmorning.py

## purpose: the title says it all

## author: Liz

import goodmorning

def chat():

    goodmorning.hello()

    print(goodmorning.forecast())

 

Go to File and save it as use-goodmorning.py, making sure it saves in the same directory as goodmorning.py. Run the module, and then call the chat() function.

Chat with your neighbor

Now it’s your turn.

  1. Make a folder in your home directory (or anywhere, as long as you remember the full address) in which you will save two Python scripts (.py files). Just as we did for the lab above, one will be a module, or set of functions. The other will call on that module to execute a chat. Test them out before you do the next step.
  2. When you are finished, set your folder and file permissions to allow a class colleague to copy the files from you and give the file directories to your neighbor. They should copy them and put them in the same directory on their computer. They should then open the files from the Python IDLE and run them in the Shell before calling the chat() function in the second file. As a reminder, the copy command will be run in Terminal and will look something like cp ~neighborusername/foldername/filename /yourusername/foldername/filename
  3. You can use our lab scripts as a template. The key features will be defining functions, using input(), and using string concatenation to create a sense of conversation.