2. Programming Basics

In this chapter you will learn how to solve simple problems by writing programs that take text and numbers as input.

2.1. User output

Any useful program must have some form of visible output. In Python print() is used for displaying output to the user:

# display a message on the console
print("Hello World!")

If you run this program the output will be:

Hello World!

Function print() will take the quoted text inside the round brackets (”…”) and put it in readable format to the console. Please note that text after a hash sign (#) is considered to be a comment and is ignored by Python.

Some parts of the program text appear to have different colors. The colors have no meaning in Python. They are only added by the code editor (e.g. IDLE) for readibility purposes. This is called ‘syntax highlighting’.

Some more useful print() examples:

# ',' combines strings
print("Loose", "words can", "be", "printed", "together.")

# You can combine text and numbers
print("Here is pi:", 3.1415, "....")

print("You can continue on the same line", end="")
print(" with 'end ='")

which produces the following output:

Loose words can be printed together.
Here is pi: 3.1415 ....
You can continue on the same line with 'end ='

The items to be printed - normally referred to as arguments - are placed between round brackets and separated by commas. Print is one example of a so-called function. Python has many built-in functions like this that we will encounter. More details on functions can be found in the corresponding chapter.

2.2. Comments

In the programs above we saw that the text on the right of the # does not have any effect on the output of the programs. It is only used to give some comment or explanation. We strongly recommend writing such comments in the code. It will help you to remember and explain why you wrote your program in a certain way.

Multi-line comments can be made using triple quotes ‘’’ in this way:

print(3) # this is a comment at the end of a print statement

'''This is an example
of a comment over
multiple lines'''

with output:

3

2.3. Variables

Consider the simple problem of computing the area of a square from its width. We know that the area can be computed by this formula: \(area = width \times width\). We need some way of telling the computer what the actual value of \(width\) is.

The way to make the computer store a piece of information - like a number - is by declaring a so-called variable. In this case we first declare variable width to store the original number. Then we declare variable area to store the result of the calculation before showing it to the user with print():

1# Assign a value to variable width
2width = 2.5 # width is now 2.5
3
4# Compute and store the result in variable area
5area = width * width # area is now 6.25
6
7# Display the result
8print("The area of a square of width", width, "is", area)

The output of this program will be:

The area of a square of width 2.5 is 6.25

The statement width = 2.5 on line 2 assigns the value 2.5 to a variable with name width. Consequently, this process is called assignment.

Please note that the meaning of ‘=’ in programming differs from mathematics. In programming it means an action (assigning a value to a variable), not a mathematical comparison.

Python is able to deduce that width is a (fractional) number and that it can do calculations with it. Therefore, no specification of the so-called data type is required like in most other programming languages.

Let’s have a look at another important data type: string. Suppose you want a program that combines the first and last names of a person:

# Assign a text to first_name
first_name = "Lionel"

# Assign a text to last_name
last_name = "Messi"

# Combine the names by concatenation ( + ) and put a space between them
full_name = first_name + " " + last_name

# Display the result
print("My full name is", full_name)

The output of this program will be:

My full name is Lionel Messi

We will learn more about numbers and strings in the next chapter.

2.4. Expressions and Operators

Let’s take a closer look at assignments like these:

full_name = first_name + " " + last_name

area = width * width

On the right side of the = we have so-called expression: stored values (variables first_name, last_name and width) combined with calculations (* and +). Expressions are the way programs calculate numbers and manipulate texts. Symbols like =, + and * are called operator because they all ‘do’ something.

Expressions can also include so-called functions as in this example:

>>> length = len('Lionel') # calculate the length of the word 'Lionel'
>>> print(length)
6

More on functions in chapter 6 of this reader.

2.5. Identifiers

The names we gave to the variables ‘width’ and ‘area’ are called identifiers. The programmer can choose any name within the following rules:

  • Identifiers are a sequence of letters, digits, and underscores ( _ )

  • Identifiers can be of any length

  • Identifiers are case sensitive: variable1 and Variable1 are different identifiers

  • Identifiers can not be a keyword (e.g. import, see below)

  • Identifiers can not start with a number (2ndName is not a valid identifier)

  • Identifiers can not contain special characters like @, % or *

Some examples of valid identifiers:

  • n, count, numberOfStudents, perform_some_calculation, PublicEnemyNr1

Meaningful names

Although you can give your variables any valid name you like, it is good programming practice to use meaningful identifiers. As an example, compare this valid fragment of Python code:

xXx_xXx = 7.5
A123456 = 8.0
_oO0Oo_ = 9.0

print((xXx_xXx+A123456+_oO0Oo_)/3)

with this fragment:

mark_1  = 7.5
mark_2  = 8.0
mark_3  = 9.0
final_mark = (mark_1 + mark_2 + mark_3) / 3
print(final_mark)

You can try out both to convince yourself that they will both produce the same output (8.166666666666666), but the purpose of both fragments (to calculate an average mark) is much easier to understand in the second fragment than in the first.

Keywords

In every computer language there are certain words that cannot be used as an identifier for variables, constants, functions and such because they are reserved for specific purposes. Do not use any of these keywords as an identifier if you don’t want to run into errors when you execute your Python program:

and

break

continue

del

else

exec

for

global

import

is

not

pass

raise

try

with

assert

class

def

elif

except

finally

from

if

in

lambda

or

print

return

while

yield

We will encounter most of these keywords in this reader and learn about their use.

2.6. User input

If you would like to re-run the program with the area calculation with different numbers, it would be cumbersome to change the code every time. The ‘input()’ function can be used to wait and prompt the user for a new number or text:

variable = input("Enter a value: ")

This eliminates the need of changing the program everytime you need a new value. Here is the name fragment re-written to allow the user to enter their own name:

 1# Assign a text to first_name
 2first_name = input("What is your first name? ")
 3
 4# Assign a text to last_name
 5last_name = input("What is your last name? ")
 6
 7# Combine the names by concatenation ( + )
 8full_name = first_name + " " + last_name
 9
10# Display the result
11print("Your full name is", full_name)

The output of this program will fist be:

What is your first name?

Execution stops at line 2 until the user enters a text followed by ‘enter’. Let’s supose the user has entered ‘Peter’. Next, the program will prompt for another input at line 5:

What is your first name? Peter
What is your last name?

After the user has entered another text, e.g. ‘Parker’, and pressed enter, the remaining lines 6 - 11 are executed to give this complete output:

What is your first name? Peter
What is your last name? Parker

Your full name is Peter Parker

Numbers as input

Python will interpret any value entered in response to input() as a string (text). You need to tell it to interpret the user input as a number. Function float(…) converts anything between the brackets to a fractional number (a so-called float). A program that calculates the area of a square with different user input values becomes:

 1# Let the user input a value for the width
 2value = input("Please enter the width of the square: ")
 3
 4# convert the value entered into a numeric value
 5width = float(value) # width is now the number that the user has entered
 6
 7# Compute the area
 8area = width * width
 9
10# Display the result
11print("The area of a square of width", width, "is", area)

The output of this program will first be:

Please enter the width of the square:

Execution stops at line 5 until the user enters a number followed by ‘enter’. Let’s suppose the user enters 4.5, then the output of line 11 will be:

The area of a square of width 4.5 is 20.25

The subject of type conversions will be discussed in more detail in section 3.5.

2.7. Errors

Programmers - like all human beings - make mistakes. It has been estimated that professional software engineers / programmers spend about 50% of their time on testing and perfecting their programs. Consequently, being able to identify and correct errors in your program is a useful skill.

In this section we will examine three fundamental kinds of errors: syntax errors and run-time errors - that can be detected by the system - and logical errors (a.k. bugs).

Example

As an illustrative example let us look at a variation of the area calculation above: a program that calculates the perimeter of a square, given its width. Below is one (correct) implementation of this task:

 1# Let the user input a value for the width
 2value = input("Please enter the width of the square: ")
 3
 4# convert the value entered into a numeric value
 5width = float(value) # width is now the number that the user has entered
 6
 7# Compute the perimeter
 8perimeter = 4 * width
 9
10# Display the result
11print("The perimeter of a square of width", width, "is", perimeter)

The output of a sample run with user input 2.5 will be:

Please enter the width of the square: 2.5
The perimeter of a square of width 2.5 is 10.0

We will now deliberately introduce a number of typical errors to see what their effect is on the operation of the system.

Syntax errors

Often simple misspellings a.k.a. ‘typos’ result in the Python interpreter not being able to even understand the intended actions in the program. These errors are commonly called ‘syntax errors’. Let us introduce such a typo in line 8 by spelling ‘with’ (a Python keyword) instead of ‘width’:

 1# Let the user input a value for the width
 2value = input("Please enter the width of the square: ")
 3
 4# convert the value entered into a numeric value
 5width = float(value) # width is now the number that the user has entered
 6
 7# Compute the perimeter
 8perimeter = 4 * with
 9
10# Display the result
11print("The perimeter of a square of width", width, "is", perimeter)

The above program will not even start in IDLE. The word ‘with’ is a keyword and the program will not know what to.

Run-time errors

If we replace the erroneous ‘with’ in the example above with another wrong name ‘widdth’, the program will start, but report an error when it comes to the line with the mistake.

 1# Let the user input a value for the width
 2value = input("Please enter the width of the square: ")
 3
 4# convert the value entered into a numeric value
 5width = float(value) # width is now the number that the user has entered
 6
 7# Compute the perimeter
 8perimeter = 4 * widdth
 9
10# Display the result
11print("The perimeter of a square of width", width, "is", perimeter)

The resulting output (for a sample input of 2.5) will be:

Please enter the width of the square: 2.5
Traceback (most recent call last):
  File "/Users/peterlambooij/Downloads/Untitled.py", line 8, in <module>
    perimeter = 4 * widdth
NameError: name 'widdth' is not defined

The program stops execution and will show the location of the error (i.e. file and line-number) and a message why it cannot continue. The programmer is adviced to at least look at the reported line and try to understand what needs to be fixed.

Logical errors (bugs)

The majority of the errors go undetected by the program. It will happily produce results and continue execution, although the user/programmer may find them unexpected. These errors are commonly called bugs. Here is an example in which the programmer omits to instruct the program to convert the user input from a string to a float number:

1# Let the user input a value for the width
2width = input("Please enter the width of the square: ")
3
4# Compute the perimeter
5perimeter = 4 * width
6
7# Display the result
8print("The perimeter of a square of width", width, "is", perimeter)

A sample run in IDLE with 2.5 as input will look like this:

Please enter the width of the square: 2.5
The perimeter of a square of width 2.5 is 2.52.52.52.5

Although the program does not stop execution, this is probably not what the programmer intended. This type of error, a so-called bug, is usually detected by testing the program or - if you are an experienced programmer - by a code review. For the interested reader: section 3.1 explains the output of in this particular case (string multiplication).

© Copyright 2022, dr. P. Lambooij

last updated: Sep 02, 2022