Thanks to Dr. Alan McLeod for the content of this lab.

This set of lab exercises will first introduce screen, or console window input and output, which is most easily referred to as just "I/O". Exercises 1-3 can be carried out at the Python prompt, as you did for Week 2, or in individual programs. The lab will then move on to exercises regarding functions and variable scope.

The prompt is fine when you are just trying out one or a few lines of code. Even if you are working on a program in IDLE, you should never hesitate to skip out to the prompt to test out a line of code or an expression that you are not certain of. But, when you are working with more than a few lines and you want to be able to change parts without having to re-type the entire thing, it is time to save these lines of code in a file.

A file consisting of lines of Python code is called a script, or just a "program". By convention Python programs have a ".py" extension, and you will find, in Windows, that they are already associated with Python. You will also find that these programs are just text files that can even be created and edited using Notepad. However, IDLE is designed to help write Python programs and has some nice features to make your work easier.

The second part of this set of exercises will show you how to create a simple Python program and will explore different ways of running it, including IDLE, which will be probably be your editor of choice. Then you will be able to write some programs to carry out simple calculations with values supplied by the user.

Exercise 1

Console I/O commands have been introduced in lecture. They consist of:

Here are a few simple exercises using the print() function at the Python prompt. If you've already done the first two parts of Assignment 1 then some of these may seem very simple.

1.1) (Ritual!) Do your own print("Hello World!") at the Python prompt.

1.2) How can you generate the following output with a single call to the print function?


line1

line2

line3

There are two ways of doing this. Here are the answers.

1.3) Assign the values of three int-type variables as follows: a = 123, b = 45678 and c = 21. You need to assign them one at a time. You can print the variable contents all on one line using print(a, b, c). Try it.

1.4) Get help on the print() function by looking in the Python docs or by typing "help()" at the prompt, then "print" at the help> prompt. Note the use of the sep= and end= keyword arguments. They can be used to change how the print() function works. When you are back at the Python prompt, see if you can figure out how to:

Here are the answers.

1.5) Display the value of the variable a preceded by the string literal: "The variable a is: ". Note that there are at least two simple ways of doing this. You might have to convert the int variable to a string. Here is the answer.

Exercise 2

The string format() method offers complete control over how numbers and strings are displayed. Look up the documentation on this method in the Help -> Python Docs file in IDLE. The easiest way to find the material is to type "format()" in the Index tab at the left. Choose the "(str method)" subtopic. This is a pretty short paragraph, but you can get more than enough information on this method by clicking on the Format String Syntax link. Don't worry about all the details right now - you can still carry out some simple exercises without knowing everything about this versatile method.

Here is an example of the use of this method and the resulting screen output:


>>> print("The variable a is: {0}, b is: {1} and c is: {2}.".format(a, b, c))

The variable a is: 123, b is: 45678 and c is: 21.

(This won't make too much sense right now, but the format() method is a member of the str class or "object" and any string literal is a str object, so we can invoke the method as a member using the period or "dot operator".) Here is another way of doing the same thing:


>>> print("The variable a is: {x}, b is: {y} and c is: {z}.".format(x=a, y=b, z=c))

The variable a is: 123, b is: 45678 and c is: 21.

You can add lots of other things to what is inside the { } (the "replacement field") to control display characteristics. Read about these in the Format String Syntax document. For example, look at how the result of dividing b by a is displayed in different ways:


>>> print("b divided by a is {0}".format(b/a))

b divided by a is 371.365853659

>>> print("b divided by a is {0:.3}".format(b/a))

b divided by a is 3.71e+02

>>> print("b divided by a is {0:.3f}".format(b/a))

b divided by a is 371.366

2.1) Print the result to one digit after the decimal place instead of three. Is the number truncated or rounded?

2.2) Can you figure out how to print the result in a field of width 12, so that the number will have a padding of spaces in front of it, without adding literal spaces? (e.g., b divided by a is      371.366)

2.3) Can you pad the number with zeros instead of spaces, to get b divided by a is 00000371.366?

2.4) Can you display the value of variable a in base 2 (binary) or in base 16 (hex)?

Here are the answers.

Exercise 3

The input() function is used to obtain input from the user. When using input() you should supply a string literal as a parameter to the function. This string will be used to prompt the user, telling him what kind of data is expected. The input() function returns a string. If you need a number, you will have to convert the string using a function like int() or float().

You can still use the Python prompt for these few input exercises, but it is getting a little more difficult to play with this kind of code ...

3.1) Here is a session using the input() function at the Python prompt:


>>> a = input("Enter a number: ")

Enter a number: 43

>>> a

'43'

Note the space at the end of the string prompt supplied to input(), which is a polite way of putting the cursor one position past the colon. Try this out at your own prompt.

3.2) You will notice that even though the user is typing a number, the variable a contains a string, because that is all that input() can return. Use the int() function to change the string to a number before it is stored in a. What happens if the user does not provide a legal integer value, or if he provides a float instead of an integer? (Sometime we are going to have to figure out a more robust way of getting numeric input!)

Exercise 4

You will likely use IDLE to write your programs, but this exercise will show you that you can create a program with just a plain text editor.

4.1) Using Notepad, or a similar simple text editor, create a file called MyProgram.py in some folder that you can write to. Put a line like print("Hi there!") as the single line of text in the file. Using your file browser (like Windows Explorer), and assuming that the *.py file type has been properly associated with Python, double-click on the file MyProgram.py in your browser window. Did you see a window open and close very quickly?

4.2) That was not too useful! Can you think of a way of keeping that window open so you can view the output without being Superman? (answer)

This shows that you can certainly write a program just using a simple text editor, and it will run nicely in a "DOS" window. But the IDLE environment is friendlier, not to mention more colourful!

Exercise 5

You can define your own functions at the Python prompt. Here is a sample session where the function message() is defined:


>>> def message():

	print("This is a message!")



>>> message()

This is a message!

Try typing this in yourself. Type the def message(): line in first. Note how the cursor automatically indents and waits for you to type in the body of the message() function. This behaviour is a result of having the colon, :, at the end of the def line. Type in the print line, press <enter> and then backspace to get the cursor back to the first column on the screen. Press <enter> again to get the Python prompt back. Now you can invoke your fancy function by entering message() at the Python prompt.

There is nothing special about this function name, "message" - you could have used any name that follows the legal variable naming rules. However, there is one function name that is accepted to be the start of your program: main(). Here is our ritual, "Hello World" program written using a main() function:


def main():

    print("Hello World!")



main()

From the IDLE window, choose File, then New Window or just type <Ctrl>n. You will get a blank editing window, like you have seen in lecture. Type in the little program shown above. Add a comment or two to the top by prefacing the text with the "pound" sign: #. Save your program by typing <Ctrl>s, calling it something like "hello.py". Run the program by choosing Run then Run Module or simply press <F5>. You will see error messages if you have made any mistakes or your fancy message in the Python Shell window, where the prompt is.

Next, put a # in front of the call to main() at the bottom of the program and run it again. As you can see, you really need to have that call to main() or your program will not do much!

A Python program is often composed of a series of functions that perform different tasks and a main() function that acts as the starting point. You can think of main() as a "coordinator" which tells the other functions when to do their jobs. The use of main() is something of a convention in programming; many other languages automatically use main() as the starting point for a program. However, in Python you always have to call main() to execute it.

5.1) Create a brand new program called InchToCm.py, by choosing "File" then "New Window" (or use <Ctrl>n) in the Python Shell window. Write a program that prompts the user for a distance in inches, which then displays the same distance in cm to a single decimal point. An inch is 2.54 cm. (answer: InchToCm.py)

5.2) Run your program a few times with different inputs. Note that you can easily re-run your program by typing main() at the Python prompt. What happens when you type a negative distance? How about when you type something that is not a number? Eventually we will have to learn how to make these programs more robust! (And we will!)

5.3) Python uses indentation to distinguish which lines belong to a function (and other blocks of code, as we'll see later). It is vital to correctly indent the code that belongs in a function. Try removing the indentation from one line in a function and running the program. What happens?

Optional: Using a value of 3.14 for pi, write a program that obtains a radius from the user and then outputs the circumference of a circle, the area of the circle and then the volume of a sphere using this radius. (answer: AllRound.py). It might be nice to use a more accurate value of pi than 3.14. Section 6.3 in the textbook can show you how to obtain pi from the math module. Here is a version of our program using the value of pi from this library: BetterAllRound.py.

Exercise 6

Functions have the ability to accept input and produce output. Input for functions is accomplished via parameter variables, which are usually referred to as parameters. A list of named parameters is placed inside the () for a function and separated by commas. Consider the following function:


def hypoteneuse(sideA, sideB):

    hypoteneuse = (sideA ** 2) + (sideB**2)

    hypoteneuse = hypoteneuse**0.5



    print("The hypoteneuse is {0:.3f}".format(hypoteneuse))

Parameters such as sideA and sideB act like variables that already have their values assigned. You can use them in any expression or statement in the function like you would use a variable which you defined yourself. We will work more intricately with parameters later in the course.

Output for functions is accomplished via a return statement:


def hypoteneuse(sideA, sideB):

    hypoteneuse = (sideA ** 2) + (sideB**2)

    hypoteneuse = hypoteneuse**0.5



    return hypoteneuse





def main():

    print("The hypoteneuse is {0:.3f}".format(hypoteneuse(9, 11)))

The return keyword allows you to pass a value back to the caller of the function. You've already worked with functions that return values:


    year = input("What year is it? ")

    year = int(year)

The input(...) function returns a string with the user's input while the int(...) function returns the integer value inside the string parameter. We'll see more complex ways of using return later in the course.

In Exercise 5.1 you wrote a program to convert inches to cm. Re-work this program to have a function that accepts a distance in inches, which then returns the equivalent distance in cm. Add code to your main() function to test this new function by prompting the user for a distance in inches and then printing out the equivalent distance in cm as obtained from the function.

Exercise 7

Where a variable is declared in a Python program dictates where it can be used. This is known as the variable's scope. In general, a variable's scope is the function or statement in which it is declared. The variable can be used in any other nested functions or statements declared within its scope. Consider the following program:


globalVar = 1



def functionOne(paramOne):

    localVarOne = 3;

    def functionTwo():

        print(paramOne, localVarOne, globalVar)



    functionTwo()





def main():

    global globalVar

    localVarOne = 5

    globalVar = 7

    functionOne(localVarOne)



main()

What is the output?

 5 3 7 

globalVar is a global variable; its value can be accessed in any function. However, to change its value a global variable must be "re-declared" in a function using the global keyword as in main(). localVarOne is defined as a local variable in functionOne(...); it can be used in both functionOne(...) and functionTwo(). The same is true for parameter paramOne.

A different local variable named localVarOne is declared in main() and only exists within this function. The value of localVarOne is copied into paramOne for the call to functionOne(...).

The use of global variables is generally avoided. Here are a few reasons why:

Having said that, global variables can be useful for defining constants that are used by many functions. For example, an accounting program may use global variables to define tax rates (e.g., GST = 0.05). In such cases, the convention is to define global constants using all uppercase letters.

Exercise 7.1) Comment out the line "global globalVar" in the main() function and run the program. Why do you think the output has changed?

Exercise 7.2) Move the declaration "globalVar = 1" to between the definitions for functionOne(...) and main() and run the program. Can functionOne(...) still use it?

Exercise 7.3) First, add the line "localVarOne = 9" in functionTwo() before the call to print(...). What is the output now? Second, add the line "print(localVarOne)" in functionOne(...) after the call to functionTwo(). What is the output? Did the change made to localVarOne in functionTwo() carry over to functionOne(...) or was a new local variable with the same name declared instead?

More Exercises

The textbook has many other exercises that you can do. At the end of chapter 2, you can do any of the "Programming Exercises" that look interesting. Two of these are shown below. For each one that you work on, try to make sure that your output has a sensible number of digits displayed. For example, don't show more than two digits if you are displaying a dollar figure. Try to use main() for user input and output and seperate functions to perform the other tasks.

Two slightly modified exercises from the textbook: