# Programming: The BasicsPython Edition

## Summer 2020(Minor edits Summer 2021) Intro | Statements | Values | Expressions | Variables | Conditionals | Comments | Iteration | Functions | Input | Lists | Summary

### Introduction

Computation is the process of computing new values from old ones. That’s it. The values may be numbers or text or many other things, and a computer is given some values and asked to compute new ones. For example, it could be given your grades in your courses and asked to compute your GPA (grade point average). Or it could be given the prices of the items in your shopping cart and asked to compute the total including tax. Or it could be given the positions of pieces on a chess board and asked to compute the best move for one of the players.

You probably knew that. But did you know that until quite recently, a computer was someone that computes. That’s right. Computers were people who worked with (mostly) numerical values: counting votes, managing financial ledgers, solving scientific equations, etc. They often had mechanical devices such as old-fashioned adding machines or slide rules to help them, but the people were the ones who knew how to compute whatever it was they were computing.

Now, if you want to tell a human how to do something, first you need to know how to do it yourself. And then you need to be able to describe it to them in a language that they understand, using steps that they know how to do. If I want you to prepare a meal of spaghetti, first I need to know how to make spaghetti myself, and then I also need to be able to explain it to you in way that you understand and can follow. If I want you to compute a student’s GPA given their grades, first I need to know how to do it and then I need to tell you how to do it in a way that you understand and can do for yourself.

Of course, we’re not really interested in telling humans how to compute things. Since the mid-twentieth century, we have been able to build computing devices, which are what we will mean from now on when we talk about “computers.” But whether it’s a human computer or a computing device, before you can tell the computer how to do something, you need to know how to do it yourself. And then you need tell the computer what to do using a language that it understands, using steps that it knows how to do.

A program is a set of instructions for telling a computer (computing device) how to compute something. Programming is the act of creating a program. That is, it’s the process of creating a set of instructions that tell a computer how to compute something. Programs are written using a programming language that the computer understands.

Unfortunately, the programming languages that computers understand are not much like human languages. And the steps that computers know how to do by themselves are amazingly basic. Human toddlers can do more by themselves than the most powerful computer. But it’s what we have to work with.

There are many different programming languages, and programmers can be passionate about which is best. Leaving that question aside, we will be using the Python programming language for this tutorial.

• An easy (and free) way to get started programming in Python is at the website repl.it. You want to “Start Coding,” then select Python, then “Create repl.” You can type your program in the middle pane and click the “Run” button to give it to Python, or type directly to Python in the right pane.

This short tutorial is intended to teach you the basics of programming so that you can start to communicate with a computer and get it to do things for you. Think of it like learning how to say “please” and “thank you,” “how much does that cost?”, and “where is the bathroom?” in a different human language. It’s not much, but it’s a start, and it’s not that hard. We’ll look at getting the computer to do some very simple things. As you begin to understand what computers can do, you’ll be able to teach yourself how to get them to do it.

### A Note for Computer Science Students

Programming is not Computer Science.

We just said that there are two aspects involved in getting a computer to do something. First you need to understand what the computer needs to do. Then you need to tell the computer what to do in a language that it understands. Programming is the second part. Computer Science is the science behind the first part.

Computer Science is the science of computing. Just like Physics is the science of how the physical world works, and Biology is the science of how the living world works, Computer Science is the science of how the computing world works.

When you study Physics, you learn the principles of the physical world. When you study Biology, you learn the principles of the living world. When you study Computer Science, you learn the principles of the computing world: how computers (computing devices) work, how different aspects of computers are related, how to compute things, how to compare different ways of computing things, and much more. You learn the principles of computing—the fundamental concepts and rules that govern computing. And you learn how to apply those principles to problems to create applications of the principles to specific problems (a.k.a. apps).

Programming is the way that you communicate your understanding of how to solve a problem to the computer so that it can (try to) do it for you. Computer Science provides the framework for understanding computational problems and their solutions. Although most topics in Computer Science involve programming, the programming is not really the point. Programming is how a Computer Scientist puts their ideas and principles into practice.

This short tutorial is about programming. We’ll work on simple problems where you should be able to figure out what the computer needs to do fairly easily. The challenge for now is learning how to “speak” using a programming language. If you go on to study Computer Science, you’ll learn the principles of computing and how to apply them to harder problems.

So let’s get started.

### Statements

Like a human essay, speech, or conversation, a program is a sequence of statements. Each statement tells the listener something. In the case of a program, the programmer is telling the computer something.

The simplest statements are commands: “do something.”

What do you think the following command statement will do? print(123)

Try it.

What are you telling Python to do? Print. What do you want it to print? 123. So this is a print statement or print command.

You can also tell Python to print several things: print(1, 2, 3, 123)

You can give the `print` command more than one thing to print, separated by commas, and it will print them all, separated by spaces, on the same line. Python then starts a new line for the next print statement.

That’s all we need to know about printing for now.

### Values

What do computers compute? They compute values.

Numbers are values and 123 is the written decimal representation of a number. So you can tell Python to print the number (the value) 123 like we just did.

You can also have numbers with fractional parts. Try these:

print(3.14159) print(0.001)

The whole numbers are called integers and the numbers that can have fractional parts are called floats. Python keeps integers and floats separate, but you don’t usually have to worry too much about the differences between them.

Numbers aren’t everything. You can also have values that are text.

print("Hello world!")

In programming, a sequence of characters is also called a string, as in a string of beads, a string of pearls, a string of horses, a string of hit songs, or a string of Christmas lights. So text values in programs are also called strings.

The doublequotes (") tell Python that you want to print literally the characters capital-h, e, l, l, o, space, w, o, r, l, d, exclamation point. So a sequence of characters in quotes is also called a string literal. It’s how you write a string value in your program, just like writing the digits 1 2 3 is how you write a numeric literal value. (In Python, you can also use single quotes to write string literals.)

### Expressions

Computers can compute new values from old ones. That’s what computing is all about.

For example, try this: print(1+2)

Instead of a numeric literal (a number) or a string, here we’re asking Python to print the value of an expression. Python computes the value of the expression, in this case the sum of 1 and 2, and gives that value to the `print` statement to print.

Python understands lots of basic math: `+` and `-`, `*` for multiplication, `/` for division, parentheses for grouping, and more. For example: print(1+2*3) print((1+2)*3)

You can see that Python understands the standard order of operations (multiplication before addition) and has parentheses for when you want to specify some other order.

One cool thing is that `+` also works with string values. What do you think this will print? print("abc" + "def")

Try it.

You can use an expression whenever you have a formula for computing something, and then your program can compute the value for you.

#### Exercises

1. An American football field is 100 yards long and 50 yards wide. What’s the area of the field in square yards?
Area of a rectangle (such as a field) is length times width: print(100 * 50)
2. What’s the area of a circle with radius 10 meters in square meters?
Area of a circle with radius r is π r2: print(3.14159 * 10 * 10)
3. A person’s first name is “Mary,” their middle initial is “J,” and their last name is “Smith.” Their daughter is also named Mary J. Smith, so they go by “Mary J. Smith, Sr.” Use an expression to combine the parts of their name properly into a single string value and print it.
print("Mary" + " " + "J" + "." + " " + "Smith" + "," + "Sr.")

### Variables

Suppose that you want to know the area of two American football fields. Or two circles of radius 10. print(100 * 50 + 100 * 50) print(3.14159 * 10 * 10 + 3.14159 * 10 * 10) Seems awkward. Easy to make a mistake cutting and pasting. Hard to read this program and understand what the expression is computing.

Wouldn’t it better to compute the area once, and then use it twice? Something like this: area = 100 * 50 print(area+area) area = 3.14159 * 10 * 10 print(2*area)

This is our second kind of statement: an assignment statement.

The name on the left of the equals sign is a name with which we want to associate with a value. This is called a variable because the associated value can vary (change).

The assignment statement tells Python to associate the value of the expression on the right with the variable on the left. In other words, make the value associated with the name be the value of the expression. This is called assigning a value to a variable.

Once you’ve done this, you can use the name of the variable in an expression, and Python will substitute its current value, like in our `print` statements.

Note that if you try to use the value of a variable that has not be defined, you will get an error from Python: print(volume) ... NameError: name 'volume' is not defined So don’t do that.

You use variables to make your code clearer, not just to avoid cut and paste. The name of a variable tells a human reader the meaning of its value. It takes a bit of practice, but using variables and expressions is an important part of making your programs readable by humans (including yourself!)

#### Exercises

1. Use variables for the length and width of a rectangular field, and use an expression involving those variables to compute its area.
length = 100 width = 50 area = length * width print(area)
2. Use a variable for the radius of a circle and for pi (π), and use an expression involving that variable to compute its area.
3. Use a variable for a person’s first name, middle initial, last name, and suffix (Jr., Sr., etc.), and use an expression involving those variables to compute the full name.
firstName = "Mary" middleInitial = "J" lastName = "Smith" suffix = "Sr." fullname = firstName + " " + middleInitial + ". " + lastName + ", " + suffix print(fullname)

One more thing about variables: In math, you usually have to “solve for” the values of variables. For example, you’re given one or more equations involving one or more variables, and the goal is to find the values of the variables that make the equations true.

In programming, variables are just names for values. You can change the value associated with a name at any time using an assignment statement.

You can change the value assigned to a variable. For example: height = 3 print(height) height = 21 print(height)

You can also use the current value of the variable in the expression when you assign it a new value. For example: x = 1 print(x) x = x + 1 print(x)

In math, “`x = x + 1`” does not make sense. In programming, it means use the current value of `x` in the expression `x+1` and assign the value of the expression back to `x`. The value of `x` after the first assignment statement is 1, so `x+1` is 1+1 or 2. So the new value assigned to variable `x` is 2, and that’s what gets printed.

### Conditional Statements

You can do quite a lot of useful computing using only assignment and print statements with variables and expressions. But a program like that will always do the same thing. Sometimes you want your programs to do different things in different circumstances.

A conditional statement lets you tell the computer to test a condition in order to decide whether or not to do something. For example, here’s an `if` statement:

x = 25 if x > 0: print(x, "is positive")

The keyword `if` is followed by an expression that must evaluate to either true or false. Python evaluates the expression and if the result is true, then it executes the indented statements following the colon (only one in this example). These are called the “then” clause of the statement, because if the condition is true, then the statements are executed.

If the condition is false, Python skips the indented statements and continues executing the program at the next non-indented line.

Or you can tell Python what to do if the condition is false: if x > 0: print(x, "is positive") else: print(x, "is negative or 0") This is called an “else” clause for obvious reasons, and it is part of the `if` statement.

Note the colons and the indentation. Very important in Python. Other programming languages do it differently, but they all have conditional statements of one kind or another.

You can give additional conditions to test using `elif`: if x > 0: print(x, "is positive") elif x < 0: print(x, "is negative") else: print(x, "is 0") You can have as many `elif` clauses as you want. Whichever condition evaluates to true first, the indented statements following it are executed and the rest are skipped. If no condition evaluates to true, then the `else` clause is executed (if there is one, otherwise nothing is executed).

You can also nest conditional statements. That is, the statements in the clauses of one conditional statement may themsleves be conditional statements. For example: if x > 0: if x > 100: print(x, "is positive and large") else: print(x, "is positive and small") else: print(x, "is not positive") Of course, you could have a nested conditional in the `else` clause, and you could have `elif` clauses for the inner conditional, and you could nest conditional statements as deeply as you want (although it gets quite hard to follow after a while).

There are many ways to specify a condition in Python. Here are a few of the most common:

• x `==` y : True if value x is equal to value y. (Note: not single equals sign!)
• x `!=` y : True if value x is not equal to value y.
• x `<` y : True if value x is strictly less than value y.
• x `<=` y : True if value x is less than or equal to value y.
• x `>` y: True if value x is strictly greater than value y.
• x `>=` y : True if value x is greater than or equal to value y.

These comparisons work for both numeric and string values, which is cool.

Conditions can also be combined to make more complicated conditions:

• `and`: The condition “c1 `and` c2” is true if both c1 and c2 are true
• `or`: The condition “c1 `or` c2” is true if either c1 is true or c2 is true (or both)
• `not`: The condition “`not` c” is true if c is false, and is false if c is true

With conditional statements, your programs can do more than just compute new values from old values. Now they can make decisions.

#### Exercises

1. Suppose that you have a variable `n` whose value is the number of dogs at an animal rescue shelter. Use a conditional statement to print its value as either “n dog” (singular) or “n dogs” (plural), where n is the value of the variable. Test your code by assigning different values to the variable and running the program.
There are many ways to do this. Here’s one that does exactly what the question asks: if n == 1: print("1 dog") else: print(n, "dogs") Note that in English, if there are no dogs, so `n` has value 0, the correct phrase is plural: “0 dogs.”
2. Repeat the previous exercise, but use a variable to store the proper form of the word “dog,” set its value using a conditional statement, and then print the phrase.
Here are two ways to do this: if n == 1: dogString = "dog" else: dogString = "dogs" print(n, dogString) dogString = "dog" if n != 1: dogString = dogString + "s" print(n, dogString) You might consider whether one is better than the other. The answer is: not really for this exact problem. But what if you also had cats and other animals at the shelter and needed to report on all of them?
3. Suppose that you have a variable `temp` whose value is the temperature of water measured during an experiment, in degrees Fahrenheit. Use a conditional statement to print whether or not the water is solid , liquid, or gas. Test your code by assigning different values to `temp` and running the program.
There are three possible states, so there are three clauses in our conditional statement. Water is solid at or below 32 degrees F and vapor at or above 212 degrees F. Here’s one possible way of doing it: if temp <= 32: print("ice") elif temp >= 212: print("vapor") else: print("liquid")
4. The water scientist from the previous exercise tells you that the temperature is actually in degrees Celsius rather than Fahrenheit. Change your conditional statement for this situation.
Water is solid at or below 0 degrees C and vapor at or above 100 degrees C. if temp <= 0: print("ice") elif temp >= 100: print("vapor") else: print("liquid")
5. Repeat the previous exercise (using temperature measured in degrees Celsius) without changing your original conditional statement. That is, use the same conditional statement, but now the value of `temp` is in degrees Celsius.
Use an expression to convert from degrees C to degrees F.
temp = temp * 9.0/5.0 + 32 if temp <= 32: print("ice") elif temp >= 212: print("vapor") else: print("liquid") Note that it would probably be better to use two variables, `tempC` and `tempF`, rather than having one variable whose value is sometimes degrees C and sometimes degrees F. But the question said not to change the conditional statement, and it uses `temp`, so...
6. Big dogs bark. Little dogs squeak. Big dogs with long fur also get hot. Little dogs with short fur need to wear a coat. Suppose that you have two variables describing a dog: the value of one variable is its size, big or little, and the value of the other is the length of its coat, long or short. Use nested conditional statements to print out a description of the dog.
Many possibilities. Here’s one that reads like the description in the problem: size = "big" coatLength = "long" if size == "big": print("This dog barks.") if coatLength == "long": print("And it gets hot.") elif size == "small": print("This dog squeaks.") if coatLength == "short": print("And it needs a coat.") It would probably make sense to have an `else` to handle any other values of `size`, even if all you do is print an error message or “I don’t know.”

As your programs get bigger, it becomes harder to figure out what they’re doing. After all, they’re written in a strange language that is not any human’s native language. It is therefore helpful to include some comments, written in English (or any human language), to help future readers of the code.

In Python, comments are indicated by the hash symbol `#` (also called a number sign or pound sign): # This is a comment A comment may be an entire line, like the one above, or added at the end of a line: y = 1 + x + x * x # First three terms of Taylor series for 1/(1-x)

Python ignores any characters after a hash symbol until the end of the line. That’s right. Comments are ignored by Python. Python doesn’t understand English (or any human language) anyway.

But if you’re working as part of a team of programmers, comments allow you to explain your intent, what you’re trying to do, to other members of the team. Maybe your code is perfect, but it still might be hard for them to understand it. Or maybe it’s not working, and it would be good for them to know what you were trying to do with it so that they can work on fixing it.

And in fact, the future readers of your comments may well include you yourself! After a hard night of programming, when you return to work the next day, you may well not remember what it was you were trying to do. Or why you thought that a certain piece of code did the job. Comments in your code will give you the context that you need to understand it.

Comments are not a replacement for using meaningful variable names and breaking your programs into understandable chunks. But in combination with writing clear code, comments make programs self-documenting.

### Iteration (Loops)

Challenge #1: Suppose I ask you print five asterisks, each on a line by themselves. What would you do? Try it yourself, then check my answer.

print("*") print("*") print("*") print("*") print("*")

Not too hard. But what if I’d said one hundred asterisks? Or one thousand? Painful. You’ll probably do cut-and-paste and try to count in your head. What’s the chance of your getting it right and knowing that you got it right? Probably pretty low.

Challenge #2: Suppose I ask you to print the numbers from 1 to 5, each on a line by themselves. What would you do?

print(1) print(2) print(3) print(4) print(5)

Also not too hard. But what if I’d said 1 to 100? or 1000? Even more painful than before, right? Not only do you have to cut-and-paste many times, you also have to edit each line to print the appropriate value. You’re unlikely to get it right, and also it’s a lot of programming work for a really simple program.

One more challenge: Print the numbers from 1 to some other number that you don’t know until the program runs (that is, it’s stored in a variable). Don’t try too hard on this one before you check my answer.

Trick question! You can’t even write this program, since you don’t know how many times to cut-and-paste the print statement. Hmm...

We want to do the same thing, or almost the same thing, some number of times or until some condition is met. And in fact, doing something some number of times is equivalent to doing it until you have done it the required number of times.

This is called iteration, from the Latin iterum meaning “again.” There are several types of iteration statements. For example, here’s a `while` statement: row = 1 while row <= 5: print("*") row = row + 1 Try it (it solves challenge #1).

There’s the keyword `while`, then a condition that can be either true or false, and then a sequence of one or more statements indented after the colon. These are called the body of the statement. A `while` statement executes its body “while” the condition is true.

When Python executes a `while` statement, it first tests the condition. If the condition is false, the body is skipped and execution continues with the next statement in the program. This is just like when an `if` statement skips any clauses whose conditions are false.

But if the condition is true, the `while` statement executes the statements in its body and then comes back to the start and tests the condition again. If the condition is true, the body is executed again, and so on, until the condition is false when it is tested.

Because the program may “loop back” and execute its body more than once, iteration statements are also called loops and a `while` statement is also called a `while` loop.

What about challenge #2: printing the numbers from 1 to 5? Instead of printing an asterisk, we’re supposed to print the number itself. Try it yourself using a `while` loop, then check my answer.

row = 1 while row <= 5: print(row) row = row + 1

It’s the same program, but now we’re printing the value of the variable `row` each time around the loop.

The value of variable `row` is 1 when Python first tests the condition. Yes, that’s less than or equal to 5, so Python executes the body of the statement. Those two statements tell Python to print the value 1, and then increment `row` (to 2). Python loops back to the start and tests the condition again. Yes, the value of `row`, now 2, is less than or equal to 5, so execute the body again. This time the `print` statement prints 2, since that’s the value of `row`, increments `row`, and repeat for 3, 4, and 5.

The loop stops when `row` gets incremented to 6, because then the condition `row <= 5` is false. Python skips the loop body and continues at the next statement in the program. You can check the value of `row` after the loop by printing it. Try it.

For challenge #3, let’s suppose that the limit for our printing is in some other variable, such as: limit = 5 Perhaps you computed it somewhere else, read it from a file, or got it from the user (we’ll see how to do that shortly).

How can you use a `while` statement to print the numbers from 1 to that limit? Try it yourself, then look at my answer.

limit = 5 row = 1 while row <= limit: print(row) row = row + 1 It’s the same pattern, only with the value of the variable `limit` being used in the loop condition rather than the numeric literal 5. So the loop limit is variable—it depends on the value of the variable `limit` at the time the condition is tested.

Remember: conditions are just expressions whose value is either true or false.

Iteration statements can be nested just like conditional statements. And in fact, you can use a conditional statement in the body of an interation statement and vice-versa.

A `while` loop, and iteration statements in general, allow you to perform repetition with variation. There are other forms of iteration statements in Python, but this is enough for for us for now.

#### Exercises

The following exercises involve printing different patterns. For these, you may sometimes want to use multiple `print` statements to build up a single line of output.

In Python, you can tell the `print` command not to print a newline at the end by adding `end=""` as the last thing to print. That is, tell `print` to end the line with... nothing (an empty string containing no characters): print(1, 2, 3, end="")

To end a line by printing only a newline, use a `print` statement with no arguments, just empty parentheses: print()

Now on to the exercises.

1. Using a `while` loop, write a program that prints 5 stars (asterisks) on a single line with no spaces between them, followed by a newline.
# 5 stars on a single line, followed by a newline col = 1 while col <= 5: print("*", end="") col = col + 1 print()
2. Write a program that prints a 5x5 square of stars (5 stars on each of 5 consecutive lines). You could do this by copying and pasting the code for the previous exercise five times. Don’t do that. Instead, use two `while` loops, one nested within the body of the other.

You can reuse your code for printing a single row of stars verbatim (without changing it). You just need to figure out where to put it in a new, bigger program.
# 5x5 square of stars row = 1 while row <= 5: col = 1 while col <= 5: print("*", end="") col = col + 1 print() row = row + 1
3. Write a program that prints a right triangle of stars 5 lines high, with the vertical edge of the triangle on the left side. Like this: * ** *** **** *****

You could do this by copying and pasting your code for printing a row a stars five times and adjusting the limits of the loops. Don’t do that. Use only two nested `while` loops.

What is the relationship between the rows of the figure and their length (the number of stars in the row)? Although this problem seems quite different from the previous one, the code is almost identical.
If you think about it, row number 1 contains 1 star. Row number contains 2 stars, and so on. Here’s the code: # Right triangle, left-aligned, height=5 row = 1 while row <= 5: col = 1 while col <= row: print("*", end="") col = col + 1 print() row = row +1
4. Print a right triangle of stars 5 lines high with the vertical edge of the triangle on the right side. Use nested `while` loops.
Draw a picture: * ** *** **** ***** Every row of the triangle has length 5. Row 1 has 4 spaces and 1 star. Row 2 has 3 spaces and 2 stars. And so on.
Here’s one way of doing it: # Right triangle, right-aligned, height=5 row = 1 while row <= 5: col = 1 while col <= 5: if 5-col >= row: print(" ", end="") else: print("*", end="") col = col + 1 print() row = row +1 It’s the same pattern, except that we know that each row will have 5 characters, and we use a conditional statement to decide whether each character is a space or a star. You could write that conditional many ways.
5. How would you change the previous programs if the size of the pattern was not fixed at 5 but was instead stored in a variable? Do it.
Replace the numeric literal 5 with the use of a variable (perhaps `size` would be a good name for it). Go ahead and do it.
6. Write a program using a `while` loop that sums (adds up) the numbers from 1 to a given number. Test your program for several different limits.
Use a variable, which I’ve named `total`, to keep a running total within the loop over the numbers from 1 to the limit. # Add numbers from 1 to limit limit = 5 total = 0 num = 1 while num <= limit: total = total + num num = num + 1 print("sum of numbers from 1 to", limit, "=", total) This is a very common idiom (way of speaking/writing) in programs.
7. Write a program that sums the numbers from a given start number up to and including a given end number.
Minor change: # Add numbers from start to end (inclusive) start = 1 end = 5 total = 0 num = start while num <= end: total = total + num num = num + 1 print("sum of numbers from", start, "to", end, "=", total)

### Functions

Suppose that we want to compute the sum of the numbers from 1 to 5, from 1 to 10, and from 1 to 100. We could copy the program from the previous section’s exercises three times and edit them each a tiny bit, but that’s going to be ugly and likely to result in errors. So we won’t do that.

Instead, let’s tell Python how to do the summing in such a way that we can easily get it to compute any such sum. def sum(limit): "Return the sum of the numbers from 1 to the given limit." num = 1 total = 0 while num <= limit: total = total + i num = num + 1 return total

The keyword `def` tells Python that we are defining a new function. You probably know that in math, a function maps “input” input elements from its domain to “output” elements from its range. In programming, a function tells the computer how to compute the output values from the input values.

The name of the function follows `def`, in this case we are defining a function named `sum`. You should always use a name that clearly identifies what the function does. In this case, it computes a sum. Nice.

The inputs to the function are then listed in parentheses. In this example, we need to be given one value, the “limit” up to which we need to compute the sum. In the definition of a function, the inputs are called parameters (“a numerical or other measurable factor forming one of a set that defines a system or sets the conditions of its operation,” New Oxford American Dictionary). And then, in Python, a colon and the body of the function, its code, indented following the colon.

In this example, the string at the start of the body is called a doc string, short for documentation string. It is optional, but I strongly recommend that you always include one in any function that you write. Although Python will just skip over it, it explains your function to someone reading your code. And there are even tools that can automatically generate documentation from docstrings, which is why they are better than comments for documenting functions.

Following the docstring is the main body of the function. And check it out: it’s the code from the last exercise of the previous section that computes the sum of the numbers from 1 to a given limit. In other words, we’re telling Python that that’s what to do if someone asks it to compute a sum.

The last statement tells Python to `return` the value of the given expression, in this example the value of the variable `total`, as the value of the function. A `return` statement is often the last statement in a function, but it doesn’t have to be. But whenever it is executed (for example, in a conditional statement), the execution of the function terminates and the value of the given expression is returned as the value of the function.

Now, to use our new function, we call it. That is, we ask it to do its thing and give it whatever inputs it requires. For example: s = sum(5) print(s)

We use the name of the function and provide values, called arguments, one for each of the function’s parameters. In this example, the `sum` function has one parameter, `limit`, so we provide one value, 5. You can use any expression to provide the argument value(s). Python will evaluate the expressions to determine their values and then pass those values to the function.

Each time your program calls a function, Python treats each parameter like a variable, and sets its value to the corresponding argument. So in our example, the only parameter of the `sum` function is `limit`, so Python assigns the value of our only argument, 5, to the variable `limit`.

Python then executes the body of the function until a return statement is executed (or the end of the body is reached). In our example, it will sum the numbers from 1 to the value of `limit` (which is 5 in this example) using the variable `total` and then return the value of that variable. In this example, the total is 15.

Try it. You can print the value of `total` inside the loop in the body of the function if you want to watch what happens. Try that also.

After the function call returns, Python continues executing where it left off, and substitutes the return value of the function for the function call. In our example, it was computing the value of an expression in order to assign it to the variable `s`. So it will assign 15 to `s`, and then go on to print that.

A couple of quick things about functions:

• First, Python comes with some functions builtin. We’ve seen one of them already... the `print` function. There are many more builtin functions and functions in the Python standard library.
• Second, some functions don’t actually compute a function in the mathematical sense, but rather they do something. Like the `print` function, for example. A call to the `print` function causes output to appear in the console, but it doesn’t actually return anything meaningful.

Here’s another example of a function that doesn’t return a value: def printStars(n): "Print the given number of stars (asterisks) on the same line." i = 1 while i <= n: print("*", end="") i = i + 1 This function does what its docstring says. But, like print, it doesn’t return anything. BTW: You can read all the gory details of the `print` function in its documentation.

In some programming languages, this would be called a procedure. In Python there are only functions, and in fact they always return something. But you would probably never use the value returned by a call to `print` or `printStars` in an expression.

• Finally, the variables that Python sets up based on the function’s parameters only exist while it is executing the body of the function. So you can print the value of `limit` within the body of the function and it will print whatever was passed as the argument to `sum`. But try printing the value of `limit` outside the body of the function, for example together with `s` after the call to `sum`. You will get an undefined name error.

In summary, functions are a very powerful way to structure your code. They allow code to be reused (used multiple times in different places in a program) without cut-and-paste. More interestingly, you can think of functions as extending the Python language with new capabilities that you designed. Very cool.

#### Exercises

1. Turn the program for summing the numbers from a given start to a given end (inclusive) into a function. Test it on a different combinations of arguments.
def sum(start, end): "Add numbers from start to end (inclusive)." total = 0 num = start while num <= end: total = total + num num = num + 1 return total print(sum(1, 5), sum(1, 10), sum(1, 100))
2. Write a function that computes and returns the average (mean) of three numbers given as arguments.
Don’t repeat yourself. Computing the mean involves computing the sum, and you already know how to do that. Use it.
def mean(n): "Compute the average (mean) of the numbers from 1 to n." return sum(1, n) / n
3. Convert your loop programs from the previous section into functions that print shapes using stars (asterisks). The functions should have one or more parameters that specify the size of the shape.

### Getting Input From The User

What do you think the following program will do? x = input() if x == "xyzzy": print("you typed the magic word!") else: print("you typed", x, "; boring")

Perhaps you guessed this, but I should tell you that `input()` is a call to the Python builtin function `input`. It takes no arguments and it returns the next string that the user types, up to when they type Return. (That’s good enough for now.)

Try the program if you haven’t already.

Now you know how to get a string from the user. Your programs can now be interactive!

Let’s try `input` with our conditional statement that tests for positive, negative, or zero: x = input() if x > 0: print(x, "is positive") elif x < 0: print(x, "is negative") else: print(x, "is 0")

Oops. `input` always gives you what the user typed as a string, but you need a number in order to compare it to the numeric value 0. (The first program worked because you were comparing two strings.)

Luckily for us, Python has builtin functions to convert a string into an integer (whole number): s = input() i = int(s) # or i = int(input())

Use `float` instead of `int` if you want a number with a fractional part (if any): f = float(input())

And just for completeness, if you have a number (numeric value) and you want a string, Python provides the builtin function `str`: n = 1.5 s = "The value of n is " + str(n) print(s)

#### Exercises

1. Ask the user for a string and print that string 5 times on consecutive lines. Make sure that you print a prompt before you call `input` so that the user knows that you’re waiting for them (and what they’re supposed to enter).
def printSomethingFiveTimes(): print("What should I print five times? ", end="") str = input() i = 1 while i <= 5: print(str) i = i + 1
2. Ask the user for a number and print the numbers from 1 up to that number on consecutive lines.
def printUpToSomeNumber(): print("Up to what number should I print? ", end="") limit = int(input()) i = 1 while i <= limit: print(i) i = i + 1
3. Ask the user for a string and then for a number and print that number of copies of the string on consecutive lines.
def printSomethingSomeNumberOfTimes(): print("What should I print? ", end="") str = input() print("How many times should I print it? ", end="") limit = int(input()) i = 1 while i <= limit: print(str) i = i + 1
4. Ask the user for a number and print the numbers from that number down to 1 on consecutive lines.
def printDownFromSomeNumber(): print("Down from what number should I print? ", end="") start = int(input()) i = start while i >= 1: print(i) i = i - 1
5. Harder: Write the function `int` for yourself (give yours a different name).
If `s` is a variable whose value is a string, and `expr` is an expression whose value is some number i, then `len(s)` is the number of characters in the string, and `s[expr]` is the i’th character in the string, starting with i=0.
def myint(s): value=0 i=0 while i < len(s): digit_str = s[i] if digit_str == "0": digit_num = 0 elif digit_str == "1": digit_num = 1 elif digit_str == "2": digit_num = 2 elif digit_str == "3": digit_num = 3 elif digit_str == "4": digit_num = 4 elif digit_str == "5": digit_num = 5 elif digit_str == "6": digit_num = 6 elif digit_str == "7": digit_num = 7 elif digit_str == "8": digit_num = 8 elif digit_str == "9": digit_num = 9 else: return value # or you might signal an error here... # Shift one place value left and add current digit value = value * 10 + digit_num # On to next digit i = i + 1 # After all the digits, return the final value return value done = False while not done: print("Enter a number: ", end="") str = input() if str == "": break num = myint(str) + 0 # Check that it’s a number print("string", str, "=", num)

### Lists

Suppose that you are developing a program to analyze student grades. This requires, first, that you be able to store the grades in your program. And then second, that you know how to access them in order to analyze them. Python makes this quite easy.

If you know the grades at the time you’re writing the program, you can tell Python to create a list containing them and assign that to a variable: grades = [ 95, 72, 88, 75, 72, 80 ]

The square brackets, “`[ ]`”, indicate a list. Python reads the comma-separated expressions between the brackets and creates a list containing their values.

In this example, the expressions are just numbers, but you can have lists of anything, and Python even allows you to have different types of things in one list. For example: things = [ 42, "Hello", -123.456 ]

You can also create an empty list: prices = [ ] And you can add items to the end of a list: prices.append(10.99) prices.append(7.50) print(prices) # Prints [10.99, 7.50]

The addition operator “`+`” works with lists by combining them. It creates a new list containing the elements of the first list followed by the elements of the second list. For example: evens = [ 0, 2, 4 ] odds = [1, 3, 5 ] print(evens + odds) # Prints [0, 2, 4, 1, 3, 5]

The Python builtin function `len` gives you the length of the list (how many elements are in it): print(len(grades))

Each element in a list has an index—its position in the list, starting at index 0. To access an element of a list, use its index as follows: print(grades) # Prints 92 print(grades) # Prints 75 Don’t get these square brackets confused with the square brackets used when you create a list (a list literal). They’re both about lists, but in this case we’re indexing into the list to get one of its elements.

You can use indexing to iterate over all the elements of a list (that is, to use an interation statement to access one element of the list after the other on each iteration): i = 0 while i < len(grades): g = grades[i] print(g) i = i + 1 Note that the loop condition uses “strictly less than” (`<`) since the indexes start at 0, not 1, so the index of the last element in the list is one less than the length of the list.

It is so common to iterate through the elements of a list that Python provides a different kind of iteration statement for it, a `for` statement: for g in grades: print(g) This is easier to use, but only if you don’t need to know the index of the elements as you’re iterating over them.

The Python builtin function `sorted` takes a list as argument and returns a new list with the same elements but sorted into their “natural” order: print(sorted(grades)) # Prints [72, 72, 75, 80, 88, 95] This leaves the original list unchanged. You may use the following to sort a list “in place”: grades.sort() They look quite similar, but print the list before and after the two different calls. You’ll see the difference.

This is enough to get you started with lists. The official Python Tutorial has An Introduction to Lists and More on Lists.

#### Exercises

1. Suppose you have a list of students’ names (say their last names) stored in a list. Write a program that prints the names in sorted order, each on a separate line.
names = [ "Pawlicki", "Ferguson", "Brown", "Einstein" ] for name in sorted(names): print(name)
2. Suppose that you have the grades for a class stored in a list, as shown above. Write functions to compute the minimum, maximum, mean (average), and median grade, respectively, of a list of numbers passed as argument.

FYI: “The median of a set of numbers is the ‘middle’ number, when the numbers are listed in sorted order. If there is an even number of numbers, then there is no single middle value; the median is then usually defined to be the mean of the two middle values.” (Wikipedia)

• Maximum
def maximum(numbers): biggestSoFar = None for number in numbers: if biggestSoFar == None or number > biggestSoFar: biggestSoFar = number return biggestSoFar
• Minimum
def minimum(numbers): smallestSoFar = None for number in numbers: if smallestSoFar == None or number < smallestSoFar: smallestSoFar = number return smallestSoFar
• Mean
def sum(numbers): total = 0 for number in numbers: total = total + number return total def mean(numbers): return sum(numbers) / len(numbers) # Better not be empty
• Median (Harder)
There are several ways to test whether a number is even or odd. For example, if a number n is even, then `int(n/2)*2 == n`. You can also use the “modulus” or “remainder” operator: `n % 2` is the remainder when n is divided by 2 using integer division. And BTW: 0 is even.
def median(numbers): # Use sorted() so we don't change the list we were given sortedNumbers = sorted(numbers) # % is the modulus or remainder operator if len(numbers) % 2 == 1: # Length of list is odd index = int(len(numbers)/2) # Return the middle number return sortedNumbers[index] else: # Length of list is even (but better not be empty) index1 = int(len(numbers)/2) index2 = index1 - 1 n1 = sortedNumbers[index1] n2 = sortedNumbers[index2] # Return average of the two numbers around the middle return (n1 + n2) / 2
3. Write a function that swaps the elements of a given list at two given indexes. That is, if `list` is a list and `i` and `j` are indexes of elements in the list, then after calling `swap(list, i, j)`, the element of the list previously at index `i` will now be at index `j` and vice-versa.
def swap(list, i, j): tmp = list[i] list[i] = list[j] list[j] = tmp
4. (Harder) Can you use your `swap` function to sort a list “in place,” like the builtin function `sort`? Think about it, then check out the hint.
There are many ways to sort a list in place. Here’s one idea. You know that the smallest element in the list has to be first, right? So find the smallest element in the list and swap it with the current first element (if it’s not already first). Now you have the same problem with the remainder of the list, which is one element shorter. Repeat until you have seen all the elements.
Selection Sort (there are other possibilities): def selectionSort(list): "In-place selection sort of the given list." # For each position in the list i = 0 while i < len(list): # Find the smallest element in the rest of the list from position i indexOfSmallest = None j = i while j < len(list): if indexOfSmallest == None or list[j] < list[indexOfSmallest]: indexOfSmallest = j j = j + 1 # Swap it with the current element (if needed) if i != indexOfSmallest: swap(list, i, indexOfSmallest) # On to next i = i + 1 If you want to copy a list so that you can sort it and keep the original: list2 = list1.copy()
5. (Harder) How about your own version of the Python builtin function `sorted` (that is, a function that takes a list as argument and returns a new list with the same elements but in sorted order, say smallest to largest)? Think about it, then check out the hint.
Again, there are many ways to create a sorted copy of a list. Here’s one idea. For each element in the original list, find its place in the sorted list (so far), and insert it there. When you’re done, return the sorted list.

FYI: You can insert an element into a list before a given index using list.insert(index, element) If the index is 0, the element is inserted at the start of the list. If the index is equal to `len(list)`, the element is inserted at the end of the list (since `len(list)` is one more than the index of the last item in the original list).

Insertion Sort (there are other possibilities): def insertionSort(originalList): resultList = [] # For each element of the original list for element in originalList: # Find where it goes in the result (so far) index = 0 while index < len(resultList) and resultList[index] < element: index = index + 1 # And insert it there (which may be at the end) resultList.insert(index, element) # Return the sorted list return resultList

### Summary

We have covered all the basics of programming. We have used the Python programming language, but all programming languages have similar elements. The details are different, but the concepts are the same.

• Statements: e.g., `print` to produce output
• Values and expressions
• Variables and assignment statements
• Conditional statements: `if`-`elif`-`else`
• Iteration statements: `while` and `for`
• Functions: definition (`def`), parameters, calling, arguments, `return`; builtin and library functions
• User input: `input`
• Lists