Intro to Computer Science

Unit 1 - Programming Fundamentals: Data Types and Functions

Table of Contents

  1. Introduction to Python
  2. Text Editors
  3. More Python
  4. Development and Debugging
  5. Programming Basics
  6. Numeric Data Types
  7. Functions, Parameters, and Return Values

1.0. Overview

We're going to look about Computer Science by writing programs using the Python programming language. There are other programming languages, but Python is absolutely the best one for what we're going to be doing.

Let's get started!

1.1. Introduction to Python

1.1.1. Running Python Interactively in the Terminal

To start the Python interpreter, start the Terminal applications, type python at the command line and hit the [Enter] key:

$ python [Enter] Python 3.4.1 |Anaconda 2.0.1 (x86_64)| (default, May 19 2014, 13:05:46) [GCC 4.2.1 (Apple Inc. build 5577)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>

The >>> prompt let's you know that Python is waiting for you to enter an instruction.

Python Output statements

Try entering the statement here, press the [Enter] key to execute it, and see what happens:

>>> print("Hello, world!")

Then try a few other statements in the interpreter to see what happens:

print(Hello, world!) print(3 + 4) print("3 + 4") print(3, 4) print(34) print(3 4)

Once you're done with your interactive session, exit by typing "exit()", or holding down the ctrl key while pressing d.

>>> ^D

Executing instructions like this one at a time in the interpreter is kind of cool, especially when you're trying to figure out a command that's new to you, or if you want to experiment real quickly with an idea.

There's one big disadvantage, though: if you want to execute your instructions again, you have to type them in again. Usually, it's much better to write a program.

1.1.2. Writing a Python program

Let's write our first program, the traditional Hello, World! exercise.

Hello, World! in Python

Do this:

  1. In the Terminal, cd to your Desktop
  2. Launch nano to create the program hello_world.py.
    $ nano hello_world.py
  3. This program will just have three lines in it:
    1. one line will print out the message "Hello, world!" when it runs
    2. the next line will print the sum of the numbers 1-10, and
    3. the last line will print a personalized goodbye message to you.
    Once you think the program is done, save it, exit nano, and try running your program:
    $ python hello_world.py
  4. If it doesn't work as you expected, or you get a message saying that the program had an error, it's not big deal. Let the debugging begin.
  5. Start up nano again to try to fix the program:
    $ nano hello_world.py
    Once you've made your changes, hit ctrl-w to Write the new version of your program to the disk—the old version will be copied over. Now try running the program again:
    $ python hello_world.py

Are you stuck? Show/hide solution

print("Hello, world!") print(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) print("Goodbye, Richard!")

If your program ran perfectly the first time, congratulations! You got really, really lucky. And if your program didn't work as you expected it would—either because you mis-typed something, or because you're still trying to figure out how all of this works, well... welcome to the world of programming. We're going to be writing programs in here, but we're going to spend even more time trying to get the programs to work the way we want them to.

It's kind of like solving a puzzle... and it's a fantastic feeling when you solve the puzzle and get your program to work.

1.2. Text Editors

A text editor is one of the most fundamental tools of computer programming. It's possible to compose text on the computer using a word processing program like Microsoft Word or Google Docs—being able to produce nicely formatted documents is important.

Text editors, however, work with pure text, and have no ability to "make things look pretty" like a word processor does. There are no superscripts or subscripts, no underlining, no bold, and no italics. The unformatted plain text is easier for both computers and programmers to work with.

There are two basic types of text editor that you might want to use.

1.2.1. Using a text editor in the terminal

We've just seen how you can use nano to edit a text file. You can also use emacs or vim, powerful programs that work in the terminal, and you'll probably see me using vim at some point in here.

These programs take a long time to learn, however, and we've got a better option available to us.

1.2.2. Using a Text Editor application on your local machine

We're going to install Microsoft's Visual Studio Code on your computer. It takes about five minutes to get it up and running. Follow along with this video, pausing it as needed so you can complete each step.

Written instructions (Summary)

You can also read a step-by-step guide on how to install VS Code for our class here.

1.2.3. Development set-up

You'll typically want to have two windows open simultaneously on your screen: one for the code that you're writing, and one for running/debugging that code. You'll switch back and forth between the two windows as you work, writing code in the window on the left, and then running the code in the window on the right to see how your program is coming along.

Set up your work environment

Take a moment to open up a VSCode window on your computer. Resize that window and move it over to the left side of the screen. You'll be writing your code in this screen.

Also, launch a Terminal and resize that window so that it can fit on the right side of your screen. When you're working on writing your code, you'll be bouncing back and forth between these two windows.

1.3. More Python

We've got a lot more to cover as we learn the Python programming language...

1.3.1. Comments

Real programs have additional components, some of which we're going to introduce right away.

Editing your program

Using your text editor (VSCode), open up and edit your hello_world.py program to include comments: text that is not used by Python, but that is used by programmers to identify and understand the code. Python ignores everything to the right of a #, so we use that to indicate a comment.

#!/usr/bin/env python3 """ hello_world.py This is the famous Hello, World! program that one always begins with. """ __author__ = "Richard White" __version__ = "2019-08-19" # This program prints “Hello, world!" print(“Hello, world!") print(1+2+3+4+5+6+7+8+9+10) print("Goodbye, Richard")

Save your program and run it again to make sure that it works just as it did before.

You could reasonably wonder why we should include in our program several blank lines and comments that don’t make the program run any differently.

Experienced coders already know the answers to these questions. Briefly:

1.3.2. Code blocks, or Suites

Programs include logical sections of code blocks, which in Python are called suites.

Suites, or code blocks

A suite in Python is a logical block of code, identified at the beginning by a colon (:), with all lines indented exactly 4 spaces from the previous line.

NOTE: Do not use [tab]s to create your spacing unless you have configured your text editor to replace tabs with spaces. Four spaces may look the same as a [tab], but Python won't be able to run your program correctly. Also, although the "4 spaces" rule is not required by Python—you can actually use any spaced-indent for a suite, as long as the same indent is used consistently throughout the program—in here we'll be using 4-spaces, which is standard Python "best practice."

Let's begin right away with setting up a suite that you'll use in practically every program that you write in the class: a main function that comprises the body of your program.

A main() function

Now modify your program to include a main function, as follows:

#!/usr/bin/env python3 """ hello_world.py This is the famous Hello, World! program that one always begins with. """ __author__ = "Richard White" __version__ = "2019-08-19" # This program prints “Hello, world!" def main(): print(“Hello, world!") print(1+2+3+4+5+6+7+8+9+10) print("Goodbye, Richard") if __name__ == "__main__": main()

Here, the def instruction in Python defines a function called "main", which contains a bit of code that won't be run until the name is used later on in the program.

Down below, then, we "call the function" by writing main(), which tells the interpreter to execute the instructions that we'd described earlier on in the function definition.

Again, you might wonder why we've made our straightforward program a little more complex by defining a function.

From this point on, you'll always be writing your programs with at least one function—main()—and then calling that function to execute it.

1.4. Developing and Debugging

Whether you're using Python or some other language, you'll need to know this.

1.4.1. Debugging

You should know right away that programs very rarely work the first time that one writes them. Writing a program has a lot in common with writing an essay or paper:

Writing a paperWriting a program
Planning the essay: outlining, etc.Drawing flowcharts, diagrams of data structures, pseudocoding
Writing the rough draftWriting the program
Editing, revising, polishing up the final draftDebugging the program so that it passes all tests

1.4.2. The Development Process

The Coding Cycle

Whether working from the command line in a Terminal shell or using a sophisticated IDE, the coding process is identical:

  1. Design the program (usually by hand, using pencil and paper)
  2. Write the program (using a text editor or IDE)
  3. Try to compile the program and debug whatever errors there might be
  4. Run a compiled version of the program to confirm that it's working better.
  5. Repeat these steps until you've tested the program sufficiently to have some confidence that it works as it's supposed to.

Compiling and Running your Python program

  • When you type python hello_world.py in the Terminal, the Python interpreter will try to compile the program (convert it from source code to bytecode.
  • If you don't get any error messages on the screen, you've successfully avoided any syntax errors. (This is no guarantee that your program is going to work correctly, but it's a start!)
  • If you did get some errors, then there may be a cryptic message, or more likely a series of messages, that you might be able to use to figure out where you went wrong. Typically a line number will be listed that may give you some idea of where to start looking. Open up your program in the text editor again and have a look at it.

    Common Syntax Problems!

    Don't forget to look at the line just before that line, too—that's often where the trouble begins. (Did you forget a semicolon? Are your quotation marks balanced? Are your parentheses balanced?)

  • Once you think you've fixed the problem, save the program and try to run the program again. Once the compilation process produces no errors, Python will automatically execute the bytecode instructions for your program.
  • Your program is almost certainly producing output at this point. This simple program doesn't have too much that can go wrong with it. But is it the correct output?

    If an assignment tells you to write a program that prints out "Hello, World!" then it needs to do precisely that! Make sure you understand why each of the following examples of output would be incorrect:
    Hello, World Hello World! Hello World Hello, Word! Hello, world!
    We'll be developing strategies that you can use to make sure that your program works correctly.

Writing good software is challenging, but rewarding, and usually even fun.

The process of writing a program involves quite a bit more than simply sitting down at the computer and entering code. A typical problem will require that you:

  1. Analyze the problem
  2. Determine the specifications
  3. Design the program's overall structure
  4. Write the program (lots of testing and debugging here)
  5. Deliver the program
  6. Maintain the program (updating it as required, repairing it as needed)

In this course, you'll often be provided with the first 2 items, and #6 won't typically be something you'll have to worry about.

1.4.3. Types of Errors

There are three specific types of errors that you'll need to keep an eye out for, and fixing errors is what we spend a good amount of time doing.

  1. Syntax errors are caught during compilation of your source code and represent incorrect use of the Python language. Typical syntax errors including

    • mispelling a variable name
    • incorrectly indenting a line
    • incorrect use of parentheses
    • incorrect use of a Python instruction

    The compiler will try to find as many errors as possible at one time, but realize that:

    • an error indicated for one line might have occurred on the previous line, and
    • a whole series of errors may be reported as a result of a single error earlier in the program.
    $ python hello_world.py File "hello_world.py", line 1 print("Hello, world!) ^ SyntaxError: EOL while scanning string literal $
  2. Run-time errors occur while a program is able to run, but doesn't do what it was designed or expected to do. Some examples of run-time errors will cause the program to stop running include:
    • trying to divide by 0
    • the user enters text when a number is expected
    • the user enters a float (decimal point) value when an integer is expected
    $ python test.py Enter a number: 0 Traceback (most recent call last): File "test.py", line 2, in print (100/val) ZeroDivisionError: division by zero $
  3. Logic errors are a specific type of error that occurs during runtime. The program will appear to run correctly, but the results produced are incorrect: a program that adds the numbers 1-10 and produces a result of 45 when the correct answer is 55, for example. The only way to catch these types of errors is with testing.
    $ python sum1to10 The sum of the integers 1 to 10 is 45 Expected result: 55

One thing that helps with avoiding errors is defensive programming: writing well-structured code with comments, and progressively testing the code so that errors in one part don't end up cascading down into other areas of the program.

One three-part "error management" strategy:

  1. learn about common errors and how to avoid them
  2. learn defensive strategies for minimizing likelihood and impact of errors
  3. learn debugging strategies to find and correct errors.

Check - Types of Errors

Identify what type of error—syntax, run-time, or logical—each of the following statements will result in.

  • print((10 * 2) / (5 - 2 - 3))
  • print("The answer to 2 + 2 is", (2 + 3))
  • print("Hello, World!"

Show/hide answers

  • print((10 * 2) / (5 - 2 - 3))
    is a Run-Time error. Dividing by 0 will cause the program to fail when it runs.
  • print("The answer to 2 + 2 is", (2 + 3))
    is a Logical error. The program is producing output, but the output is incorrect.
  • System.out.println("Hello, World!"
    is a Syntax error. There is a missing parenthesis at the end of the string Hello, World!, so this program won't even compile.

1.4.4. Using scp to transfer files

You can use the scp command to transfer files from one computer to another.

The scp command

scp is used to securely copy files from one "source" computer (often your local machine) to another "destination" computer (often the class server) according to the following syntax:

scp <source> <destination>

In order to make this command work, you'll need to provide username and server information as part of the command.

To securely copy a file from the Desktop of my local computer to my Documents directory on the server I'd use this:

$ scp ~/Desktop/my_file.txt rwhite@crashwhite.polytechnic.org:Documents/ rwhite@crashwhite.polytechnic.org's password: my_file.txt

To securely copy a file from your local computer to a directory on the server where I'll look for your assignments, you'll use this:

$ scp ~/Desktop/userID/hello_world.py userid@crashwhite.polytechnic.org:~/forInstructor userid@crashwhite.polytechnic.org's password: ch07ex02-userid.py 100% 11KB 11.4KB/s 00:01

To securely copy a file from the instructor's Public directory down to your machine, you'll use this:

$ scp userid@crashwhite.polytechnic.org:/home/csinstructor/pfscsa/Public/filename ~/userID userid@crashwhite.polytechnic.org's password: filename 100% 11KB 11.4KB/s 00:01

1.5. Programming Basics

Let's write some programs! Get your development environment set up: a coding window on the left and a running/debugging window on the right. Also, create a standard Python document on the left coding window that we'll use when we're ready to start writing.

1.5.0. Overview

In this session we'll be learning how to assign values to variables, how to perform numeric calculations, how to get input, and how to write a simple program.

1.5.1. Assigning values to variables

The fundamental thing that computers do is calculate the answers to mathematical problems. To do that, we need to be able to take numbers and store them in the computer's memory.

Programmer-assigned value to a variable

To assign a value to a variable in a program:

<variable> = <expression>

Examples:

height_in_feet = 5.8
height_in_inches = 12 * height_in_feet
height_in_inches = height_in_inches + 0.5 # I grew this year!

Let's try writing a program that allows us to convert temperatures from one system to another.

temp_converter.py

The formula for converting from degrees Fahrenheit (U.S. temperature system) to degrees Celsius is

Write a Python program temp_converter.py that takes the temperature in degrees Fahrenheit (say 70°F) and prints out the equivalent temperature in °C.

Show/hide one solution

#!/usr/bin/env python3 """ temp converter.py This program converts from degrees F to degrees C """ __author__ = "Richard White" __version__ = "2017-09-08" def main(): # The main program will go here temp_fahrenheit = 72 temp_celsius = (temp_fahrenheit - 32) * 5 / 9 print(temp_celsius) if __name__ == "__main__": main()

This solution is one way to solve the problem.

1.5.2. Assigning values to a variable via user input

Although that temp_converter.py isn't bad, it requires that we rewrite the program every time we want to convert a different temperature.

We can improve the program quite a bit if we write it so that the user can enter their own initial temperature (degrees Fahrenheit) each time the program runs. Let's see how to get user input into one of our programs.

User-assigned value to a variable

To allow a user to enter a value while the program is running:

<variable> = input() # for entering strings

The input() function takes whatever is entered as a string, a series of characters. If you want those characters to be evaluated as a number, you'll need to convert them using the float() function.

<variable> = float(input()) # to take a string entered and evaluate it as a number.

It is also possible to include a simple prompt as part of the function. If we want to have the user enter their name and age, we could do it this way:

print("Enter your name: ") name = input() print("Enter your age: ") name = float(input())

Or we can include the prompt as part of the input statement like this:

age = float(input("Enter your age")) user_name = input("Enter your name")

temp_converter_input.py

Make a new version of the previous program temp_converter.py that it asks the user for a name and a temperature, and then prints out a custom message of the temperature in degrees C using their name.

Note: You can print multiple items with a single print statement by separating each item from the others with a comma (,).

Show/hide one solution

#!/usr/bin/env python3 """ temp_converter_input.py This program converts from degrees F to degrees C """ __author__ = "Richard White" __version__ = "2017-09-08" def main(): name = input("Enter your name: ") temp_fahrenheit = float(input("Enter the temperature in degrees F: ")) temp_celsius = (temp_fahrenheit - 32) * 5 / 9 print(name, "the equivalent temperature in Celsius is", temp_celsius) if __name__ == "__main__": main()

1.6. Numeric Data Types

In this session we'll be looking at the two different types of numeric data types in Python, seeing how you can import a module to give Python additional capabilities, and looking at local text editor applications.

1.6.0. Overview

Programming languages represent different types of data differently, and it's important for you to be aware of what data type one is working with. Data types in Python include int (integers), float numbers (floating point, or decimals), str (strings, of text), list (for lists of things), tuple (kind of like lists, but immutable), dictionary...

To begin, let's look at several of the numeric data types, operations that can be performed on those numbers, and some of the ways we can work with those numbers using functions in the math module.

1.6.1. Integers and Floating Point numbers

Integers

Plain integers are simply that: integers, i.e. numerical values without a decimal point. You can confirm the type of a number by using the type() function in interactive mode:

>>> type(3) <type 'int'>

Integers in Python3 have unlimited precision: you can perform any calculation you like and Python will be able to handle it without an "overflow" error, which occurs in some languages when a value is too large to be stored in the memory space allocated for it.

Floats

Floats are floating point numbers, i.e. numerical values that do have a decimal point.

>>> type(3.0) <type 'float'>

Why does a computer need to distinguish between the two? It's all about speed. It's far easier for computers to deal with integers, and therefore far faster for them to perform operations with integers. Differences in speed won't be apparent in most programs that we write, but for any program that performs the same operation thousands, million, or billions of times, working with integers where possible produces a significant increase in speed.

Of course, if you need to work with decimals (floats), then you'll have to use them where appropriate.

Start up the Python interpreter and try out each of the examples here. Can you predict what the output of each will be?

>>> 5 + 2
>>> 5.0 + 2
>>> 5.0 / 2
>>> 5 / 2
>>> 5 // 2 # how is this different?
>>> 5 % 2 # this is related to the last one
>>> 5 * 2
>>> 5 * 2.0
>>> 5 ** 2
>>> 2. ** 0.5

Note that the // operator allows for "whole number" division—it returns the integer result of the division without a decimal and without any remainder.

The modulo operator % gives you that remainder.

These two division strategies turn out to be enormously useful to us.

You can use Python's built-in functions to convert from one data type to another:

>>> print(float(3)) 3.0
>>> print(int(3.7)) 3
>>> print(round(3.7)) 4

1.7. Functions, Parameters, and Return Values

1.7.0. Overview

In this session we'll be taking our first steps toward writing larger, more complex programs. We'll look at how writing procedural functions can help us better organize our code and make it less redundant, and how to write functions that uses parameters and return values to communicate with the programs that call them.

1.7.1. Functions and Parameters

1.7.1.0. Definition and Uses of Functions

Functions

A function is simply a small program inside a larger one, whose purpose is to:

  • organize your program into logical blocks of code
  • reduce duplicated code (shortening and simplifying your program)
  • make your program easier to maintain (by keeping your code better organized)

Generally speaking, you should include functions in your program if:

  • You find that you're repeating code with minor variations
  • Your program takes up more than "one screen" of space

In fact, a popular acronym among software engineers is DRY: Don't Repeat Yourself. If you do find yourself rewriting lots of segments of code, you should probably try to find a way to write the code more efficiently.

One way of reducing the amount of repeated code that we have to write is by using loops, which we'll learn about soon. Another very important strategy is to organize code into functions.

Defining a Function

Just as we've used def main(): to define a main block of code that runs, we can define other functions with blocks of code that will execute when we "call" the function. As an example, here's a short (and not very useful) function to say "Hello" to somebody:

def say_hello(): print("Hello!")

These lines just define the function, but the code doesn't actually execute in our program until we call it:

say_hello()

At this point, the "Hello!" message is displayed.

1.7.1.1. Standalone functions

I'm welcoming guests to my party and I find myself saying the same thing over and over again as each guest shows up at the door. I've written a program to print what I'm saying:

""" party.py Welcomes guests to my party """ def main(): guest = "Ziko" print("Welcome,",guest) print("Food is over there,") print("drinks are over here,") print("I hope you have a great time!") guest = "Reese" print("Welcome,",guest) print("Food is over there,") print("drinks are over here,") print("I hope you have a great time!") guest = "Ayush" print("Welcome,",guest) print("Food is over there,") print("drinks are over here,") print("I hope you have a great time!") main()

This program works just great, but you can see that I've had to repeat my little speech quite a few times. We can make the program a little more efficient by writing a function to print out the parts that are repeated.

This program produces exactly the same output:

""" party.py Welcomes guests to my party """ def welcome(): """Prints out a welcome to party guests. """ print("Food is over there,") print("drinks are over here,") print("I hope you have a great time!") def main(): guest = "Ziko" print("Welcome,",guest) welcome() # calls the function guest = "Reese" print("Welcome,",guest) welcome() # calls the function guest = "Ayush" print("Welcome,",guest) welcome() # calls the function main()

This is quite a bit more efficient than what I did before. Each time I "call" the welcome() function in the main, the instructions in that welcome() function are performed.

1.7.1.2. Functions with parameters

We can make our function even more efficient by moving that print("Welcome,",name) instruction side the function, but when we first do that, we run into a problem:

def welcome(): """Prints out a welcome to party guests. """ print("Welcome,",guest) print("Food is over there,") print("drinks are over here,") print("I hope you have a great time!") Traceback (most recent call last): File "party.py", line 27, in main() File "party.py", line 16, in main welcome() File "party.py", line 8, in welcome print("Welcome,",name) NameError: global name 'guest' is not defined

The issue here is that although the main() program knows who the guest is, the function doesn't. We need to send that bit of information in via a parameter.

Parameters

A parameter is information that is passed into a function.

A formal parameter is included in parentheses as part of the function definition. The argument—either a variable or a value—is given in parentheses when the function is called.

The working version of the program looks like this:

""" party.py Welcomes guests to my party """ def welcome(guest): """Prints out a welcome to a party guest. """ print("Welcome,",guest) print("Food is over there,") print("drinks are over here,") print("I hope you have a great time!") def main(): guest = "Ziko" welcome(guest) # calls the function guest = "Reese" welcome(guest) # calls the function guest = "Ayush" welcome(guest) # calls the function main()

This works just as it should!

We're going to look at some other ways one can use functions, but first let's look at the random module.

1.7.2. The random Module

We've already discussed the math module, and how you can import that module to use various methods that will allow your Python program to perform mathematical calculations.

Now let's look at another useful module, and learn how to get help using that module.

The random Module

The random module in Python provides various random generators that can be used to produce random values or random select items from a list.

Common methods used in the random module include:

  • random.randrange(n) - returns a random integer between 0 and n
  • random.randrange(a,b) - returns a value between a (inclusive) and b (exclusive)
    Example: random_card_value = random.randrange(1,14) # gives a value between 1 and 13
  • random.choice(aList) - returns a single random choice from a list of items
    Example: random_suit = random.choice(['spades','hearts','diamonds','clubs'])

Here's an example of how you can use that module to generate a random roll of a six-sided die:

#!/usr/bin/env python3
"""
Using the random module to simulate rolling a die.
"""

import random

def main():
    roll = random.randrange(6) + 1      
    # randrange randomly gets an integer from 0-5 inclusive.
    # Adding one gives us a value from 1-7, inclusive.
    print(roll)

if __name__ == "__main__":
    main()

There are other methods that can be used in the random module. You can find them by using Python's help function in interactive mode.

What if you wanted to simulate playing Craps, which requires rolling two dice and adding them together? How would you do that?

Show/hide solution

# Roll two dice and add them together # assumes that import random has been included roll1 = random.randrange(6) + 1 roll2 = random.randrange(6) + 1 print(roll1, "+", roll2, "=", roll1 + roll2)

That's still not bad, especially for a short little operation like this. But you can see that we're starting to repeat some of our coding, and if we had to do very much more here, we'd definitely want to come up with a different strategy for coding this.

1.7.4. Parameters and Scope

Here's a more formal development of how we can write functions that can be used in three different ways:

Let's see how to write each type of function with a few examples.

1.7.4.1. Stand-alone functions

A stand-alone function doesn't need to interact with the main program in any serious way; it doesn't require any information from the main program, and it doesn't need to return any information to the main program. In this case, the function's sole purpose is to keep your code organized so that it's easier to read and manage.

Let's say that you're writing a program that allows the user to play Blackjack on the computer. If you want to print out the instructions for the user, you could certainly put a bunch of print() statements in the main() body of your program.

But it's better to move that block of print statements to someplace else—to a function—and then we'll just call that function if needed.

In most cases, the function definition is placed before the main() defintion. The code, then, looks like this:

def give_instructions(): print("Here's how you play Blackjack!") print("Play begins with 2 cards dealt to each player...") print("...") def main(): give_instructions() . . if __name__ == "__main__": main()

When Python executes this code, it:

  1. takes note of the print_instructions function definition and checks it for syntax, but doesn't actually execute that code yet.
  2. takes note of the main() function definition and checks it for syntax, but doesn't actually execute that code yet.
  3. falls through to the bottom of the code to see what it should do. If we're running this program from the command line, then __name__ == "__main__" so the main() function (program) is executed line by line.
  4. encounters the print_instructions() line, causing execution to jump up to that function, and lines there are executed until the function is done.
  5. returns to the line after the function was called in the main() where it continues to execute instructions.

Notice that the main() program now is much less cluttered and easier to read now that I'm using it to call other functions. If all the jumping around from the bottom of the program to the main() to the print_instructions() seems a little awkward, you'll get used to it very soon!

1.7.4.2. Sending in information with parameters

In the last example, we didn't need to pass any information back and forth between the main program and the function, but most programs DO need some way of doing that. How do you pass information into the function so that it can actually do something useful? You use parameters.

Let's take a look at a complete program that actually uses parameters.

"""Calculator Program, by Richard White This program takes two numbers entered by the user and performs a mathematical operation on them. """ def add_them(number1, number2): print("The sum of",number1,"and",number2) print("is",number1+number2) def main(): n1 = float(input("Enter a number: ")) n2 = float(input("Enter a second number: ")) add_them(n1, n2) if __name__ == "__main__": main()

You can probably guess exactly how this program works. At run time, the main program is called, which asks the user to input two numbers, after which the add_them procedure is called, with those two variables as parameters. In the add_them function, the formal parameters (variables) number1 and number2 refer to the actual parameters n1 and n2. Printing number1 refers to whatever value was referred to when the function was called... and that was n1. The function takes n1 and n2 and prints their sum. Pretty straightforward to this point.

We need to talk about scope for a minute, though.

1.7.4.3. Scope

Scope

Scope refers to the area in a program where a particular variable may be used.

Local scope variables may be used "locally" (in the current function), but don't have any value outside the function.

Global scope variables have value outside a given function, and may be referred to inside a function, but they typically can't be changed by that function.

In our Calculator Program, n1 and n2 are local to main(), and global to add_them. number1 and number2 are local to add_them, and undefined outside of that function.

Exercise: Scope

Examine the following function, and predict what will happen when the program runs.

def add_them(number1, number2): answer = number1 + number2 def main(): n1 = float(input("Enter a number: ")) n2 = float(input("Enter a second number: ")) add_them(n1, n2) print(answer) # produces an error, 'answer' is not defined if __name__ == "__main__": main()

The program doesn't print out the answer that we were hoping for; the variable answer is defined in the add_them() function, but not in the main program. We'll see how to solve that issue in the next section.

1.7.4.4. Getting information back out of a function

We've learned that you can pass information into a function using parameters. But how do you get information back out?

Let's take a look at our calculator program again. What if we'd written this:

""" Calculator Program that won't work. """ def add_them(number1,number2): answer = number1 + number2 def main(): n1 = float(input("Enter a number: ")) n2 = float(input("Enter a second number: ")) add_them(n1, n2) print(answer) # This won't work if __name__ == "__main__": main()

This program won't work as we need it to, because the variable answer is "local to add_them", and undefined in our main program. We need to get the answer back out of the function somehow.

Our programming solution is to return a value.

return statements

A return statement in a function that returns operation of a program back to the point where the function was called. Any variables included as part of the return statement are sent back to the function call as a result.

def add_them(a,b): return a+b # Calculate a + b # and sends result back # to function call

Here's a version of our program, then, that does work:

"""Calculator Program that works! """ def add_them(number1, number2): return number1 + number2 def main(): n1 = float(input("Enter a number: ")) n2 = float(input("Enter a second number: ")) answer = add_them(n1, n2) print(answer) if __name__ == "__main__": main()

One common use for functions is to gather user input. Writing separate functions for "initializing" a program (setting initial values for data) and actually processing that data is very common.

Functions for input

Write a small program that includes a function to get the user's name and age. The function should pass this information back to the main program.

Show/hide solution

def get_input(): name = input("Enter your name: ") age = float(input("Enter your age: ")) return name, age def main(): user,age = get_input() # Call the function if age > 90: print("Wow,",user,"that's pretty old!") else: print(user, ", you are",age,"years old.")

Now try this one:

Functions for input and calculation

Write a small program called quadrilateral.py that includes two functions: one to get the dimensions of a quadrilateral (and return those dimensions to the main()), and one that uses the information from the first function to calculate the area and perimeter of that quadrilateral and return those to the main(). The main program should then print out the results of the analysis.

Show/hide solution

#!/usr/bin/env python3 """ quadrilateral.py This program identifies the area and perimeter for a quadrilateral of dimensions provided by the user. It also uses functions! @author Richard White @version 2017-09-27 """ def get_dimensions(): length = float(input("Enter length of quadrilateral: ")) width = float(input("Now enter width:")) return length, width def calc_area_perimeter(length, width): area = length * width perimeter = 2 * length + 2 * width return area, perimeter def main(): l,w = get_dimensions() a,p = calc_area_perimeter(l,w) print("The area and perimeter of your") print("quadrilateral are", a,"and", p) if __name__ == "__main__": main()

As you're writing this program, you want to be able to trace exactly what values each variable has as the information is passed to and from the functions.

Here's another program to emphasize the importance of functions:

Four types of functions

Write the program four_functions.py that includes four functions:

  1. The first function is called give_instructions. It takes no parameters, and it returns no values. It just prints out an explanation that the program is going to calculate the area of a rectangle.
  2. The second function is called get_input. It takes no parameters. It asks the user to enter the length and width of a rectangle, and it returns those values to the main program.
  3. The third function is called calculate_area. It takes parameters for length and width, does a calculation to determine the area, and returns that result to the main program. It doesn't print anything.
  4. The fourth function is called display_results. It takes a parameter for the area and prints out the results of the program. It doesn't return anything.

The main program calls the functions as needed.