Programming Basics

Programming Basics

We'll usually express our algorithms with programs. A computer program is basically a description of an algorithm that can be understood (and followed) by a computer. That's really all there is to programming: expressing what you want the computer to do, in a way it can understand.

Programming Basics

A programming language is a way for human to write such a description. All programming languages (Python, C++, Java,…) are trying to solve that same basic problem.

Compare natural languages (English, French, Japanese) which are in a sense just different ways to express the same ideas. Some ideas may be easier to express in Japanese than English and some things may be easier to express in Python than Java, but the basics are fundamentally the same. They can all express the same concepts.

Python

Python is the programming language we'll use in the course.

Python was designed to be relatively easy to work with as a first programming language. It's also well-suited to many tasks: commonly used in data analysis, web development, etc.

Starting With Python

Python is free to download. I suggest you mostly work in IDLE (the Integrated DeveLopment Environment).

When you start IDLE, you'll see an interactive interpreter where you can test code one line at a time.

To create an actual program: File → New File. Then save as a .py file.

Starting With Python

A Python program is a series of statements. A statement is baslically a single instruction in your program.

Python follows the instructions (executes the statements) in order (until we learn ways to control the order they are executed, at least).

Starting With Python

Let's write our first statement:

print("Hello world!")

This can be typed in the IDLE interactive interpreter and it will run as soon as you press Enter.

Or, in a separate window and saved as hello.py. Then it will run when we select Run → Run Module.

Starting With Python

print("Hello world!")

This statement…

  • Is a print statement: it's used to display characters on the screen.
  • Contains the string "Hello world!". A string is a sequence of characters.

A print statement displays whatever is in the parentheses: in this case, the 12 characters in that string.

Doing Calculations

We will need to do calculations to implement most algorithms.

e.g. in the guessing game, we need to calculate halfway between the smallest and largest, which is something like \[\left\lfloor\frac{\mathit{smallest}+\mathit{largest}}{2}\right\rfloor\,,\] i.e. calculate the average and round down.

Doing Calculations

An expression is any kind of calculation that produces a result.

Some examples of numeric expressions where the result is a number:

ExpressionResult
100 + 8108
6 * 1272
10 + 2 * 316
(10 + 2) * 336

Note: order of operations as-expected.

Doing Calculations

So far, all we have seen to do with the result of a calculation is printing it:

print(20 * 6)

We will see more places to use expressions later but the short explanation: anywhere you need a value in Python, you can write an expression and it will be calculated.

Doing Calculations

Expressions can also be used to build a string: these are string expressions. Most notably, the + can be used to join strings together (i.e. concatenate them). You can also use * and a number to repeat a string.

ExpressionResult
"CMPT" + "120""CMPT120"
"CMPT" + " 120""CMPT 120"
"100" + "8""1008"
"AB" * 3"ABABAB"

Doing Calculations

Notice that a number and similar-looking string are different things in Python, and they are treated differently. When you type 10, it's a number (i.e. the integer after 9) and "10" is a string (containing two characters, 1 and 0).

ExpressionResultWhy?
10 + 212numeric addition
"10" + "2""102"string concat
10 * 220numeric multiply
"10" * 21010string repetition
10 * "2"2222222222string repetition
10 + "2"error: can't add number and string

Functions

An expression can also include the evaluation of functions.

A functions takes zero or more arguments and returns a result (or return value).

Functions

For example, there's a function len that calculates the length of strings (among other types). This is an expression with a function call:

len("abcd")

The function is len. It takes one argument, which is "abcd" here. It returns the number of characters in the string: 4 in this example.

Functions

We have seen print which is also a function in Python. It doesn't return anything but instead does something: it displays some characters on screen.

The value returned by a function can be used like any other value. e.g. we can print it.

print(len("abcd"))

… will print 4.

Functions

Or we can use it as part of a larger expression.

print(len("abcd") + 10)

… will print 14.

Functions

There are several built-in functions that we can use any time in our programs, like print and len. We can also find functions in modules or define our own (both will be covered later).

Functions

Another example: round that takes a number and rounds it to the nearest integer:

ExpressionResult
round(1.234)1
round(9.876)10
round(9.876)/25.0

Functions

We can also give round an optional second argument: the number of digits after the decimal point.

ExpressionResult
round(9.876)10
round(9.876, 1)9.9
round(9.876, 2)9.88

Storing Information

We aren't going to be able to implement very many interesting algorithms if all we can do is calculate things and immediately print them. We'll add more tools to our programming toolbox as the course goes on.

It's often necessary to get/​calculate something and store that value so you can use it later. e.g. the smallest number in the guessing game.

Storing Information

Variables are used to store information in our programs. You can store any kind of information Python can work with in a variable. (e.g. we have seen numbers and strings so far.)

Variables have names that you can use to refer to them. For example, this statement creates a variable named count and stores the number 17 in it:

count = 10 + 7

Storing Information

count = 10 + 7

This an assignment statement: it stores the result of the right-side expression in the variable.

Setting a variables reserves some space in the computer's memory for this data, stores it, and connects that value to the variable name.

Storing Information

If we want to use the value stored in a variable, we can refer to it by name

count = 10 + 7
print("This is one more:")
print(count + 1)

The last line will print 18.

Storing Information

We can give each variable any name we want (letters and numbers and _, but not starting with a number).

The name should be meaningful: somehow indicate what the purpose of the value is. e.g. count might be the number of times something happened.

Storing Information

Another example:

course_number = 120
message = "Hello"
print(message, course_number)

This will print Hello 120. (Comma-separated things in a print are printed with spaces between them.)

Storing Information

Important note: the variables stores the result of the expression on the right side of the assignment, not the whole expression.

radius = 10
circ = 2 * 3.14 * radius
radius = 1000
print(circ)

That will print 62.8 (not 6280): when the circ = assignment was executed, radius was 10 and the calculation was done at that moment.

Storing Information

Also note: the variable name has no quotes around it. That's how we distinguish between the variable and the string that looks similar.

dept = "cmpt"
print(dept)
print("dept")
print(cmpt)

The output:

cmpt
dept
NameError: name 'cmpt' is not defined

Aside: Interactive Shell

I will occasionally give examples as they would appear in the Python (IDLE) interactive shell (or interactive prompt, or REPL, Read-Eval-Print-Loop). The previous example expressed that way:

>>> dept = "cmpt"
>>> dept
'cmpt'
>>> "dept"
'dept'
>>> cmpt
NameError: name 'cmpt' is not defined

Aside: Interactive Shell

In the interactive shell, you can type code one line at a time and see what happens. If the code prints something, it will be displayed. If you type an expression, you'll be shown its result.

>>> print("hello")
hello
>>> print(12 + 34)
46
>>> "hello"
'hello'
>>> 12 + 34
46

The first two here are statements that print something. The last two are expressions that have a result: be cautious about how similar they look.

Aside: Interactive Shell

Another aside: double quotes and single quotes around strings are equivalent in Python. I tend to use double quotes; the interactive shell tends to display single quotes.

>>> "test"
'test'
>>> 'test'
'test'

You can use whichever you like in your code.

Types

We have seen that numbers and strings are different in Python. e.g. you can subtract numbers (10 - 1 gives 9) but not strings ("10" - "1" causes a TypeError).

They are different types (or sometimes data types).

Types

There are actually two types of numbers: integers and floating point values (≈ real numbers). If you type a number with any decimal places, you're creating a floating point value. Here, the first "ten" is an integer; the next two are (the same) floating point; then a string.

>>> print(10)
10
>>> print(10.0)
10.0
>>> print(10.0000)
10.0
>>> print("10")
10

Types

We can ask Python what the type of a value is with the type function.

>>> type(10)
<class 'int'>
>>> type(10.0)
<class 'float'>
>>> ten = 10.0
>>> type(ten)
<class 'float'>

Types

Types come up when we are dividing: dividing two integers (with /) might get a non-integer result:

>>> 15 / 4
3.75

But sometimes, it's useful to have calculations stay within the integers (e.g. our guessing game: we need the guess to be an integer).

Types

Python has another division operator for that: // divides and rounds down to the next integer.

>>> 15 // 4
3
>>> -15 // 4
-4

You can think of // as divide and round down.

Type Conversion

We know that the string "10", the integer 10 and the floating point value 10.0 are different types and therefore different values in Python.

But it's also fairly obvious they are related.

Type Conversion

There are built-in functions that convert between them: int to convert to an integer, float to convert to a floating point value (≈ real number), and str to convert to a string.

These can be useful to construct a string to print.

Type Conversion

e.g. we want to output something like num=10. We might try this:

num = 10
print("num=", num)

That produces num= 10 because the comma always adds a space.

If we try "num=" + num we get a TypeError because we can't add a string and a number.

Type Conversion

But we can convert the number to a string and then concatenate that to another string.

num = 10
print("num=" + str(num))

Type Conversion

Joining multiple string pieces together with + to build the output we want is a fairly common pattern. That requires a type conversion if the value isn't already a string.

print("It was " + str(temp) + "°C according to " + name + ".")

User Input

So far, all of our programs have done the same thing every time we run them: there's no way for them to do anything but repeat the same calculation every time we run (other than changing the code).

Being able to ask the user something, i.e. get input from them, will give us a way to make things more interesting.

User Input

The input function will let us get input from the user.

When our code runs and gets to an input() function call, it will pause and wait for the user to enter a line of text. It will be returned as a string.

User Input

We can (optionally) give an argument to input that is the prompt for the user, like this:

name = input("What is your name? ")

After that line, name will be a string, so we could use it like this:

print("Hello, " + name + ".")

User Input

name = input("What is your name? ")
print("Hello, " + name + ".")

The output of the program will be like this (depending what is entered):

What is your name? Greg
Hello, Greg.

User Input

Or as a video, to see the timing:

User Input

Calling input will always return a string: just the characters the user types.

If we want a number, we have to convert it as appropriate. That will often be something like:

count = int(input("How many? ")
length = float(input("How long? ")

If the user enters something illegal for that type, the program will fail. We'll accept that. (for now?)

User Input

We can now write a program that feels like it does something useful:

width = float(input("Enter the width: "))
height = float(input("Enter the height: "))
area = width * height

print("A rectangle " + str(width) + " by " + str(height))
print("has area " + str(area) + ".")
Enter the width: 3.5
Enter the height: 14
A rectangle 3.5 by 14.0
has area 49.0.