Termbank
  1. A
    1. Absolute Path
    2. Ajonaikainen
      concepts
    3. Alustaminen
      variables values
    4. Argumentti
      values functions
    5. Arvo
      values
    6. Assignment
      variables values
    7. Assignment Operator
      variables values operators
    8. Attribute
      objects
    9. Attribuutti
      Attribute
    10. Avainsana
      names
    11. Aliohjelma
      Function
  2. B
    1. Boolean
      control flow
    2. Boolean Operator
      control flow operators
    3. Boolen operaattori
      Boolean Operator
    4. Branch
      try structures conditional structures
    5. Bug
      problem solving
    6. Bugi
      Bug
    7. Builtin Function
      functions
    8. Block
      Code Block
    9. break
      loops keywords
  3. C
    1. Callback
      functions
    2. Carriage Return
      escaping strings files windows
    3. Code Block
      control flow functions
    4. Code File
      concepts
    5. Command Line Argument
      terminal
    6. Comparison Operator
      control flow operators
    7. Comparison Value
    8. Condition
      control flow
    9. Conditional Statement
      control flow
    10. Conditional Structure
      conditional structures control flow
    11. Constant
      variables values
    12. Control Structure
      try structures loops conditional structures
    13. Call
      Function Call
    14. Ctrl + C
      Näppäimistökeskeytys
    15. Code
      Source Code
    16. Callback
      Takaisinkutsu
    17. Command Prompt
      Terminal
    18. continue
      loops keywords
  4. D
    1. Data
    2. Data Format
      strings files
    3. Data Structure
      dictionaries concepts lists
    4. Debugging
    5. Default Value
      values functions parameters
    6. Dictionary
      data structures
    7. Docstring
      documentation
  5. E
    1. Epätosi
      values
    2. Error Message
      problem solving
    3. Escape
      strings
    4. Evaluointi
      expressions values
    5. Event
      concepts
    6. Exception
      try structures problem solving
    7. Exception class
      exceptions control flow
    8. Execution
      expressions concepts
    9. Element
      Item
    10. enumerate
      lists loops
  6. F
    1. False
      Epätosi
    2. File Extension
      files
    3. File Handle
      objects files
    4. Filename
      strings files
    5. Float
      values types
    6. Format
      strings printing
    7. Formatting
      Format
    8. Function
      functions
    9. Function Call
      functions statements
    10. Function Definition
    11. f string
      strings
    12. for
  7. G
    1. Generator
      objects loops
    2. Globaali muuttuja
      variables values
    3. Global Scope
  8. H
    1. Handle
      File Handle
    2. Handler
      functions concepts
    3. Hyppy
      control flow
    4. Hardkoodaus
      Kovakoodaus
  9. I
    1. if statement
      Conditional Statement
    2. if structure
      Conditional Structure
    3. Identifier
      variables functions
    4. Indentation
      concepts
    5. Index
      values lists
    6. Index Subscription
      values lists
    7. Infinite Loop
      loops
    8. Input
      strings concepts
    9. Interface
      modules functions concepts
    10. Item
      values lists
    11. Iteration
      loops
    12. import
      modules
  10. K
    1. Key
      dictionaries values
    2. Keyword Argument
      functions
    3. Kirjasto
      modules
    4. Kommentti
      debugging documentation
    5. Kovakoodaus
      values
    6. Käyttöliittymäelementti
    7. KeyboardInterrupt
      Näppäimistökeskeytys
  11. L
    1. Lause
      concepts
    2. Lauseke
      concepts
    3. List
    4. Literal
      values
    5. Local Variable
    6. Loop
      control flow
    7. Loop Variable
      variables loops
  12. M
    1. Main Program
      concepts
    2. Merkki
    3. Merkkijono
      values types
    4. Method
      functions objects
    5. Member Function
      Method
    6. Method Call
      expressions objects
    7. Module
    8. Mutable
      values concepts lists
    9. Muuntumaton
      values strings concepts
    10. Määrittely
      concepts
  13. N
    1. Name Conflict
    2. Namespace
      modules functions concepts
    3. Newline
      strings files
    4. Nimeämätön vakio
      values constants
    5. Näppäimistökeskeytys
      exceptions
  14. O
    1. Objekti
      concepts
    2. Olio
      Objekti
    3. Ohjelmointityyli
    4. Ominaisuus
      objects
    5. Opening Mode
      files
    6. Operand
    7. Operation
      expressions
    8. Operator
    9. Optional Argument
      values functions parameters
  15. P
    1. Parameter
      functions
    2. Parametrization
    3. Path
    4. Placeholder
      strings printing
    5. Poikkeusten käsittely
      control flow exceptions
    6. Precedence
      expressions concepts
    7. Presedenssi
      Precedence
    8. Precedence
    9. Printing
      strings concepts
    10. Programming Problem
      problem solving
    11. Python Console
      tools
    12. Python Interpreter
      tools
  16. R
    1. Running
      Execution
    2. Recursion
      functions concepts
    3. Referring
      variables values objects
    4. Relative Path
    5. Return
      values functions
    6. Return Value
  17. S
    1. Silmukka
      Loop
    2. Suoritusjärjestys
      Precedence
    3. Sapluuna
      strings concepts
    4. Scope
      concepts blocks
    5. Separator
      strings files lists input
    6. Sequence
      data structures concepts loops
    7. Slicing
      lists
    8. Solution Model
      problem solving
    9. Source Code
      concepts
    10. State
      concepts
    11. Stub
      problem solving functions
    12. Syntax
      concepts
    13. Syntax Error
      exceptions
    14. Shell
      Terminal
    15. Stacktrace
      Traceback
  18. T
    1. Taikaluku
      Nimeämätön vakio
    2. try-rakenne
      Poikkeusten käsittely
    3. Takaisinkutsu
      functions
    4. Terminal
      tools
    5. Testaaminen
      problem solving concepts
    6. Text File
      files
    7. Tosi
      values
    8. True
      Tosi
    9. Traceback
      problem solving
    10. Tuple
      data structures lists
    11. Type Conversion
      values functions types
    12. Tyylisääntö
    13. Tyyppi
      values concepts
  19. U
    1. User Interface
      concepts
  20. V
    1. Variable
      values concepts
  21. W
    1. while
      loops
    2. with
      files
Completed: / exercises

1. Material: The Mysteries of Cosmic Variables

What's Going on?

As the name Elementary Programming suggests this course teaches you how to program without any kind of pre-requirements. It is going to be a rocky road but we hope that the great accomplishments at the end of it will make up for all the trouble. The pre-exercises and instructions exist to give you everything you need before diving into this learning material. From there you will learn to install and run the correct applications and to write some basic math into the
Python console
. You may even learn what this mysterious console is. Heck, you'll even catch a glimpse of what
code files
are.
There's a lot of variables when it comes to learning programming but none of them are insurmountable. Learning is generally enhanced with some sense of purpose. This is a good moment to think about what You would use programming for. There are use cases for programming skills in almost every field and even in many hobbies. Programming skills can open up surprising opportunities in many aspects of life. However, nothing is quite as effective as motivation from personal aspirations. What could You program?
Within the framework of this course we can only offer you one goal: everything you learn in the course eventually leads up to the final project. If you cannot come up with a more personal purpose for programming, at least keep the final project topic of your choice in mind when going through these materials. One morning you might wake up with a mystic enlightenment about how a minesweeper game works under the hood; or how RLC circuits can be solved programmatically; or how measurements can fit into a nice plot. In that moment it's good to reflect upon where you started and how far you've come. We recommend that you take a look at the topics right now, here at the start.

Alright Sensei. Will You Now Tell Me What Programming Is?

Image source 1
Programming is not all about writing
code
. Code is simply the most apparent manifestation of programming. A lot of programming activities can be done in secret within your mind. Only when you start to write code the uninitiated around will realize what you're up to - but it will be too late! Your plan to take over the world is already underway.
What else is there besides code then? In more general terms we can say that a programmer solves
problems
. In our context a problem is any need that can be fulfilled by programming - be it the need for your own minesweeper game, or the need to post memes online for others to like and share. While neither of these would qualify as actual Problems, once some need is selected to be fulfilled with programming it effectively becomes a programming problem.
The solution to a programming problem is generally a plan of what the code itself should do. At this stage the
solution model
may only exist only within the programmer's mind - or perhaps on paper. Creating solution models to problems is the first invisible programming skill.
Knowing the possibilities of code is essential in producing a solution. However, at this stage it's too early to fuss over small details like how the code will actually be written. It is mandatory to understand programming concepts though: how program execution is controlled and how programs process information. When learning these concepts it's good to remember that they are largely not unique to Python. Common programming concepts exist in all programming languages in one way or another. Conceptualizing a
solution model
is the second invisible programming skill.
Only after going through this process of solving a problem and then conceptualizing the solution we can finally fuss about the minor detail that is writing the code itself. We say "minor" because the code itself is just
syntax
that the programmer uses to describe their solution to the computer in an unambiguous manner. Compared to everything else it's more like a formality really. If you only know how to write code you won't get very far in programming.

In the Beginning There Was a Variable

Learning goals: After this section you'll know what variables are. You'll know how to use variables to make the computer remember things. You will also have have a basic understanding of how variables are connected to the computer's memory. Assignment operator will be familiar. Last but not least you are also familiar with rules and conventions regarding variable names.

Introduction to the World of Variables

Our very first programming concept will be memory. As soon as we're dealing with anything beyond individual statements remembering things becomes a necessity. In programming this concept of memory is implemented through
variables
that reside in the computer's memory. In Python variables are created when they are assigned a value. This is done with the assignment operator = with the variable on the left and the value on the right.
x = 1337
A major difference exists between computer and human memory: the computer does not know the meaning of things it remembers while humans (usually) do. The value 1337 is just a number that resides somewhere in memory. The computer cannot respond directly to a request such as "give me the previously calculated value of x". However it does know what each memory address contains and it can answer if asked for a value from a specified location. Luckily programmers don't need to know these memory addresses - that is what variables are for. In this example, the variable is x.

Digesting Variables

The concept of
variable
can be explained in many ways. At its core it's an agreement between the programmer and the
Python interpreter
that a certain word (e.g. x) is used to
refer
to a specific location in the computer's memory. As a result of this agreement both parties can talk about data in their own terms: the programmer can refer to things with descriptive names while the computer can handle memory addresses. This can be simplified to saying that after executing x = 1337, x means 1337 - even though this is not completely accurate.
While we often use phrasing such as "variable contains" the variables themselves don't really contain anything. It's just a shorthand for indicating that the
variable
refers
to a certain
value
in the computer's memory. Variables are like headings in a book index or labels on a map. Neither contains what they refer to; they simply show where it is. The map is not aware what "Oulu" means to whoever is looking for it - it simply knows that such a name has been given to a certain geographical region.
So if x = 1337 means that we define a name x that refers to memory slot that now contains the value 1337, what do the following two lines mean?
y = x
x = 4451
The first line defines another name for the value x
refers
to. As a result both x and y now refer to the same
value
, i.e. 1337. This is not renaming since both x and y will exist; neither is it copying because only one value 1337 exists in memory. The second line creates a new value 4451 that will be assigned to another memory address. Immediately after we redefine x to refer to this new memory location and the value it contains. As a result we now have both x and y but their values are now respectively 4451 and 1337. The animation below illustrates the relationship between names and values.
One important thing to note about
assignment
is that despite having the same symbol (=) as mathematical equivalence it's not the same operation. In particular the order of operands is meaningful. The variable must always be on the left and the value on the right. If you try to swap them...
1337 = x
you will get:
SyntaxError: can't assign to literal
This means there is
syntax error
because it's impossible to assign anything to a
literal value
. You also can't have an operator on the left side:
x + 3 = 5
because this will also cause an explosion:
SyntaxError: can't assign to operator
This time the messages is a bit more confusing. It's just a way of saying that we can't assign to the x + 3
operation
. We'll dive a bit more into interpreting error messages at later sections in this material.
To summarize: it's only possible to have a
variable
on the left side of the = operator. Everything else should happen on the right side. Later we'll see a couple of other things that can be on the left side though. Since being on the left side of the operator means the variable is being assigned to we can infer that when it's present elsewhere we want to retrieve its value instead. Therefore when the following statement is processed we can imagine the [!term=Value!] of each variable in place of its name. When the statement is carried out, the value of each variable is retrieved from memory before proceeding with other instructions (i.e. the + operator). Likewise the right side of the assignment operator is executed in its entirety before anything is assigned to the variable on the left.
x = y + 4451
The last we saw of y it was referring to the value 1337. As we retrieve it and add 4451 the new value of x ends up as 5788 because the addition is carried out before the new value is assigned to x. To be more precise the new value 5788 is stored in a new memory location, and x is changed to refer to that location. The old value of x will be left by its lonesome in its memory slot until it gets replaced by something.
As we're going through
assignment
and other
operations
we can also instate our first style guideline: there should always be a single space between each
operator
and its
operand(s)
- otherwise the code would look kinda crammed. This is also in accordance with Python's official style guide. What a coincidence. So, just like in the examples, one space before and after each operator. And yes, we will check - or rather the automated evaluation of tasks does.

Line Has Points

Learning goals:
Assignment
of intermediate results to
variables
.
Introduction:
Let's start from a situation where we have one point from a line that goes through the origin. The x and y coordinates of this point are assigned to variables in the
Python console
as follows:
In [1]: x = 4
In [2]: y = 2
Your task is to calculate the line's slope using these coordinates, and then calculate the values y1 (when x = 7) and y2 (when x = 159) using the slope value.

Answer Specification:
The task will ask you for the answer in five phases. Each phase is answered by one line of code. You should also follow along in your Python console to be bale to see what happens. The things that will be asked are
  • create variable x with value of 4
  • create variable y with value of 2
  • calculate the value of variable k using the variables x and y (division)
  • calculate the value of variable y1 using k and the
    number
    7 (multiplication)
  • calculate the value of variable y2 using k and the number 159 (multiplication)

Warning: You have not logged in. You cannot answer.
It's also possible to "update" the value of a
variable
. For instance if we have a variable that contains the score of a sportsball team and they score another point, we could have a line like this to handle the situation:
score = score + 1
This line retrieves the value of score then adds one to it and finally saves the result and updates score to refer to the new value. There's also a shorthand
syntax
for writing the same
statement
and it looks like this:
score += 1
The same can be done with other
operators
as well.

Variable Naming

There are rules to naming
variables
that are absolute in Python. Only letters, numbers and underscore are allowed in variable names. Names also cannot start with numbers. Furthermore, names that start with an underscore have a specific implied meaning that is beyond the scope of this course - therefore starting names with underscore should be avoided. Within these rules you are allowed to name your variables as you wish. Please avoid funny meme names though. The following example shows some valid and well chosen names:
matches = 5
player1 = "Goofy"
player_score = 41.8
Variables are agreements between the programmer and the computer about the meaning of each name in the code. Since the computer doesn't particularly care about the names, you as the programmer have the freedom to choose names in a way that makes your job easier. The number 1337 doesn't hold any specific meaning to the computer but it does to you. Best practice is to name variables accordingly so that future you also knows what they mean. For instance x is not a descriptive name for your commute distance. Besides it's not just for future you - there will be other people reading your code as well. Within the context of the course it's much faster for TAs to help you if they don't need to spend extra time figuring out what each variable name means. Naming
variables
is also a good measure for whether you've understood the code you've written. If you can't name the result of a
statement
what are the chances you understand what it does in the first place?
Image source 2
On this course we also follow the the official naming guidelines for Python. In short: names are written with lowercase letters only and multiple words in a name are separated with underscores. Like so: donkey_height = 100. We make an exception for SI units: if you use them it's better to use the proper symbol even if it would be an uppercase letter. However, this only applies to symbols that exist in the English alphabet - Greek letters and such should be avoided.

Reddit in Motion

Some internet warrior who didn't read this material properly has decided to go full meme with their variable names. Humanity needs you to figure out more descriptive names for variables in the code line below.
Learning goals: Naming
variables
.

Introduction:
Below is a code line written by an Internet meme hero. Since it might be hard to figure out what this code line is supposed to do, we can tell you that it is the formula for kinetic energy.
kappa = 1 / 2 * doge * peepo ** 2

Answer Specification:
Retype this code line to the answer box below using proper names for the variables. You can either use names of the physical quantities or their SI symbols. Just don't mix them.
Write the equation using proper variable names:
Warning: You have not logged in. You cannot answer.

Ever-Expanding Math

With what we got so far we can write some simple code that solves simple equations and does other kinds of math. The functionality of a basic calculator is at least something but by itself not particularly impressive. It's time to expand our horizons.
Image source 3
Learning goals: After this section you'll know mathematical basic operators. Typing lines of code expands to lines that do more than one thing. You will also become more familiar with the math-like execution order of code. The concepts of integers and floating point numbers - and some complications related to them - are also on the menu.

Operation Square Root

Operator
is a symbol that indicates an
operation
(e.g. mathematical operations like addition with the +-symbol). Operations use
operands
that are placed on both sides of the operator.
An illusration with the code line "product = multiplier * multiplicant". The names "multiplier" and "multiplicant" are denoted as "operand". The * character is denoted as "operator"
Operation and its components.
Most common operators in programming are mathematical operators that are introduced in this material and logical operators that are in the next material. Python knows the basic operators with their familiar symbols: +, -, * and / (addition, subtraction, multiplication and division respectively). We're now mostly missing power and root. Both of these can be actually done with the same operator: **. This makes sense because root is the same as power with fractions.
cube_volume = side_length ** 3
side_length = cube_volume ** (1 / 3)
There are also a couple more
operators
related to division that are occasionally needed. First we have // which indicates integer division. Second, % operator gives the remainder. Let's explore these with a short task and get back to them when they become more relevant (in the third material).

No Quarter Given

Division is the most complex basic mathematical operation because its result is divided into two parts: quotient and remainder. Both are relevant in programming so it's good to know what kinds of division operators are found in Python.
Learning goals: Know what division
operators
exist in Python.

Introduction:
Do the following calculations in
Python console
:
In [1]: 19 / 4
In [2]: 19 // 4
In [3]: 19 % 4

Answer Specification:
Type the result of each
operation
to the answer box.
Type the results into the box below, one per line, in the corresponding order.
Warning: You have not logged in. You cannot answer.
Just like math, Python also has execution order or
precedence
for
operators
. For mathematical operators, precedence is familiar: multiplication and division take place before addition and subtraction; equal precedence from left to right. Execution order can be altered with parentheses so that anything inside parentheses takes precedence. Precedence and operators can be further investigated from Python's documentation. Reading documentation in general is an essential programming skill.

Two Kinds of Numbers

Numbers in math are divided into various categories like integers and decimal numbers. These categories are also important in programming. In Python decimal numbers are identified by the existence of the decimal point. Therefore 5 is always and integer but 5.0 is a decimal number. Decimal commas are not to be used in Python because commas have a very different meaning.
However since computers deal in ones and zeros they are in fact not very good with real decimal numbers. In computing terminology a separate term is used instead of "decimal number" to indicate the difference:
floating point number
or float.
87.41871478 # This is a float
A floating point number is an approximation of a decimal number, i.e. it is not exactly accurate. In most scenarios the inaccuracy manifests after so many decimals that it generally does not matter in practice because results are usually rounded eventually anyway. For instance let's look at cubic root of 64, i.e. 64 ** (1 / 3). The cubic root should be exactly 4. However if we actually execute the statement in Python, we get 3.9999999999999996. You can find an in-depth description of floating point issues from Python's tutorial. The inaccuracy is not very relevant here because the result is still 4 after rounding. Likewise we would need to make quite a large number of calculations before this inaccuracy produces an error.
There is, however, a very fast way to produce an error from this inaccuracy. Occasionally it's necessary to
convert
numbers from one type to another. Usually from float to integer because there are certain use cases that only accept integers.
To illustrate the problem, let's consider screen coordinates. A computer screen consists of picture elements or pixels each of which are produced by physical components. This makes it a discrete coordinate system. Your mouse cursor will always point at a pixel - never between them. What follows is that the position of graphical objects on the screen cannot be expressed as decimal numbers. When a program needs to draw on the screen, it has to convert the object's position to an integer.
This conversion is done with two
functions
in Python: int and float. Named as abbreviations of integer and floating point number respectively. Without going into details about what functions are just yet, let's just see what happens when we use them:
In [1]: float(4)
Out[1]: 4.0
In [2]: int(4.0)
Out[2]: 4
This looks simple enough. But?

Breach of Integrity

Converting numbers to integers and rounding them are not quite the same thing, as can be seen from this exercise...
Learning goals: See how the int
function
handles decimal parts.

Introduction:
In this short exercise all you need to do is to convert the previously seen number 3.9999999999999996 to an integer. Try to do this in the
Python console
using the int function.

Answer Specification:
Copy the result of the
function call
to the answer box.
Type the result returned by the int function below.
Warning: You have not logged in. You cannot answer.
One vital fact about the int function: it only returns the integer part of a number - there is no rounding. You can achieve the same result by applying integer division with one: 3.9999999999999996 // 1. If we recklessly convert a float result from a calculation to an integer, this can result in a significant error. The result should be rounded first, and for this we need some new tools.

Functions - Threat or Opportunity?

Our next contestants are... functions. The term may be familiar from math, most commonly as f(x). This notation defines a statement and its result is said to be the function of x - in other words the result value depends on the value of x. While not exactly identical, it's a good starting point for delving into functions in programming context.
Learning goals: After this section you are familiar with the concept of functions: what they are, why they exist, where they are and how to use them. You will also learn how functions are separate parts of a program that can communicate with the rest of it. Finally you'll come to know a few basic functions.

The Essence of Functions

Functions
are recycling at its best. If a snippet code that does one particular thing exists there's little point in re-inventing the wheel. Functions can be found
built into Python
, from various
modules
and
libraries
. You can also write your own functions which is a very good habit to pick up. So good in fact that it's best to start working on it from the get-go. You don't need to understand the code below just yet - it's there just to show you what can be expected in the near future when we start to work on our very own functions.
def calculate_mean(values):
     return sum(values) / len(values)

mean = calculate_mean((6, 8, 10, 7, 9, 8, 5, 7))
An ideal
function
is an isolated, fully independent unit. In other words the function's internal workings are not dependent on any code outside of it. Functions written in such a way can be used in any context and always work as expected. Likewise a programmer doesn't need any understanding of a function's internal logic in order to use it - they only need to know how to use it. A function's documentation is responsible for describing anything you need to know about using it. Naturally Python's
built-in functions
fulfil all these conditions. They include the previously seen int and float functions.
Although we say that an ideal function is isolated it doesn't mean that it shouldn't have any means to communicate with the rest of the program. Understanding the nature of this communication is essential in learning to utilize functions. For the rest of the world, a function is a black box. Something just goes in and something comes out. These two things, input and output, form the
interface
that other parts of the program use to communicate with the function.
A central term related to functions is
calling
. Just like a phone call, there are two endpoints in this process: the caller and the callée. The callée is the function; the caller is the part of the program where the function is called.
Image source 4
A
function
is called through its interface. This interface dictates the rules about what kinds of things the function can handle, the order in which they must be presented and what can be expected as the result. From the function's perspective it's vital that the caller adheres to the restrictions placed by the interface.
Let's look at the int function in order to make some actual sense of this. What we know of it so far is that it receives a number and returns the integer part of said number. Let's assume we are calculating the transition of a moving object along the x axis of a coordinate system. This is done by multiplying the object's directional unit vector's x component (e.g. 0.32) by the object's speed (e.g. 10).
speed = 10
direction_x = 0.32
transition_x = int(direction_x * speed)
Understanding the subject matter of this example is not essential. It's just a scenario where converting a number to an integer is actually needed. It's also a rather common scenario in game programming. The crux of this example is the third line where we can see a
function
called
. The part of code that's inside the parentheses defines what is sent to the function for processing. It's probably also noteworthy that due to precedence the operation inside the parentheses is executed first. Therefore the function is ultimately sent the result of the multiplication (i.e. 3.2). Once the function has done its thing and the dust settles, all that's left is the integer value 3 that will then be
assigned
to the transition_x variable. The animation below illustrates what's going on.

Squareception

An important aspect of programming is to be familiar with its terminology. In this exercise you need to be familiar with argument and return value.
Learning goals: Think about the roles of
arguments
and
return values
in a
function call
.

Introduction:
You can write the following lines to the
Python console
or otherwise think about them:
In [1]: small_side = 8
In [2]: big_side = 3493
In [3]: squares_per_side = int(big_side / small_side)
The code lines are related to calculating how many smaller squares fit inside a bigger square.

Answer Specification:
The answer has to consist of two numbers, each on their on line. The first number should be the value that is passed to the int function, i.e. its argument. The second line should contain what the function
returns
.
Type both numbers below, on separate lines.
Warning: You have not logged in. You cannot answer.

A World of Possibilities

We ended up looking at functions in the first place because we wanted convert the result of 64 ** (1 / 3) to an integer correctly. Using just int(64 ** (1 / 3)) gave us 3 and left us very bamboozled. We found out the reason but are still lacking a solution.
As we can witness from its documentation, Python comes with numerous
functions
. At the earlier stages of the course we're mostly playing around with functions found there, and quite frankly we won't touch majority of them either. Function names are usually quite well chose. For our problem - which was the lack of proper rounding - we will probably find a function called "round" useful. Just to be sure that it actually does what we want of it, let's learn how to read documentation.
Sceenshot of round function
Documentation of the round function.
The very first line which contains the
function
name is crucial. This one line specifies how the function is to be
called
. The words inside the parentheses, number and ndigits, are names for
values
the function accepts. The names typically have been chosen to somehow reflect the nature of the value that the function can use. In this case the first value called number is the number that is to be rounded; the second called ndigits (number of digits) defines the desired precision of the result.
These names, number and ndigits, belong the to a special category of
variables
that is called
parameter
. On the other side of the equation where we call the function and give it a number to round and another number as the desired precision (e.g. 3.56 and 1) these values will be called
arguments
.
In [1]: round(3.56, 1)
So far so confusing, but what about the square braces around the ndigits parameter? First of all this has nothing to do with the
syntax
of defining functions. If you would look at how the round function is defined you would see something like this: def round(number, ndigits=0):. The square braces are simple documentation markup that indicates ndigits being optional. In other words the function can be called without giving a value for this parameter. The text part of the document even says what happens if it's not given: ndigits will have the value 0. Therefore these two behave identically:
In [1]: round(4.451, 0)
Out[1]: 4.0
In [2]: round(4.451)
Out[2]: 4.0
Because the , 0 part of the first line is superfluous, the best practice is to leave it out entirely. This is almost always done in situations where we want to use the
default value
of a parameter.
Optional arguments
are only given when we want them to have a value that differs from the corresponding default:
In [1]: round(4.451, 2)
Out[2]: 4.45
When
functions
are given multiple
arguments
they are separated from each with commas. There is also another style guideline related to this: similarly to writing text, each comma should be followed by exactly one space. Arguments are assigned to
parameters
in order. In the example above the number parameter gets its value from the
literal value
argument 4.451 while ndigits gets the value of 2. Parameter and argument are not the same, they just share a value. An argument can be a literal value or a
variables
but a parameter is always a variable.

Round Zero

Writing function calls is one one of the most common things in programming. It's good to practice them. Repeatedly.
Learning goals: Writing a
function call
with multiple
arguments
.

Answer Specification:
What kind of a code line you would write to use the round
function
to round 0.123456 to four decimal precision?
Write your function call below.
Warning: You have not logged in. You cannot answer.

Functions in Use

Now we can finally write a code snippet that converts the result of 64 ** (1 / 3) to an integer correctly:
result = round(64 ** (1 / 3))
result = int(result)
This can also be achieved with a single line of code
result = int(round(64 ** (1 / 3)))
Precedence
follows familiar rules: the inner
function call
is executed first. As there is kind of a lot going on on this line, the animation below illustrates what happens step by step.
It's ultimately up to you to decide when to include multiple operations on one line and when to split them by saving intermediate results to
variables
. Readability is king in majority of programming. This means too long or complex lines should be avoided. However, on the flip side, code that constantly defines lots of variables for intermediate results also makes it harder to figure out the essential parts.
We now know what
functions
are, where to find them and how to use them in code. Our next stretch is to look more into how functions are used and look at some functions that will be commonly used throughout the course.
Our first point of interest is showing results while running
code files
. While working in the
Python console
the results of various
statements
were shown immediately unless they were
assigned
to
variables
. The console executes the entire statement and finally shows the result. However, when code files are ran the results of statements are not shown automatically. Instead the results are practically thrown into the bin if they are not assigned to variables. Therefore a code line such as
4451 + 1337
does practically nothing. It does produce a result (5788) but the result is not used for anything and is therefore instantly discarded. Since running programs without seeing their results does not sound particularly fruitful, we should probably have a way to show relevant results. This can be done with the print function. Lo and behold, a simple example:
result = int(round(64 ** (1 / 3)))
print(result)
the same without intermediate variable assignment:
print(int(round(64 ** (1 / 3))))
In a nut shell, print is a
function
that prints its
argument
, followed by a newline character. If there are multiple print function calls in a program, each of those will be shown on their own line in the program output.

Printing Service

When working in the Python console, results are automatically shown. With code files this is not the case - nothing is shown in the output. In this exercise we're going to learn how to make selected results visible in the output when running code files.
Learning goals: Printing to the terminal when running a
code file
.
Goal: Make the given program print its results.
Before You Begin:
At the end in the Resources section of this exercise there's a code file that includes some calculations from basic mechanics. Download the code file from the green arrow button and run it in the
terminal
. The problem should be imminent: you can't see any results.
In case you don't remember how to run code files in the terminal, look here.
Main Program Modifications:
Your task is to add print
function calls
to the last two lines of the program so that these lines that previously did nothing will have their results printed.
Resources:
acceleration.py
x_0 = 50
v_0 = 100
a = 10
t = 5

v_0 + a * t
x_0 + v_0 * t + 0.5 * a * t ** 2

Return your printing code here
Warning: You have not logged in. You cannot answer.
As we are mostly dealing with numbers in the beginning, most of our useful functions besides print will be mathematical. These include functions for taking minimum, maximum and absolute values: min, max and abs. There are even more mathematical functions included in Python but they have been wrapped into a separate
module
. Fear not, we will use them soon enough.
Besides mathematical functions there's one function that is useful when working in the
Python console
: help. Without any arguments it opens an interactive help interface. If instead given a function's name as an
argument
it shows information about the specific function. The following call would show information about the round function:
help(round)
Typically these help printouts are shorter and less detailed than the ones in the online documentation. It's still useful for quickly checking what kinds of arguments a function accepts etc. Once you're done looking you can exit back to the console by pressing Q.

The Secret Lives of Functions

Now we've learned enough basics about using
functions
. Our next trip takes us to the dark side of the moon where we will be creating our own functions. We will also take a look at the structure of code files while we're at it.
Learning goals: After this section you know the syntax for defining functions. You will become aware about how the code inside a function is separate from the rest of the code. You will also have some understanding of how variables and their values behave within functions and function calls. As a bonus you also learn how to organize your code file and why it's important.

Function Legos

The internals of a
function
contain just ordinary code. There are however two important
keywords
that are unique to functions. The first one of these is def which indicates a
statement
that defines a function. The second one is return which indicates a statement that exits the function and returns code execution to the line where the function was
called
from, and what value(s) will be
returned
to it. Code inside a function is separated from rest of the code by indenting after the def statement. Here's an example that we can poke:
def calculate_distance(speed, time):
    return speed * time
This function is rather simple - so simple in fact that you probably would not want to make it a function in a real program. The first line uses the def
keyword
to tell Python that this line starts a function definition. The next line has been
indented
, indicating that this line is inside the function, isolated from other code. The def line by itself also has three distinctive parts to it: the def keyword itself, the name of the function, and the function's
parameters
.
The rules and guidelines for naming
variables
also apply to naming
functions
. However, function names typically have a verb to indicate an action - something the function performs. When function names are used in code they are also often followed with parentheses whether they're being defined or called.
distance = calculate_distance(100, 2) # distance is a variable, calculate_distance is a function
On the line that start the function definition, the parentheses contain the function's parameters - in our example, speed and time - separated by a comma. Finally the definition line must always with a colon. Colon has a specific meaning in Python: it starts a new
code block
which means the next line(s) must be
indented
.
Function definition ends when the indented block ends. Often a line containing the return keyword is at the end of the function. This line will always exit the function. It also defines what the function
returns
as its result. It defines the second half of the interface that the rest of the program uses to communicate with the function whereas the
parameters
on the defining line form the first half.

Energetic Function

Defining your own functions is an important aspect of programming. This involves learning the correct syntax and understanding what parameters are.
Learning goals: Defining a
function
and terminology related to it.

Answer Specification:
You need to write a code line that starts a new function definition. The function's name must be calculate_energy and has to have two mandatory
parameters
: mass and velocity (in this order).
Write your function definition line (the one starting with the def keyword, not the function code itself) below:
Warning: You have not logged in. You cannot answer.

Parametric Argumentation

The concepts,
parameter
and
argument
, are integral when playing with functions. Parameter is a
local variable
- a name that is used for an argument's value inside the function. Argument is a
literal value
or a
variable
, and its value is given to a parameter when the function is
called
. In other words an argument is
assigned
to a parameter.

Paramaster

Below is a program that calculates properties of a cylinder. Your task is to recognize which names in the program belong to parameters.
PI = 3.1416

def calculate_volume(radius, height):
    volume = height * PI * radius ** 2
    return volume

def calculate_area(radius, height):
    area = 2 * PI * radius ** 2 + 2 * PI * radius * height
    return area

length = 10
lid_radius = 2
print(calculate_volume(lid_radius, length))
print(calculate_area(lid_radius, length))
Check the boxes attached to names that belong to parameters.
Warning: You have not logged in. You cannot answer.
Of course
arguments
are not assigned to
parameters
randomly. Assignment is based on position: each argument will be assigned to the parameter in the corresponding position. It's also worth noting that despite the terminology being used, the
value
is not actually moved or copied anywhere. The process simply creates a new
reference
from the parameter to the existing value. The entire process is illustrated below:

Parametric Discrimination

Passing of values from arguments to parameters is another process that should be understood well. Naturally it means also understanding what arguments and parameters are in the first place... That would be the topic of this exercise.
Learning goals: Familiarize yourself with the concepts of
value
and
parameter
and their role in
function calls
.

Introduction:
Below is a
function
definition and a short code snippet that calls the function. This function could be used in a program that shows how many solutions a quadratic equation has.
def calculate_discriminant(factor_1, factor_2, constant):
    discriminant = factor_2 ** 2 - 4 * factor_1 * constant
    return discriminant

print(calculate_discriminant(5 - 8, 4 * 3, 13))

Answer Specification:
Your task is figure out what
value
each
parameter
receives. Write your answer in the following format:
factor_1 = ?
factor_2 = ?
constant = ?
Copy the template to the box below, then replace each ? with the value of each parameters.
Warning: You have not logged in. You cannot answer.
The concept of scope is critical in understanding parameters.
Local variables
are not visible outside of their scope. In this case the scope is the function. They simply do not exist beyond this scope. All
parameters
and other
variables
that are created inside the function are local variables. In addition to not being visible outside, they also cease to exist when the function's execution ends.
This means that you can have variables with the same names inside two different functions and these will not interfere with each other in any way. There is also another scope - the
global scope
, or the main program's scope. Names within the global scope are readable from anywhere in the program. However, they cannot be
assigned
new values outside of the main program's scope. For now everything that is not indented is part of the main program scope. If you try to assign to a main program variable from within a function, Python will instead create a new
local variable
with the same name.

Local Expert

In this simple identification task you have to find all
local variables
from the given code file.
def calculate_unit_vector(x0, y0, x1, y1):
    length = ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** 0.5
    ux = (x1 - x0) / length
    uy = (y1 - y0) / length
    return ux, uy

def calculate_position(direction_x, direction_y, speed):
    x = direction_x * speed
    y = direction_y * speed
    return x, y

movement_speed = 5
initial_x = 2
initial_y = 6
target_x = 10
target_y = 12
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
new_x, new_y = calculate_position(vector_x, vector_y, movement_speed)
print(new_x)
print(new_y)
Listed below are all names in the code. Which among them are local names?
Warning: You have not logged in. You cannot answer.
Image source 5

The Return Trip

In the same vein as
values
are given to a function by assigning
arguments
to
parameters
, values are returned from a function via its
return value
. The return value is defined by the return
keyword
like we did in the exercise above. Understanding the difference between
variable
and
value
is once again essential. When returning, variables are not suddenly released from within the function. What return statement does is that it offers a reference to the value that was returned. It is up to the caller to decide what to do wit it. Here's the previous example, slightly modified:
def calculate_distance(speed, time):
    distance = speed * time
    return distance

v = 100
t = 0.6
s = calculate_distance(v, t)
In this example the
function
returns a reference to the
value
of the distance
variable
. In the last line of the example the reference is
assigned
to a new variable s. The name distance will not be exposed outside the function and the variable itself will cease to exist after the function call has been completed. We do however have a new variable, s, which refers to the same value that distance used to refer to. The value crosses the boundary between function and main program, but the variable does not.
As learned earlier, you can basically imagine a function's return value where the function call used to be once the call is completed. What follows is that instead of assigning the result to a variable it can also be passed on as an argument to another function. Which we actually already did:
result = int(round(64 ** (1 / 3)))
A function can also return multiple values. One such function is divmod which performs division and returns both the integer quotient and the remainder. When a function returns multiple values each of those values can be assigned to its own variable. This is simply a matter of putting a matching number of variables on the left side of the
assignment operator
:
In [1]: dividend = 10
In [2]: divisor = 3
In [3]: quotient, remainder = divmod(dividend, divisor)
In [4]: print(quotient)
3
In [5]: print(remainder)
1
We actually saw this a moment ago in the exercise where the components of a 2-dimensional vector were returned from a function. If you've followed along so far, you should know that by the time the assignment is done, there are only two numbers on the right side of the assignment operator. Therefore it should also be possible to simply assign two
literal values
to two variables on one line. Turns out it is:
In [1]: quotient, remainder = 10, 3

Writing Functions

So far it seems the rabbit hole that is
functions
goes way deep. Yet here they are in the beginning of the course. What makes them worth all this trouble?
We hope that this list makes you experience enlightenment like the cat in this picture:
Picture of a cat staring very closely at a bright white monitor
Image source 6
An ideal function does one clearly distinctive thing. Its name should also convey what the thing it does is. If a function does not fulfill these requirements it either does too many things or is poorly named.
Another prospect of ideal functions is that they are as reusable as possible - within reason. If a program contains several procedures that are almost similar, in an ideal scenario all of those can be done with one function. The reusability of functions is heavily influenced by the choice of
parameters
. In math this is relatively simple: make all unknowns in a formula function parameters so that they will be given as
arguments
when the formula is needed in the program.
In general
parametrization
is a skill that develops through programming experience. It can be practised by looking at mostly identical structures and spotting their differences. These differences can often be turned into function parameters. The exercises of this course generally ask you to implement reusable functions. To get the most out of them, you should stop for a while to think why each function has been defined as it has been.

Function Placement

The placement of
functions
in code does matter. A function is created the moment its definition line - indicated by the def keyword - is executed. Therefore the definition line must precede any lines that would use the function. At this point it's important to remember that code inside a function is not executed until the function is
called
. This means that the order of function definitions does not matter. Code inside a function (A) can call another function (B) that is defined later in the code as long as function A is not called before function B is defined.
Since the order doesn't usually matter, you can choose your own system for organizing functions in your code. In general functions should be defined in one clearly separate part of the code. Roughly a code file should be divided into three parts:
  1. initialization part, for various preparations;
  2. function definition part, where all functions are defined;
  3. main program part.
Screenshot of a code file where constant definition is marked as belonging to the initialization part, a function definition is marked to the function definition part, and some calcualtions using the above marked as the main part
The three parts of a code file. Parts should not overlap.
The initialization part does things that are required throughout the program. Generally this means defining
constants
and importing
modules
. We'll get to both of these later. The function definition part should define all
functions
in the program. It will therefore contain def
statements
followed by indented function contents.
Finally the main program part is where the program actually starts. Before that all functions should have been defined. Usually all a
main program
does is
call
functions. If the functions are well named this makes the flow of the program very clear. In some programming languages the "main program" is placed inside a special main function and the program starts from that function.

A Prompt Lesson

Learning goals: After this section you'll know how to print messages to the user and how to prompt input from them. In particular you will know how to obtain a numerical value from the user to be used in the program.

More Vector Geometry

In this section we'll work on an earlier example. In an earlier exercise we introduced bunch of code that calculated unit vectors and motion using said unit vectors and a velocity. There is one particular glaring flaw in the program: in order for it to work as a proper vector calculator it would need a way to actually input points without editing the
code file
itself. As a more minor flaw, the program currently just prints out numbers without explaining what they are:
4.0
3.0
In other words the user has no way of knowing where these numbers come from and what they mean. There are at least two immediate improvements that can be made: first of all the program should prompt for the vector's start and end points from the user; second it should label the numbers it prints out.
For now let's only make use of the function that calculates the unit vector. The other function can be left in the code, we're just not going to use it. We've included the code file below in case you've lost it. We've also removed any main program lines that are not related to calculating the unit vector, and added lines to print the unit vector.
unitvector.py
def calculate_unit_vector(x0, y0, x1, y1):
    length = ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** 0.5
    ux = (x1 - x0) / length
    uy = (y1 - y0) / length
    return ux, uy

def calculate_position(direction_x, direction_y, speed):
    x = direction_x * speed
    y = direction_y * speed
    return x, y

movement_speed = 5
initial_x = 2
initial_y = 6
target_x = 10
target_y = 12
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
new_x, new_y = calculate_position(vector_x, vector_y, movement_speed)
print(new_x)
print(new_y)

It Talks!

The program should start by telling the user something along these lines: "This program calculates the unit vector between two points on a 2-dimensional plane". In order to do this, we need a new skill: text processing. In programming, text is usually called
string
because it has letters lined up after each other. Almost as if there were letters on a...
(•_•)
( •_•)>⌐■-■
(⌐■_■)
...string. So don't allow your cat anywhere near your code.
So far we've used letters to name things like variables and functions in the program. How does Python know when something is a name and when it's a string then? Strings are marked by quotation characters. When a quotation character is encountered Python knows for certain that whatever follows after should be interpreted as a string. Likewise the string will continue until another quotation character is encountered. Single (') and double (") quotes can both be used as long as each string begins and ends with the same type of quote. The same explanation in code:
"string"
'another string'
variable
When it comes to choosing which quote to use, the general rule is just "choose one". I.e. whichever you choose, stick with it. The material uses double quote (") because it's generally more common in other languages. Some languages, e.g. C, only allow single characters to be quoted with single quotes and string must be marked with double quotes.
String
is its own separate
type
. It joins the ranks of types that so far consist of integer and
float
. Therefore string are
values
that are stored in memory just like numbers and everything we've said about values so far also applies to strings. Strings can be
assigned
to
variables
, and they even support some
operations
. They can also be printed with the print
function
just like numbers. Therefore the program introduction line ("This program calculates the unit vector between two points on a 2-dimensional plane") can be shown to the user by passing it as an
argument
to the print function:
print("This program calculates the unit vector between two points on a 2-dimensional plane")

Donkey Party

Learning goals: Writing a simple print
function call
.

Answer Specification:
Write a line of code which outputs the following text: donkeyswings.
Why, you ask? Because you totally can!
Type the code line below.
Warning: You have not logged in. You cannot answer.
Our vector program should label the vector components it prints. We should also inform the user about the start and end points of the vector since at the moment it cannot be seen from anywhere. Adding the prints:
print("This program calculates the unit vector between two points on a 2-dimensional plane")
initial_x = 2
initial_y = 6
target_x = 10
target_y = 12
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
print("Starting point (x y):", initial_x, initial_y)
print("Target point (x y):", target_x, target_y)
print("Directional vector (x y):", vector_x, vector_y)
We've also snuck in a new way to use the print function into this example: it can actually be given more than one argument to print. To be more precise, print is a function that prints all of its arguments (number unspecified) separated by spaces and terminated by a newline (in fact you can change the separator and terminator characters as well, but that's a matter for another time). If you run this program, you should see much more informative output:
This program calculates the unit vector between two points on a 2-dimensional plane
Starting point (x y): 2 6
Target point (x y): 10 12
Directional vector (x y): 0.8 0.6

Input 101

Next we want the program to ask the user to provide the points instead of just letting deciding on its own. For majority of the course we will communicate with the user through text
prompts
because we only need one
function
to use them: input. The first thing to do when learning a new function is to see what Python itself says about it:
In [1]: help(input)
Help on built-in function input in module builtins:

input(...)
    input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.
The basics are easy enough to spot: the function has one
optional
argument
and it returns a
string
. The help text itself tells us that when the user terminates the input with the Enter key the newline produced by it is not included in the string
returned
by the function. And the prompt
parameter
? It contains a message that is displayed to the user. Its purpose is to instruct the user about what they should input.

Prompt Play

Learnin goals: See what input
function
actually does.

Introduction:
Write the following to the
Python console
:
In [1]: input("Tell your name: ")
When the prompt is printed, lie that your name is donkey.

Answer Specification:
We're looking for the value that is shown (after Out [1]) when you have pressed enter after typing your name.
To the answer field below, copy the line that Python outputs when you press the enter key.
Warning: You have not logged in. You cannot answer.
Since input works just like any old
function
the
value
it
returns
can be
assigned
to a
variable
. The biggest difference is that the return value is not directly dependent on the given
argument
. The argument is just an instruction to the user, and whatever the user decides to input based on that, the function returns. The animation below illustrates how the input function works.
Our present vector code's
main program
starts like this (excluding the instruction line):
initial_x = 2
initial_y = 6
target_x = 10
target_y = 12
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
By modifying the first four lines to use input we can obtain values for the
variables
from the user. We can also remove the lines that print the two points. The user should know what the points are since they were just asked to provide them! With these things in mind, the main program changes to
print("This program calculates the unit vector between two points on a 2-dimensional plane")
initial_x = input("Input starting point x coordinate: ")
initial_y = input("Input starting point y coordinate: ")
target_x = input("Input target point x coordinate: ")
target_y = input("Input target point y coordinate: ")
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
print("Directional vector (x y):", vector_x, vector_y)
We're adding one space to the end of the input function
argument
. This will reduce claustrophobic feelings by separating the prompt message and the user's input from each other:
Input starting point x coordinate: 2

One Type of Error

Learning goals: In this exercise you'll learn about an erorr that will undoubtedly occur many times during the course: what happens when a user's input is used in calculations as it is.

Introduction:
Download the code from below and run it in the
terminal
. Input the values 2, 6, 10 and 12 as seen in the examples.

Answer Specification:
We're looking for the name of the
exception
that occurs. The name is the on the beginning of last line of the error message, before the colon.

Resources:
unitvector.py
def calculate_unit_vector(x0, y0, x1, y1):
    length = ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** 0.5
    ux = (x1 - x0) / length
    uy = (y1 - y0) / length
    return ux, uy

def calculate_position(direction_x, direction_y, speed):
    x = direction_x * speed
    y = direction_y * speed
    return x, y

print("This program calculates the unit vector between two points on a 2-dimensional plane")
initial_x = input("Input starting point x coordinate: ")
initial_y = input("Input starting point y coordinate: ")
target_x = input("Input target point x coordinate: ")
target_y = input("Input target point y coordinate: ")
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
print("Directional vector (x y):", vector_x, vector_y)

Copy the name of the error to the box
Warning: You have not logged in. You cannot answer.

Answers Can Be Wrong but Questions Never Are

The wall of text achieved in the previous exercise should look something like this:
This program calculates the unit vector between two points on a 2-dimensional plane
Input starting point x coordinate: 2
Input starting point y coordinate: 6
Input target point x coordinate: 10
Input target point y coordinate: 12
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/some/folder/unitvector.py in ()
     15 target_x = input("Input target point x coordinate: ")
     16 target_y = input("Input target point y coordinate: ")
---> 17 vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
     18 print("Directional vector (x y):", vector_x, vector_y)

/some/folder/unitvector.py in calculate_unit_vector(x0, y0, x1, y1)
      1 def calculate_unit_vector(x0, y0, x1, y1):
----> 2     length = ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** 0.5
      3     ux = (x1 - x0) / length
      4     uy = (y1 - y0) / length
      5     return ux, uy

TypeError: unsupported operand type(s) for -: 'str' and 'str'
An
error message
consists of two parts: the longer part with indentations shows where in the program the error occurred. The last line describes what kind of error was encountered. The first part shows a
traceback
, essentially a chain of
function calls
that led to the error. It starts from the
main program
and ends with the part that ultimately caused the error. In this case the chain starts from the main program (written as <module>) line 17 where the calculate_unit_vector
function
was called.
The error itself is encountered inside the calculate_unit_vector function on line 2. The last line tells us that we encountered a TypeError
exception
. This exception indicates that at least one of the
values
in the program has the wrong
type
. The description on the same line gives us more details: we're trying to subtract one
string
from another.
Debugging
is an essential programming skills and learning to read these error messages is an important part of it. Let's go through this thing in detail one more time:
However although we've been shown the line where the error ultimately happens, this doesn't mean the cause of the error is on this line. And indeed, it isn't in this case.

Sherlock de Bug in The Methods of a Master Detective

In problem situations, it is advisable to do some detective work. One important method is to check in the interpreter or with a small source code file how a specific part of a program exactly works. In this case, we'll check how input function operates.
Learning goals: More details about how the input
function
works - what happens when the input is a number.

Introduction:
Write the following into the
Python console
:
In [1]: input(": ")
: 23

Answer Specification:
Once again we want a copy of the value that is shown after giving the input. It would also be wise to consider what this value means for mathematical operations.
What does the interpreter show as a return value of the input function?
Warning: You have not logged in. You cannot answer.
Image source 7
So the actual problem is that the input
function
produces a
string
while we need an integer or a
floating point number
. By amazing coincidence what we learned earlier about conversion between these two number types with int and float functions comes in handy here as well. As it turns out they can also convert strings to numbers. The requirement is that the string needs to actually look like a number: either an integer or a decimal number. In this case converting to float is better because we never said the coordinates must be integers. This can be done by modifying the input lines:
initial_x = type(input("Input starting point x coordinate: "))
After doing this for all input lines the program works as long as the user
inputs
only numbers. If the user doesn't input a number we're in all kinds of fresh and exiting problems. However for this material we're just gonna assume that no one's gonna do such a basic mistake... The updated code file is below:
unitvector.py
def calculate_unit_vector(x0, y0, x1, y1):
    length = ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** 0.5
    ux = (x1 - x0) / length
    uy = (y1 - y0) / length
    return ux, uy

def calculate_position(direction_x, direction_y, speed):
    x = direction_x * speed
    y = direction_y * speed
    return x, y

print("This program calculates the unit vector between two points on a 2-dimensional plane")
initial_x = float(input("Input starting point x coordinate: "))
initial_y = float(input("Input starting point y coordinate: "))
target_x = float(input("Input target point x coordinate: "))
target_y = float(input("Input target point y coordinate: "))
vector_x, vector_y = calculate_unit_vector(initial_x, initial_y, target_x, target_y)
print("Directional vector (x y):", vector_x, vector_y)

100 Bugs in the Code

Before moving forward, you get to write your own input line! Your task is to write a single line of code that presents the user a question "How many bugs in the code? " In addition you can stop to think about how many bugs will be in the code when one is fixed...
Learning goals: Once again recalling how to use the input
function
.

Introduction:
Copy this
string
so that you can use it as the input function's
argument
:
"How many bugs in the code? "

Answer Specification:
We're looking for an input function call where the given string is its argument. In addition the function's
return value
has to be converted to an integer and finally the whole thing should be
assigned
to a
variable
called bugs.
Type the code line to the answer field.
Warning: You have not logged in. You cannot answer.

Modules

Learning goals: After this section you'll know what modules are and how to use modules that come with Python. More detailed explanations will be given later in the course.

Modules in the Spotlight

In this section we're going to only talk about
modules
that are included in Python itself. There's a vast amount of other modules - including every
code file
you write - but at this stage we shan't fuss about them. Actually, you've already used one module: the drawing tasks in the pre-exercises use a module called Turtle. Back then in order to utilize it we just used a magic line of code that was not explained in any way: from turtle import *. Since mysticism is bad for learning it's about time we explained what's going on with this line. From our perspective Turtle is a collection of
functions
that for all intents and purposes behave just like any functions we've seen in the material so far. These functions come with Python but they've been packed to a separate module. This is done primarily because most programs don't need these features, and loading them would just produce extra baggage.
Functions contained within modules are not automatically loaded up for all Python programs. Instead we need to indicate when we want to use them. This is the purpose of the
import statement
. The magical import statement we used in the pre-exercises is actually a less common method of importing modules. We're now going to introduce the more common and usually more correct way to do it. It may feel sillier at this point but it will keep your code much cleaner when projects start to get bigger. But first we need to talk about namespaces.

Names in Space

One of the key points in this material has been that names defined inside a function only exist within that function. A similar principle applies to modules. The names defined within a module are said to be part of the module's
namespace
. However as opposed to functions, module names can be exposed to other modules by using the import statement. In its simplest form an import statement is just import module_name, e.g. for Turtle import turtle. The difference compared to the magical line from earlier is that this doesn't directly bring us all names from inside Turtle. Instead it only brings one: turtle.
Illustration with two boxes: the left one contains only the name "turtle"; the right one contains the first four and last two names from the turtle module (with triple ellipses in the middle)
The namespaces of a program and an imported module
How do we actually use the functions if all we have is some crappy turtle? The other names are attributes of the module object. In Python attributes of any object are accessed by prefixing the desired name with the name of the module it resides in and a single dot. E.g. drawing a line forward: turtle.forward(50). This method does require more typing but it has a distinct advantage: readers can easily tell with a glance that forward is a function that belongs to the turtle module. If import is done like we did in the pre-exercises, all of the names from that module are brought into our program's namespace. This makes it very hard for anyone reading the code to figure out where each name is coming from.
Drawing a circle using import turtle would go like this:
In [1]: import turtle
In [2]: turtle.circle(30)
Using the from-import syntax can also cause unexpected
name conflicts
. If the names from all imported modules are put into the same namespace the probability of name conflict increases with each added module. If a name conflict happens either the program will simply not run because some variable or function has been overwritten with another. Or perhaps even worse, if the program does run it may have unexpected behavior that is hard to debug.
In some cases it gets tiresome and even messy to write the entire module name before each function when the same function is used repeatedly. However, this is not a reason to use heavy weaponry like the from turtle import * statement. In that line, the asterisk * is a shorthand for importing everything (i.e. it's a wildcard character). It can be replaced with a list that's been narrowed down to only contain names we actually need. For instance if we want to draw squares like we did in the pre-exercise, the following import would allow us to do it just like we did previously:
from turtle import begin_fill, color, done, end_fill, forward, left
The advantage of doing this is that now we're clearly indicating which functions have been imported from Turtle. Another way to alleviate the module name writing problem is to use aliases: modules can be renamed upon import. This is particularly useful when functions from a module with a long name are used repeatedly. In order to do this, we would write an import like this: import turtle as t where the rightmost t is the new name. Drawing a circle would now look like:
In [1]: import turtle as t
In [2]: t.circle(30)

Mathy Modules

As stated previously, for now we will only be using modules that are included in Python. We say "only" but there's quite a few of them already. Although there's a lot of them it's relatively easy to tell what each module could be used for based on their names and short descriptions. Depending on what you're doing, chances are you'll never need majority of them. At the moment we only need Turtle, and now we're adding just one other module to the pile: math. The module contains most common mathematical operations that are not common enough to be included in the list of
built-in functions
.

Fishing for Math

When fishing you need to know where to go when you want to catch a specific fish. So it is with programming and mathematical functions. There's simply so many of them that not all of them exist in the same place. The most basic of basic functions are built into Python itself but a bit more specific functions have been tucked away into the math module. The math module contains most functions that are familiar from high school math. But for really heavyweight math you need to look even further...
Learning goals: Explore the contents of the math
module
and learn what operations need functions from there, and which can be done with just basics.

Introduction:
Open the following pages in your browser:

Answer Specification
We have listed a bunch of mathematical operations below. Your task is to find out which ones of these can be done with Python's
builtin functions
or
operators
, and which ones require functions from the math module. In this exercise we consider an operation requiring math module if it cannot be done with a single operator or function otherwise. This means that while some of these things can be done by combining basic operators/functions, we always want a function that does the whole thing by itself - and your task is to know where that function is.
Choose operations that require a function from the math module (there's 4)
Warning: You have not logged in. You cannot answer.
In addition to functions, some modules also contain constants. They will be introduced in more detail in the next section. Constants from modules are used just like functions: prefix with module name and a dot. For instance, the math module contains the commonly used mathematical constants pi and e. These can be accessed in Python from the math module like this:
In [1]: import math
In [2]: math.pi
Out[2]: 3.141592653589793
In [3]: math.e
Out[3]: 2.718281828459045
The values for these constants are as accurate as possible for computers - the
Python console
just doesn't by default show more decimals. We'll play with the math module more in the exercises.

Constants

Learning goals: After this section you know what constants are, what they are used for and how they affect the rest of the code.

The Cake is a Lie

Title is appropriate: Python doesn't actually have
constants
. Constants are nothing more than
variables
that are just used in specific ways in code. In general terms constants are values that are usually set at the start of code execution and they cannot be changed. In this sense they are very related to mathematical and physical constants. They can be used to make formulas more readable: when some arbitrary number is given a name instead of using it as a
literal value
. Names have meaning, numbers usually don't. This makes the code easier to follow for a reader because they don't need to figure out the meaning of a mystical arbitrary number in the code. There can also be situations where the same value is used in multiple places in the program - if the value needs changing later, it's much easier to change it one place.
Constants should be defined in the initialization part of the code, after imports. Since constants are just variables they are created the same way: by
assigning
a value. While constants don't exist as a separate concept in Python, when a variable is roleplaying a constant, its name is written in uppercase.
SPEED_OF_LIGHT = 299_792_458
This also shows off a feature introduced in Python 3.6: long numbers can be written by using underscore as a separator to make them more readable.

Mirror, Mirror Off the Scale

Constants can help in making code much more maintainable. In game programming there's a common use case for scaling when the game's geometry (i.e. character size, movement speed etc.) has the be scaled with the window size. In this example we have defined a scalable game character.
Learning goals: Using
constants
to replace repeatedly used
literal values
.

Introduction:
Our game character has three attributes as defined below:
size = 40 * 0.8
speed = 10 * 0.8
range = 200 * 0.8
The value 0.8 seen here is a scaling factor that is applied to the game's geometry (i.e. all
values
that are measurements will be multiplied by it). In this case the final values haven't been calculated beforehand because nice round integers are easier to handle. However, if we actually want to change the scaling we need to change the value everywhere.
To avoid this issue a competent programmer should define a constant in the beginning of the
code file
:
SCALE_FACTOR = 0.8

Answer Specification:
Change the three lines that define character attributes so that they use the constant instead of the literal value 0.8. In other words after the change is made, changing the value of SCALE_FACTOR should affect all three attributes. This is incredible convenient in case the value needs to be changed.
Rewrite the changed lines into the answer box, in their original order.
Warning: You have not logged in. You cannot answer.
Since
constants
are defined at the beginning of the code file they belong to the
global scope
which makes them conveniently available for reading inside
functions
. As we've discussed earlier, functions can read variables from the main program's scope. However, please bear in mind that functions should never use values that it has not received either a) as a
parameter
or b) from a constant.

Summary

This chapter introduced the essential buildings blocks for learning programming.
Variables
are the means that computers use to remember
values
during program execution. In Python variable and its value are separate entities: a variable
refers
to a value that exists in the computer's memory. Even so, it is often said that variables contain values even though this is not exactly accurate.
Our second essential building block are
functions
. Functions act as means to divide a program into smaller components that can be reused. Structuring of code is the main advantage of functions. Small components with a specific purpose are much easier to handle than big wholes that try to do everything. By splitting a program into functions it's possible to solve small problems one at a time which is far more effective than trying to solve the entire problem at once. Functions enable division of tasks within the program.
An important aspect related to functions was
scopes
within the program. Particularly important was the principle of separating the internal scope of each function from the
global scope
of the
main program
. It is one of the more difficult concepts in the beginning. The rule of thumb is that functions should only read values from variables that are their
parameter
. In addition they can read values of
constants
.
We also took a quick glance at how to use
modules
. Modules are a way to wrap together useful functions (and other things) that are related to a certain purpose. We looked at two examples: Turtle, which we use for simple drawing programs; and math which is more useful for serious programs. Scope was also important for modules, and in their case it was referred to as
namespaces
. We looked at how the
import statement
can be used to decide how to access functions from other namespaces. There will be more about modules in the fourth material where we also learn how to create them.
Finally we briefly introduced
constants
that are used instead of repeatedly appearing
literal values
. This is done for two reasons: first, a named constant is far more descriptive than an arbitrary value in the code; second, if the value would be present in multiple places, it is much easier to maintain the code if it is only defined in one place.

Image Sources

  1. Screen capture of History Channel's Ancient Aliens, caption added.
  2. original license: CC-BY 2.0 (caption added)
  3. Screen capture of Inception (movie), caption added.
  4. original license: CC-BY 2.0 (caption added)
  5. original license: CC-BY 2.0 (caption added)
  6. original license: CC-BY 2.0 (caption added)
  7. oroginal license: CC-BY 2.0 (caption added)
?
  1. Description
  2. Examples
Absolute path is an operating system term that refers to the full "address" of a file or folder. Absolute path is written starting from the disk root. When absolute path is used, the current directory does not matter. Absolute paths are usually avoided in code - especially in applications that are meant to be shared. Another user is very unlikely to have the exact same folder structure as the application's developer. In particular if an absolute path refers to the user's home folder, it is very likely not going to be the same for another user.
Ajonaikaisesta (engl. run time) puhuttaessa määreenä on se aikaväli, kun ohjelma on käynnissä. Esimerkiksi Pythonissa virheet (syntaksivirheitä lukuun ottamatta) tarkastetaan ajonaikaisesti. Ohjelma saattaa siis olla käynnissä ja toimia tiettyyn pisteeseen saakka, kunnes törmätään käsittelemättömään poikkeukseen – ajonaikaiseen virheeseen (engl. run time error).
  1. Description
  2. Esimerkit
Alustamisella (engl. initialize) tarkoitetaan yleisesti jonkin arvon asettamista muuttujalle muuttujan luonnin yhteydessä. Pythonissa ei ole mahdollista luoda muuttujaa, jolla ei ole myös jotain arvoa. Niinpä tyypillisesti käytetäänkin sanamuotoa ”muuttuja alustetaan arvolla x”, millä tarkoitetaan sitä, että muuttuja, joka luodaan, saa luomisen yhteydessä (eikä vasta joskus myöhemmin) arvon x.
  1. Description
  2. Esimerkit
Argumentti (engl. argument) on funktiokutsussa käytettävä arvo, joka välitetään kutsuttavalle funktiolle. Funktiokutsun alkaessa argumentit sijoitetaan parametreiksi kutsuttuihin muuttujiin, joiden kautta arvoihin pääsee funktion sisällä käsiksi.
Arvo (engl. value) on konkreettista, tietokoneen muistissa sijaitsevaa tietoa, jota käytetään ohjelman suorituksen aikana. Arvoilla on tyyppi ja sisältö; esimerkiksi numero 5 on tyypiltään kokonaisluku, jonka sisältö on 5. Useimmiten arvot liitetään muuttujiin, mutta myös operaatioiden ja funktiokutsujen paluuarvot sekä koodissa sellaisenaan esiintyvät arvot ovat arvoja. Käytännössä siis kaikkea konkreettista mitä ohjelma käsittelee voidaan kutsua arvoiksi.
Assignment is related to variables and values. A typical figure of speech is "assigning to a variable" which means giving a certain value to a variable (e.g. x = 5). More specifically, in Python, assignment to a variable means creating a connection between the name and value of the variable - the variable is a way to find the value.
Similar expressions that can be used to mean the same thing are: "saving to a variable", "storing to a variable", "referring to a variable", "stuffing a value into a variable"... etc.
Assignment operator i.e. the = character is used for variable assignment. When using the operator, the target variable must always be on the left side and the value (or statement that produces the value) on the right side.
Attribute is a value that belong to an object, sometimes also called property. It's a name that belongs to the object's internal namespace and it can be accessed through the object: timestamp.tm_hour would read the hours from a timestamp.
  1. Description
  2. Kurssin avainsanat
Avainsanat (engl. keyword) ovat ohjelmointikielessä kielen käyttöön varattuja sanoja, joilla on erityinen merkitys. Hyvät tekstieditorit tyypillisesti merkitsevät avainsanat muista nimistä eroavalla tavalla (esimerkiksi lihavoinnilla tai tietyllä värillä). Avainsanat ovat yleensä suojattuja, eli samannimisiä muuttujia ei voi luoda. Yleisiä avainsanoja Pythonissa ovat esimerkiksi funktioihin liittyvät def ja return. Avainsanat ovat siis osa ohjelmointikielen kielioppia.
Boolean is the most simple data type in programming languages because it has only two values: true (True in Python) and false (False in Python). Things like comparison operators return booleans, and they are often used in conditional statements and while loops. In Python all values are equivalent to one of the boolean values. Generally all so called empty values (0, "", None etc.) are equal to False while the rest are equal to True.
  1. Description
  2. Extra info
Boolean operator refers to Boolean algebra which deals in values of truthfulness. These operations include and, not, and or - all familiar from conditional statements. Out of these and is True if and only if both operands are True; or is True if at least one operand is True; and not is True is its sole operand is False.
Branch is an execution path in the program that is mutually exclusive with other branches in the same control structure. For example in a conditional structure each if, elif and else define their own branches and only of them is executed.
Bug is an error in the program's source code. As the result of a bug the program either doesn't start at all, crashes during execution, doesn't work correctly in some situations, or can even cause severe security issues. Careful programming and testing - including rare edge cases - reduces the probability of bugs. Tracking down the part of code that causes a bug and fixing it is called debugging.
Buitin functions are function that are included in the Python core. They can always be used without importing any modules or libraries.
Callback is a common mechanism, especially in modern programming, where another part of the program - often made by someone else - is given a function it is to call during its execution. If a normal function call is like a phone call, a callback is a like a call request. If a part of the program uses a callback, it usually described what kind of a function it accepts - especially what parameters the function can/must have and what kind of a value it should return.
Where UNIX-based systems produce \n characters (newline) to indicate line breaks, Windows uses \r\n where the r is a carriage return character. It's a remnant from mechanical typewriters, and indicates the procedure of physically moving the typewriter head to the beginning of the line. In general this is just something that's good to know - Python treats both line breaks quite nicely.
Code block or block is a term used for liens of codes that belong to the same context. A block is formed of lines that have the same indentation level (although a block can also contain other blocks). Typical blocks are the executable parts of conditional structures i.e. the indented code lines that follow a condition. A block ends when a line with less indentation than ones belonging to the block is encountered.
Code file is a text file that contains executable code. A Python code file can be ran from the terminal by typing python code.py where code.py is the file's name. When you run a code file the return values of individual lines are not shown unless they have been specfically rpinted.
  1. Description
  2. Material example
  3. Basic use
Command line argument or parameter is a name used for additional information that is passed to a terminal program when it's started. Command line arguments are typically separated by spaces. E.g. in python code.py, code.py is actually a command line argument. Command line arguments can be accessed in Python from the sys module's argv variable.
Comparison operators are used for comparing values to one another. They are familiar from mathematics and can be used to compare size. Comparison operators return a boolean value, True or False, depending on the result of the comparison. Comparison operators are: <, <=, >, >=, == and !=
Comparison values are used e.g. in sorting lists. A comparison value is a value derived from a list item that is used instead of the item itself in sorting. For instance, if a list contains lists, a comparison value can be an item taken from a certain index of each inner list. It can also be a more complex derivative such as the sum of items or their mean value.
  1. Description
  2. Examples
Condition is used in this course to refer to the part of conditional statements and while loops that defines when the statement is true. Anything between the keyword that starts the stamement and the colon that ends it is basically its condition.
  1. Description
  2. Examples
Conditional statement is a line of code that defines a single condition, followed by an indented code block which defines what should be done if the condition is true. Conditional statements include if and elif statements, the latter of which cannot be present without the former. Conditional statements that are linked together form conditional structures. A conditional statement must always end with a colon and it must be followed with at least one indented code line.
  1. Description
  2. Examples
Conditional structure is a structure that consists of one or more conditional statements that branches program execution. Most of them have at least two branches: if and else. Between the two there can also be an indefinite number of branches under elif statements. It is also possible to have nothing but a single if statement in a structure. Each branch in a conditional structure has at least some code that defines what the program does in a situation falling under a condition.
As a whole a conditional structure is interpreted by checking the truthfulness of the first branch (if). If it evaluates to True, program execution continues to the code block inside the statement after which execution skips the rest of the structure. If it evaluates to False, other branches will be evaluated in sequence until one of them is True, or if none of them are, the else branch is executed.
  1. Description
  2. Examples
Constant is a named literal value. They are used especially when the same literal value is used repeatedly in a program. Named constants are also just in general more practical in code than seemingly arbitrary literal values because its meaning can be derived from its name. Likewise if the value needs to be changed it is much easier if you only need to change it in one place (where it's defined). Python doesn't actually have a way to define "real" constants - they are simply variables. The difference is implied by writing constant names in full upper case. E.g THE_ANSWER = 42.
Control structure is a common name for different programming structures that control the program flow in some way. Within this course this includes conditional structures, loops and exception handling.
Data (engl. data) on ohjelmoinnin asiayhteydessä mitä vaan tietoa, joka ei kuitenkaan yleisesti kata itse ohjelmakoodia. Yleensä datasta puhuttaessa tarkoitetaan yksittäisiä literaaliarvoja, muuttujien sisältämää tietoa tai jostain tietolähteestä (kuten tiedostosta tai verkko-osoitteesta) luettua tai sinne kirjoitettua tietoa. Nyrkkisääntönä voi kuitenkin pitää sitä, että koodi ja data ovat eri asioita, ja koodi käsittelee dataa. (Joissain yhteyksissä koodikin lasketaan dataksi, mutta näihin ei tällä kurssilla syvennytä.)
Data format is the "syntax" of a data file, and it defines how data has been saved to the file. Data format also defines what kind of data can be stored in the file. The basic idea of each data format is to enable the saving of data structures in a program in some format that also makes it possible to load them back in later. A data format can be based on some existing standard (e.g. JSON) but ultimately it's the programmer's responsibility to choose what data is relevant for the program and how to best represent it.
Data structure is a common name for collections that contain multiple values. The purpose of a data structure is to store data that consists of more than one value. There are various ways to make a data structure and each of them convenient means for adding, removing and modifying values. Data structures implement a way to bundle data together. Generally the difficult details involved have been hidden from the programmer.
Choosing data structures that serve the purposes of your program and are easy to handle in your code is essential. The most common structures in Python are list, tuple and dictionary. Another convenient structure is set which doesn't contain duplicate values. In addition to built-in structures, more can be found from the collections module.
On later courses you'll also become familiar with other important structures like trees and graphs.
Debugging is the process of hunting down and fixing programming errors i.e. bugs. There are many ways to track down bugs. One of the more common ones in Python is the error message it shows when a program crashes. Another common method to find errors is the use of debug prints. This means putting additional print function calls in the code temporarily to either see how far the code gets or what kinds of values variables have. Debugging is such an important part of programming that there are even specific debugging tools that have been developed. We don't use them on this course however.
Default value is a value that can be defined for a function parameter. It will be used for that parameter's value if its corresponding argument has not been given in a function call. E.g. in def prompt_length(question, maximum=10): function definition, the maximum parameter has been made optional by giving it the default value of 10.
  1. Description
  2. Definition
  3. Value lookup
  4. Modifying dictionaries
Dictionary is a data structure that assigns keys (usually strings) to its values. The advantage of using dictionaries is that descriptively named keys make code that handles the data structure much easier to read. Starting from Python 3.7 dictionary keys and values are guaranteed to be in the order they were added.
In Python docstring is a comment-like entity but it has a special meaning. A docstring is usually delimited with triple quotes (i.e. '''document''' or """document""". If a docstring is placed immediately below a function's def statement (indented!), it becomes the function's documentation that is shown with the help function. Likewise a docstring placed at the very beginning of a code file becomes the module's documentation. A good doctstring describes what a function does, and explains its parameters and return values.
Docstrings should not be used as comments! Outside of the aforementioned places, commenting should be done with actual comments (lines starting with #).
Epätosi (engl. false) on toinen kahdesta mahdollisesta totuusarvosta ja toisen, eli toden, vastakohta. Sitä voidaan pitää lopputuloksena loogisissa ja vertailuoperaatorioissa, jotka eivät pidä paikkansa. Esimerkiksi vertailuoperaatio 5 < 4 ei pidä paikkansa, joten kyseinen operaatio evaluoituu epätodeksi. Pythonissa epätotta merkitään avainsanalla False.
  1. Description
  2. Examples
Error message is the Python interpreter's way of informing about an exception in a program. The error message contains information about where in the program the exception happened, which line caused the exception, the exception's type (e.g. SyntaxError) and a short verbal description. Error messages are your best friends and reading them is a very integral programming skill. Don't be afraid of them, they are only there to help you find out what's wrong in the code!
Escape in programming terms means interpreting a character in an exceptional way. For instance "n" is just the letter n but "\n" is a newline character. In this example the backslash character \ causes the normal interpretation of the n character to be escaped and replaced by another interpretation. The backslash functions as an escape character. One typical use is including " in a string that's delimited with ": "donkey ear interval is 14\""
Evaluointi (engl. evaluation) tarkoittaa lausekkeen tai muuttujan arvon lopputuloksen määrittämistä. Suoritettaessa lauseet evaluoituvat joksikin tietyksi arvoksi.
Event is a programming cocept that is generally used in the context of interactive applications that run in real time. These applications usually have a main loop that monitors for events. Events include: user clicks with the mouse, user presses a key, a certain amount of time has passed etc. Handler functions can be attached to events, and they will be called whenever the event is detected. This makes programming of interactive programs much easier because there's no need to worry about how actions on the screen are detected when implementing the application itself.
  1. Description
  2. Examples
Exception is a scenario in programming where the program cannot proceed as instructed. Exceptions have a type (e.g. TypeError) that can be used in handling the exception within the program. Type can also be useful when trying to solve the issue if it is not intended. In most cases exceptions also come with a message that gives more details about what caused the issue. In Python exceptions are handled with try-except structures.
Exception is the base class of most common exceptions. We also call it the Pokémon exception because if you use it in a try-except structure it will catch all the exceptions. In most cases this is not a good thing. It makes interpreting problem situations more difficult for both the user, and you, the developer. The latter is due to the fact that it will also catch any mistakes you made in your code, and you won't get any useful information when the program isn't behaving correctly.
Execution or running means going through a program or code snippet so that the instructions written within are carried out by the computer. Python interpreter executes code one statement at a time. While this is ongoing the program is "running". Execution ends when there is no more code to run, there's an unrecoverable error or when the program ends itself.
File extension is the part of the file's name that is on the right side of the last period in the name. They are commonly used for indicating file types. Image files for instance often have .png or .jpg as their extension. Python code files usually have .py at the end (e.g. donkeyswings.py).
File handle is a special object that Python uses to refer to an opened file. Most important note is that the handle is not the same as the file's contents - the handle can be used to read the contents, or write to the file. A file handle is obtained with the open function with the file's location (path) and the opening as arguments. E.g. with open("donkey.txt", "r") as somefile: opens donkey.txt inside a with statement (where files usually should be opened), with somefile as the file handle.
Filename is the name of a file that consists of the file's actual name and a file extension. For instance, donkeyswings.py is a complete filename where the given name is donkeyswings and the extension is .py.
Inside code, filenames are always strings.
  1. Description
  2. Conversions
Floating point number or float is an approximation for decimal numbers used by computers. Computers can't handle real decimal numbers due to their architecture, and that leaves us with floats. Floats can occasionally cause rounding errors - something to keep in mind. Python has a module for handling decimal numbers more accurately, called decimal.
  1. Description
  2. Examples
  3. Choosing parameters
The format method of strings is a powerful way in Python to insert values of variables into text that is either printed or saved to a file. Formatting works by defining placeholders in strings (e.g. {:.2f}) for marking spots where the format method arguments will be placed. Example: "Interval between donkey's ears is {:.2f}".format(measurement).
Note: format is an older way for general string formatting. Using f strings is a more modern way. However, there are still uses for the good old format method too.
  1. Description
  2. Examples
Function is an independent part of a program that consists of the defining line (with the def statement) and the lines of code that defines the function's behavior. Functions are used to clarify program structure and to reduce redundancy. Functions communicate with each other and the main program through their parameters and return values. Variables (including parameters) defined inside a function cannot be accessed from outside the function. Likewise functions should not read values outside of their own scope.
  1. Description
  2. Examples
Function call is a procedure where the program's execution "jumps" to another location in the code - to the beginning of the function that is being called. When a function is called it is given a varying number of arguments - values that are assigned to parameters defined in corresponding positions in the function definition. A function's execution ends when a return statement is encountered or there are no more lines inside the function's code to execute. When this happens, the program's execution returns to the line where the function was called, and the function call itself is "replaced" by the function's return value.
In short function calls allow one part of the program to utilize another part - e.g. the main program can use a function, or a function can use another function.
  1. Description
  2. Examples
Functions are defined with the def statement which specifies the name of the function and the names its parameters. Choosing these is an essential part of writing generally useful functions. The name should describe what the function does accurately but shortly. Parameter names should be chosen so that it's easy to deduce what kinds of values they will take as arguments. The function's code is indented inside the def statement as its own block. A function code can - and often does - include multiple lines. It can also include further indentations (like control structures).
  1. Description
  2. Examples
Generator is a special type of object that works like a list in, for example, a for loop. However, it's not a series of values in memory like a list would be, but a special function that produces values in a lazy way, yielding a new one whenever it is called. Because of this it's not possible to show the "contents" of a generator, and it's not subscribable with indices. Generators are not included in beginner level courses.
  1. Description
  2. Esimerkit
  3. Tilasanakirjat
Globaali muuttuja (engl. global variable) on pääohjelman tasolla esitelty muuttuja, jota muokataan suoraan funktiossa tuomatta sitä funktion nimiavaruuteen parametrin kautta. Globaalien muuttujien käyttö on huonoa ohjelmointityyliä, ja niiden sijaan tietoa kuuluisikin kuljettaa funktioille argumentteina ja ottaa funktiolta vastaan paluuarvoina muutettuja arvoja. Näin tekemällä välttää niin kutsutun globaalin tilan, joka huonontaa koodin ymmärrettävyyttä.
Global scope encompasses all names (variables, functions etc.) that have been defined on the main program level. All names that belong to the global scope can be accessed from anywhere in the program code. However they can only be assigned new values in the main program level. In general functions should only use constants and other functions from the global scope. Main program variables should always be passed to functions through parameters.
A handler function is a function that has been connected to an event so that when the event occurs, the function is called. This often means that the handler is not called from within the same code file or module it was defined in, and instead it works as a callback. Handlers are often related to user interface and game libraries where the program's main loop is running inside the library and monitors events. In this scenario handlers are the actual application's means of implementing their functionality through events. Because the application's writer cannot influence how handlers are called, handler parameters and return values must match the requirements set by the library.
  1. Description
  2. Esimerkit
Hypystä (engl. jump) puhuttaessa tarkoitetaan ohjausrakenteen aiheuttamaa siirtymistä, jonka jälkeen ohjelman suoritus jatkuukin jostain muualta kuin seuraavalta koodiriviltä.
  1. Description
  2. Naming Conventions
Variables, functions, constants, modules and all kinds of things each have their own 'identifier - the part of the source code that's been assigned to mean that one particular thing. For instace if a programmer defines a variable width with the value 15 the name width can later be used to retrieve the variable's value. So the identifier can be thought of as a contract between the programmer and the Python interpreter about the meaning of a certain word in the code. Identifiers always belong to a namespace.
Indented code lines have blank characters in front of them, either spaces or tabs. The role of indentation in general is to organize code and improve its readability. However in Python indentation is also used as the syntax for separating code blocks from each other - all lines with the same indentation level belong to the same block. On this course we prefer spaces, and the width of one indentation level is 4 spaces. All reasonable text editors can be configured to insert spaces instead of the tab character when the tab key is pressed.
  1. Description
  2. Example
Index is an integer value that denotes the position of an item in an ordered collection (list, tuple, but also string!). Indices start from zero which makes the last index (collection length - 1). Index can also be thought of as distance from the beginning of the colection. Python supports negative indices where -1 points to the last item, -2 to second to last etc. Using an index to get an item from a collection is called subscription.
  1. Description
  2. Examples
When the index of a data structure, e.g. list, is used the act itself is called (index) subscription. The subscription is denoted with square braces, e.g. grades[0]. Subscription returns an item. Subscription outside the list causes an IndexError exception, and it's good to keep in mind that the last index of a list is its length - 1 (because indexing starts from zero). Index can also be negative - in this case counting starts from the end so that -1 is the last item of the list.
  1. Description
  2. Example
An infinite loop is a loop that does not have an end condition - the code inside it gets repeated "infinitely". Infinite loops do have uses in programming but they can also be caused unintentionally by a bug in the code. In Python infinite loops are usually "achieved" only by while loops.
  1. Description
  2. Examples
Input when used within the context of this course is a text-based command or answer to a question that's been requested from the program's user. It is prompted with the input function and will always be a string. When a program prompts for input the entire program stops until the user has given their input.
  1. Description
  2. Examples
Interface in general refers to a connection between two things, and in programming it particularly means the way in which two parts of a program are connected to each other. For instance we can talk about the interface of a function which refers to the way in which the function accepts information as parameters and returns information as its return value. Likewise libraries typically have an API (Application Programming Interface) that tells how the library's features are used. Humans are also connected to programs through interfaces, specifically user interfaces.
  1. Description
  2. Examples
Item or element is an individual value contained within a data structure. The term is most commonly used in the context of lists. In this context, items also have a position, index, that denotes its distance from the beginning of the list. Therefore the index of the first item in a list is 0.
Iteration is a concept related to loops. One iteration of a loop means executing the code inside the loop once.
  1. Description
  2. Examples
Key acts as an index for a dictionary. It can be used to look up a value from the dictionary. Each key corresponds to exactly one value. Keys are typically strings, but they can also be any immutable types like numbers or tuples.
  1. Description
  2. Examples
Keyword argument (kwarg) is used in function and method calls to assign arguments directly to parameter names. This is very often used with the format method: "Hello {name}".format(name="Hagrid"). Another common use case is with functions that have a whole lot of optional arguments and only some of them need to be given. Using keyword arguments can also make the code generally more readable, especially for arguments that are either True or False.
Kirjasto (engl. library) tai moduuli (engl. module) (kuten niitä Pythonissa virallisesti kutsutaan) on valmiiksi kirjoitettua koodia, jolla on oma rajattu tarkoituksensa. Tyypillisesti kirjasto sisältää ainakin nipun aihepiiriinsä kuuluvia funktioita, mutta voi sisältää muutakin (esim. luokkia tai vakioita). Esimerkiksi Turtle on kirjasto, jonka tarkoitus on tarjota helposti käytettäviä piirtofunktioita.
  1. Description
  2. Esimerkit
Kommentti (engl. comment) on kooditiedostossa olevaa tekstiä, joka ohitetaan kun koodia suoritetaan. Kussakin kielessä on oma tapansa sille miten rivi merkitään kommentiksi. Pythonissa se on #- eli risuaitamerkki (engl. hash character), jonka jälkeen riviltä löytyvän tekstin Python-tulkki ohittaa kokonaan. Kommenteilla voi selventää koodin lukijalle (tai itselleen) mitä koodissa tapahtuu. Yleensä kommentit on hyvä laittaa omille riveilleen kommentoitavan koodin yläpuolelle.
Ohjelman ja sen funktioiden toiminta kuvataan yleensä mieluiten dokumenttimerkkijonossa. Kommentteja käytetään enemmänkin välihuomioiden tekemiseen.
Toinen tapa käyttää kommentteja on tilapäisesti kommentoida rivejä pois esimerkiksi vaihtoehtoisen koodin testaamiseksi. Tällöin aiempaa koodia ei tarvitse poistaa – kätevää, jos myöhemmin osoittautuu, että sitä tarvitaan sittenkin.
Ohjelman käyttämät arvot ovat kovakoodattuja (engl. hard coded) silloin, kun ne esiintyvät literaaliarvoina – eli semmoisenaan – ohjelman lähdekoodissa sen sijaan, että ne selvitettäisiin ajonaikaisesti esimerkiksi kysymällä käyttäjältä tai lukemalla tiedostosta.
Käyttöliittymäelementti (engl. UI element, widget) on jokin (yleensä graafiselle) käyttöliittymälle ominainen komponentti, jonka kautta käyttäjän vuorovaikutus ohjelman kanssa on mahdollista. Tällaisia ovat esimerkiksi napit, valikot, liukusäätimet ynnä muut.
Lause (engl. statement) on ohjelmointikielessä nimitys yksittäiselle suoritettavalle asialle, joka on yleensä yksi koodirivi.
Lauseke (engl. expression) tarkoittaa ohjelmoinnissa evaluoitavaa yksikköä. Esimerkiksi 5 + 5 ja "aasi" != "apina" ovat lausekkeita, jotka evaluoituvat arvoiksi 10 ja True. Lauseke yksin ei muuta ohjelman tilaa mitenkään, ellei sillä ole sivuvaikutuksia. Sen sijaan lauseke vaikuttaa osana lausetta.
  1. Description
  2. Examples
List is an ordered collection of values, and in Python it's a true swiss army knife. A list can contain values of any types, and its size is not limited.
Values inside a list are called items or elements. Each item has its own designated spot inside the list, called index. Indices start from zero! In addition, list is a mutable type. The third material contains a lot of information about lists.
A list can also contain other lists. Such a construct can also be called a two-dimensional list. Of course it's possible to have more than two levels of nested lists, which increases the number of dimensions. These would be called multidimensional lists.
Literal (literal value) is a generic name for any values that are present in the code as such. I.e. the value is not assigned to a variable but has been written into the code itself. For instance in the statements x = 5 and print("donkey"), 5 and "donkey" respectively are literals. The term is used primarily for simple types: numbers, boolean values and strings.
Local variable is a variable that has been defined inside a limited scope, typically - and especially on this course - inside a function (including function parameters). A local variable cannot be accessed from the outside. In addition it gets destroyed when the scope it belongs in stops being relevant - usually when a function call ends.
Loop is a control structure that repeats the instructions contained within it either a certain number of times or until some condition is no longer met. Loops can be used to return program execution to a previous point, and they can also be used for processing large number of values. Python has two kinds of loops: for and while.
Loop Variable is a variable that's introduced in for loop declaration. This variable will receive each value in the sequence (e.g. list) that is being iterated over in the loop. Its value changes on each iteration. A simple example from the material: for animal in animals: where animal is the loop variable. If the sequence contains tuples (or lists), a for loop can also have multiple loop variables: for student, grade in grading:. Loop variables are not inside their own scope and must therefore be distinct from other names inside the same function's scope.
Main program is the part of the code where the real execution of the program starts. As a rule of thumb any statements and control structures that are attached to the left boundary are part of the main program. Main program is usually at the very end of a code file and usually inside if __name__ == "__main__": statement. However do not use this statement in the earlier exercises because then the checker cannot execute your program's main program.
Merkillä (engl. character) tarkoitetaan ohjelmoinnissa yksittäistä datana esiintyvää kirjainta, numeroa, välimerkkiä tai muuta vastaavaa symbolia. Pythonissa merkki edustaa pienintä merkkijonon yksittäistä palasta.
  1. Description
  2. Esimerkit
Merkkijono (engl. string) on tietotyyppi, joka sisältää tekstiä. Sitä käytetään erityisesti käyttäjän kanssa viestimiseen. Merkkijonojen sisältöä voidaan myös tallentaa tiedostoihin. Pythonissa merkkijono merkitään lainaus- tai heittomerkillä (esimerkiksi "aasi" tai 'aasi'). Suosimme ensimmäistä. Merkkijono voidaan merkitä myös kolmella merkillä jolloin se voi olla monirivinen – tätä käytetään erityisesti dokumenttimerkkijonojen (docstring) kanssa. Merkkijono on muuntumaton tietotyyppi – kaikki, mikä näennäisesti muokkaa merkkijonoa, tosiasiassa luo (ja palauttaa) siitä muutetun kopion.
  1. Description
  2. Examples
Method is a function that belongs to an object, i.e. it's one of the object's attributes. Methods are often used by objects to change their own state somehow, or derive another value from themselves. When a method is called it is prefixed with the object that ownds it: choice.lower(). Methods are occasionally called "member functions" as well.
Method Call is a similar process to function calls. As a significant different the target object is defined by prefixing method name with it whereas it would be given as an argument in a function call. In a typical method call an object operates on itself. For instance word.upper() is a method call that operates on the object referred to by the word variable.
Module is basically any Python code file. Although more commonly module is used as a synonym for library. Typically a module contains functions and potentially other (like constants and classes) things that are connected to a certain domain or use case. Large programs are also often split into modules so that each module focuses on one aspect of the program.
  1. Description
  2. Examples
Python objects can be divided into two types: mutable and immutable. Mutable objects can have their values changed during program execution e.g. as the result as a method call. The most common example of a mutable object is a list: hogwarts.append("Hufflepuff") changes a list named hogwarts by adding a new value to it. Any references to this list later in the program will access the contents that now include "Hufflepuff".
  1. Description
  2. Esimerkit
Pythonissa objektit erotellaan muuntuviin ja muuntumattomiin. Muuntumaton (engl. immutable) arvo on sellainen, jonka sisältö ei voi muuttua - kaikki operaatiot jotka näennäisesti muuttavat arvoa tosiasiassa luovat siitä uuden kopion, joka yleensä sijaitsee uudessa muistipaikassa. Esimerkiksi merkkijonot ovat tyypillinen muuntumaton tyyppi Pythonissa. Siksi merkkijonojen kanssa näkee yleensä jotain tällaista: valinta = valinta.lower()
Ohjelmointikielissä on oleellista ymmärtää määrittelyn (engl. definition) ero suorittamiseen. Määrittelemällä luodaan kuvauksia funktioista, muuttujista ja erilaisista tietorakenteista – tavallaan siis kerrotaan ohjelmointikieltä käyttäen, minkälainen jokin edellä mainituista asioista on, tai mitä sen kuuluisi tehdä. Pythonissa määrittelyn ja suorittamisen ero on helpoin ymmärtää funktioiden avulla. Funktiomäärittelyssä funktio vasta luodaan – ikään kuin tehtaalla koottu laite. Funktiota varsinaisesti käytetään – eli sen toiminnallisuus hyödynnetään funktiota varten määriteltyä koodia ajamalla – vasta funktiokutsun yhteydessä. Samaa vertausta käyttäen funktiokutsu vastaa siis sitä hetkeä, kun tehtaalta saapunut laite käynnistetään.
Nimikonflikti syntyy, jos useammalle kuin yhdelle arvolle koitetaan antaa sama nimi. Tällöin tapahtuu niin, että tuoreempi sijoitus jåä voimaan. Tästä seuraa yleensä ohjelman kaatavia virheitä, koska usein arvot ovat eri tyyppiä. Voi jopa käydä niin, että epämääräisesti nimetyn funktion päälle tallennetaan vahingossa saman niminen muuttuja.
Namespace is a group of names (variables, functions, constants etc.) that belong to the same context. For example the names inside a function (inside the function definition code block) form their own namespace: names inside the function are only accessible from within. There's also a global namespace which is the main program's namespace. Using normal import in a program creates a new namespace within that program that is accessible through the module's imported name - the names inside the module form their own namespace. See also: Scope.
Newline (line break, end of line, EOL), the "\n" character is a character that, when printed or written to a file produced a line break. If a string is inspected without printing it e.g. in the console, all line breaks are shown as "\n" characters.
  1. Description
  2. Esimerkit
Nimeämätön vakio tai taikaluku (engl. magic number) on koodissa esiintyvä literaaliarvo, jota ei selitetä millään tavalla. Hyvään ohjelmointityyliin kuuluu taikalukujen välttäminen. Oikea – itsedokumentoiva – tapa on nimetä koodissa esiintyvät vakiot muuttujiin, jolloin niiden muuttaminen onnistuu tarpeen tullen yhdestä paikasta yhdellä muutoksella, ja koodin lukijan on helpompi ymmärtää koodia.
  1. Description
  2. Syventävää nippelitietoa
Näppäimistökeskeytyksellä (engl. keyboard interruption) voi pakottaa jumiin jääneen ohjelman sammumaan. Sen saa aikaan painamalla Ctrl+C sen terminaalin ollessa auki, jossa ohjelma pyörii. Pythonissa näppäimistökeskeytyksen saa käsiteltyä kaappaamalla KeyboardInterrupt-poikkeuksen try-except-rakenteella.
Objekti (engl. object), joskus myös olio, on Pythonissa yleistä terminologiaa. Kutsumme objekteja pääasiassa arvoiksi alkeiskurssilla, mutta Pythonissa kaikkea voi käsitellä objekteina. Tämä tarkoittaa, että mihin tahansa voidaan viitata muuttujilla (esimerkiksi funktion voi sijoittaa muuttujaan). Tämän kurssin puitteissa objekti-termiä käytetään sellaisista arvoista joilla on metodeja.
Objektit nousevat merkittävämpään rooliin alkeista eteenpäin, erityisesti koodissa jossa käytetään luokkia.
Ohjelmointityyli (engl. programming style) on joukko ohjeita tai tapoja, joita ohjelmoija noudattaa koodia kirjoittaessaan. Näihin tapoihin lasketaan muun muassa sisennyksen syvyys, muuttujien ja funktioiden nimeämiskäytännöt, välilyöntien käyttö lauseissa sekä monet muut tyyliseikat. Ohjelmointityylejä on useita erilaisia, ja tällä kurssilla opetetaan noudattamaan tiettyjä tyyliin liittyviä sääntöjä.
Ominaisuus (attribute) liittyy objekteihin siten, että objekteilla voidaan sanoa olevan ominaisuuksia. Tällä kurssilla useimmat näistä ominaisuuksista ovat metodeja, mutta ne voivat olla myös arvoja. Objektin ominaisuutta käsitellään notaatiolla, jossa objektin nimen ja ominaisuuden nimen väliin tulee piste, esim: valinta.lower()-metodikutsussa valinta on objekti ja lower on ominaisuus.
  1. Description
  2. Examples
Opening mode is used for telling Python (and the operating system) how to open a file. A file can be opened for reading or writing. By default, if opening mode is not given, a file will be opened in reading mode "r". There are two writing modes:
  • "w", write, which overwrites anything that may have been in the file previously with the new content.
  • "a", append, which writes the contents to the end of an existing file instead
Both writing modes create the file if it did not exist previously.
Operand is the fancy name used in mathematics and programming for values that are used in an operation. E.g. 5 + 8 is an addition operation and its operands are 5 and 8. Operands can be thought of as the subjects of operations.
  1. Description
  2. Examples
Operation is a term used for anything carried out by an operator in the code. Mathematical operations are typical examples. An operation consists of an operator and one or two operands. For instance 5 + 5 is an operation.
Operator is a name for symbols that define an operation in mathematics and programming. Operators always appear with at least one operand, but often two. An example of an operator would be + symbol which denotes an addition operation.
An argument in a function call is an optional argument if its corresponding parameter has been given a default value. This means that it's possible to call the function without giving that argument. If there are multiple optional arguments for a function, they are often given using keyword arguments.
Parameter is a variable defined along with a function. They are variables that are assigned values from arguments when the function is called. In other words when values are transferred in a function call, they are called parameters from the function's point of view. E.g. in def prompt_input(question, error_msg): question and error_msg would be parameters. Parameters can also have a default value that will be used as its value if the matching argument is not given in a function call - this makes the argument optional.
Parametrization means expanding the use cases of a process by turning some of its values into variables. This way the same process can be repeated for multiple sets of values with different results. Mathematical functions are one kind of parametrization: all points represented by the function are produced by changing the value of a variable (e.g. x). In programming parametrization is quite concrete because usually a procedure is turned into a function. The function's parameters then define which values are not fixed and the function will behave differently with different parameters.
  1. Description
  2. Examples
Path is the location of a file or folder on the hard drive. A path can be absolute or relative. Absolute path includes every folder from the target all the to the root (e.g. in Windows the root is the drive letter, like C:) whereas relative only includes folders up to the active folder (i.e. the folder where the program was started in). Path is usually presented in programming languages as a string, and path parts are separated with slashes /. When forming path inside code, it's best to use the join function from the os.path module.
  1. Description
  2. Additional formatting
Placeholder is by general definition a way to mark a spot that will be replaced by something else later. In this course they are primarily used with string formatting. A placeholder within an formatting string is marked with curly braces (f"Hi {name}"). Placeholders in strings can also contain additional formatting specifiers like setting the number of decimals to show (f"Donkeys have {average:.2f} legs on average"). When a placeholder is resolved, it is replaced by the value of the variable or statement inside the curly braces.
  1. Description
  2. try-except-else-finally
Poikkeusten käsittely (engl. exception handling) on ohjelmointikieleen sisäänrakennettu keino ohjelmoijalle reagoida poikkeuksiin. Pythonissa poikkeusten käsittely onnistuu try-except-rakenteella, jossa sekä try: että except: aloittavat omat lohkonsa; try-lohkon alle kirjoitetaan se koodi, joka mahdollisesti aiheuttaa jonkun tietyn poikkeuksen ja except-lohkon alle taas se koodi, joka suoritetaan siinä tapauksessa, että kyseinen poikkeus tapahtuu. Joissain muissa ohjelmointikielissä except-avainsanan sijaan käytetään avainsanaa catch, minkä takia yleisesti puhutaan poikkeusten kiinni ottamisesta.
Precedence, of math fame, defines in which order various operations in a statement are resolved.
result = 10 + 2 * (2 + 3)
The result of this statement is 20 because the sum of 2 and 3 is resolved first, followed by multiplying the result by 2, and finally adding the multiplication result to 10. In this example the highest precedence is held by the operation in braces, followed by multiplication, and then finally addition.
Precedence defines the execution order of instructions or operations on a line of code. Operations of different type have different precedence in execution order. These can be found from the link below. Operations with same precedence are executed from left to right. Like in mathematics, the order can be changed by using parentheses.
  1. Description
  2. Examples
Printing is somewhat different in programming context - although not really that far removed - from combining paper and ink to pages. In context of computer programs it usually means producing text on the screen, especially to a terminal. Python has a function for this purpose: print(...) that prints its argument(s) to the terminal.
Programming problem is the goal of a programming task. It is therefore some sort of a need that has been recognized and a program is coded to fulfill that need. The need can be e.g. automatization of a task, creating a web site or just making a fun game.
  1. Description
  2. Examples
Interactive Python interpreter or Python console as we like to call it is a program that executes Python code lines as they are written into it. It shows the return value of the line if any exists (e.g. the result of a mathematical operation). On this course we use IPython instead of the vanilla Python console. After installation you can start IPython by typing ipython to the terminal.
Python interpretetr is a program that transforms Python code into instructions to the computer's processor. It's responsible for executing both code files and individual lines in the Python console. The word can also be used to mean Python console though, so be careful.
  1. Description
  2. Examples
Recursion is a common programming term that refers to a function calling itself. Recursion is a function-based way to create repetition in the code where the function gives itself new arguments and handles its own return values. Recursion is handy e.g. when navigating tree-like structures - one "branch" is handled at a time, and then recursion is used to handle branches branching out from that branch, and so on. Recursion is not very widely used in Python. One reason is the recursion depth limit which restricts how many times a function can call itself.
Referring is the method in which a variable is connected to its value. The target of the reference is the computer's memory and the variable itself - under the hood - contains an address where from memory the value can be found.
Relative path is an operating system concept that indicates the path to a file or folder from the current folder. Relative paths do not care what kind of a garden maze of folders exists between the disk drive root and the current path. For this reason relative paths are usually used to refer to a program's own sub folders. This allows the program to be moved to another location without updating any paths in the code.
  1. Description
  2. Examples
Return is a process that happens when a function's execution ends. Typically the value(s) returned by the function are defined inside the function with a return statement. In the code that calls the function, the return value will replace the function call and can therefore be assigned to a variable or passed on to another function.
Return value is the value (or values) that a function returns when its execution ends - the function's result. Functions in Python can have multiple return values. When reading code you can regard return value as something that will replace the function call when the function execution has ended. A return value is defined inside a function with the return statement. E.g. in return True there is one return value: the literal boolean value True.
Sapluuna (engl. template) on muotti esimerkiksi tekstille, joka käyttäjälle halutaan näyttää, mutta joka ei semmoisenaan ole vielä valmis. Sapluunasta siis puuttuu tietoa, joka on tarkoitus saada sapluunan paikanpitimien tilalle.
Kurssilla yleisin sapluuna on merkkijono, jossa on paikanpitimiä format-metodia varten.
  1. Description
  2. Examples
Scope is a concept related to the visibility of names (variable, function etc.) in certain parts of the program. For instance within a function block any names defined inside the function can be used because they belong to the same scope. Other functions cannot access these names because they belong to a different scope. Names in the global (main program) scope can be accessed from anywhere in the code.
  1. Description
  2. Examples
Separator is a term related to strings and text files. It means a specific character that is meant for indicating a split inside a string when it is read into the program. For instance, if a string contains values that will be parsed into a list, the separator is the character than indicates where one part ends and the next one begins. The split method is often used in these situations - the method can use a specific separator to split a string into a list.
A sequence is any value in Python that is a series of things - for instance, string, list and tuple are all sequences.
  1. Description
  2. Examples
Slicing is the act of taking a new sub-sequence out from an existing sequence (usually list, but sometimes also string). The result of slicing is a value with the same type that's a copy of the selected part in the original sequence. The selection is done by choosing start and end indices. Both are optional. A slice is written as follows: page = collection[5:10] - this would make a slice including indices 5...9. The number on the right side of the colon in a slice is the first index that is not included in the result!
Slicing never causes an IndexError.
Solution model is an abstract construct developed by a programmer regarding how the solution to a programming problem works. It's not code yet, but it should be explicit and dividable into distinctive steps so that it can be turned into a program. Solution models can be sketched inside one's mind, by using paper and by trying this out in the Python console.
Source code or code means text that has been written with a programming language.
State, as the name suggets, referes to the program's current state. In practice state covers everything belonging to the program's state space like variable values, data in files, and where the code execution is currently at. A guaranteed way to make spaghetti code that's beyond repair is to use the global state - a crime that's perpetrated by functions that use global variables.
Later, on courses that go more formally into programming concepts, you'll learn of things like state machines, as well as stateless and stateful programs.
  1. Description
  2. Examples
Stub function is a function that's been defined properly with all the parameters etc. but has no content in it. They are typically put into the program code when planning its overall structure. Doing so allows the functions to be called elsewhere in the code while the function isn't fully implemented yet. The contents of a stub function usually come down to just pass, an informative print, or returning some placeholder default value. In larger projects stub functions sometimes are set to raise a NotImplementedError exception which makes it easy to locate the function that's not ready yet.
Syntax is the grammar of code. It defines what kind of text counts as valid Python. If code doesn't conform to the correct syntax, it cannot be executed. Syntax also informs a programmer about the correct formatting for each stement in the programming language.
Syntax error is an exception that happens when the Python interpreter inspects a code file before executing it and notices something broken in there, i.e. code that is written incorrectly. A code with syntax errors is not run at all.
One common syntax error is unbalanced parentheses. This results in a strange error message in the sense that Python reports the next line as the cause of the error. Remember to check previous lines as well when you receive strange syntax errors!
Takaisinkutsu (engl. callback) on yleinen ohjelmoinnissa käytetty menetelmä, jossa funktio ottaa parametrin kautta vastaan funktion kutsuttavakseen heti (synkroniset takaisinkutsut) tai joskus tulevaisuudessa (asynkroniset takaisinkutsut). Nimensä menetelmä on saanut soittopyynnöstä: kutsuttavaa funktiota, jolle jokin funktio välitetään argumenttina, ”pyydetään” kutsumaan tätä annettua funktiota. Pythonissa listojen sort()-metodin key-parametri on esimerkki callback-funktioiden käytöstä. Usein käyttöliittymiä toteutettaessa käyttöliittymäelementteihin kytketään callback-funktioita.
Terminal, command line, command prompt and shell' are different names to the text based interace of an operating system. It is used for text-based operating system commands and for running terminal programs. On this course we mostly move around with cd (change directory) and use ipython command to run code files and start the Python console.
  • In Windows you can open the terminal by typing cmd to the start menu search
  • In Mac OS X you can start the terminal by typing terminal to Finder
  • In Linux you can open the terminal from the desktop by pressing Ctrl + Alt + T or by typing terminal to the search
Testaamalla eli kokeilemalla (engl. test) selvitetään, toimivatko hartaasti näppäillyt koodirivit halutulla tavalla. Testejä suorittamalla siis etsitään koodista mahdollisia ohjelmointivirheitä. Ohjelmien testaaminen on jopa niin olennaista, että joidenkin alan työntekijöiden tehtävänä on ainoastaan automatisoitujen testien ohjelmointi. Lovelace-järjestelmän tarkistimet testaavat järjestelmään lähetetyt koodit.
Generally text file is any file that can be read with a text editor. In this course's context we use text file to refer to files that are handled as text inside Python. We do this to separate them from code files that are run with Python. Text files are used in this course to store data between runs of the program.
Tosi (engl. true) on toinen kahdesta mahdollisesta totuusarvosta ja toisen, eli epätoden, vastakohta. Sitä voidaan pitää lopputuloksena loogisissa ja vertailuoperaatorioissa, jotka pitävät paikkansa. Esimerkiksi vertailuoperaatio 5 > 4 pitää paikkansa, joten kyseinen operaatio evaluoituu todeksi. Pythonissa totta merkitään avainsanalla True.
  1. Description
  2. Esimerkit
Traceback is the process of tracing an error back to its source. When an exception occurs the Python interpreter prints an error message that includes a traceback. It's presented as a stack of function calls where the last one is the funtion where the exception occurred. They are also called stacktrace for this reason. For example if the main program calls the funcion f which in turn calls function g where the exception occurs, the stack would be
main programfg.
  1. Description
  2. Examples
Tuple is a co-called frozen list. It's an ordered collection of values like a list but it's an immutable object. A tuple can't be changed. They can only be created, and read. Usually a tuple is delimited with normal braces: "#!python3 (1, 2, 3) but actually this is a tuple even without them: 1, 2, 3.
Unlike lists, tuples can be used as dictionary keys.
  1. Description
  2. Examples
Type conversion (also type casting and type coercion) means changing the type of a variable or literal value to another one. In Python this is commonly done when a number is requested from the user and it is returned as a string. In practice this can be done with e.g. int("123") or float("3.14"). In some cases Python performs type conversion automatically, usually when mathing with floats and integers.
Tyylisäännöt ovat kokoelma suosituksia, joiden mukaan koodia tulisi kirjoittaa. Kullakin kielellä on yleensä omansa. Tyylisääntöjen rikkominen ei varsinaisesti riko ohjelmaa, mutta tyylisääntöjen mukainen koodi on miellyttävämpää lukea ja usein tästä johtuen myös helpompi korjata. Tällä kurssilla seurataan Pythonin virallista tyylistandardia erityisesti tekstikenttätehtävissä. Myös tiedostotehtävissä on koodin laadun tarkistus, jossa käytetään PyLint-ohjelmaa.
  1. Description
  2. Esimerkit
Tyyppi (engl. type) on arvon ominaisuus – jokainen arvo edustaa aina jotain tiettyä tyyppiä. Tyypin tarkoitus on siis kertoa, minkälaisesta arvosta on kyse. Käytännössä tästä seuraa myös se, mitä operaatioita arvoilla voi tehdä, ja mitä metodeja niiltä löytyy. Funktiot on myös miltei aina toteutettu siten, että niille syötettävien argumenttien täytyy olla tietyntyyppisiä, jotta funktio voisi toimia. Tyypit ovat yksi ohjelmoinnin keskeisimmistä käsitteistä.
Pythonissa arvojen sopiminen koodista löytyviin operaatioihin tarkistetaan tilannekohtaisesti näiden arvon ominaisuuksien perusteella – ei siis suoraan itse tyyppiä tarkastamalla. Esimerkiksi useimmissa tapauksissa kokonaisluku ja liukuluku kelpaavat molemmat, mutta on myös tapauksia, joissa näin ei ole (esimerkiksi merkkijonoa ei voi kertoa liukuluvulla).
Tällä kurssilla tyypillisiä tyyppejä ovat kokonaisluku (int), liukuluku (float), merkkijono (str), lista (list), totuusarvo (bool) ja monikko (tuple). Myös funktioilla on oma tyyppinsä!
User Interface (UI) is the interface between a program and its user (typically human). In a simple text based UI input function calls are used to prompt things from the user and print calls can be used to display instructions and results.
Many programs intended for end users (consumers) typically offer a graphical user interface (GUI). These typically involve icons, popup menus and other elements that can be poked with by mouse or touch screen. On this course we will take a very shallow stab at graphical user interfaces in the final project.
A simplified way to describe variable is to think of it as an information storage - it contains something. This expression is often used in speech even though it's not entirely accurate. The more accurate description is that a Python variable is a reference to a value. It's a connection between the variable's human-readable name and a value that's stored in the computer's memory. So the variable in fact doesn't contain the value, it just contains information about where it is.
  1. Description
  2. Examples
The break keyword is a special instruction that is used in loops. It interrupts the loop's execution immediately, and code execution continues from the first line after the loop. If the loop had an else branch, it is not entered.
  1. Description
  2. Examples
continue is the other keyword related to loops (the first one being break). Unlike break which interrupts the entire loop, continue only interrupts the current iteration - execution continues from the next iteration. Note that this keyword is only needed in situations where part of the iteration is to be skipped. There's no need to put continue to the end of the loop iteration.
  1. Description
  2. Examples
enumerate is builtin function that produces a generator-like object in Python. Its primary use is in for loops when the code needs to access the items' indices in addition to the items themselves. The enumerate object produces tuples where the first item is the original item's index and the second item is the original item itself. Use example: for i, character in enumerate(moomin_valley):.
f(ormat) string is a special string that is used for inserting values from variables or simple clauses inside a piece of text. This is also called string interpolation in programming terminology. This kind of a string is marked by prefixing it with a lowercase f. You can include placeholders inside the string by using curly braces, and writing variable names or clauses inside them.
Example: f"Interval between donkey's ears is {measurement:.2f} inches" (assuming that a variable named measurement has been definied previously)
  1. Description
  2. Examples
In Python for is one of the two loop types. It's designated for iterating through data structures. It is used especially with lists. In general, for loops are used when it's possible to determine in advance how many iterations the loop must do. In addition to iterating through structures, for loop is therefore used for doing a certain number of iterations (e.g. 10 iterations). For loop declarion looks like for item in collection: where item would be the name of the loop variable, and collection would be the data structure that is being iterated over.
  1. Description
  2. Examples
In Python modules are "activated" by import statements. In normal use (e.g. import math) the statement makes a new namespace accessible through the module name. Functions from the imported module can be accessed through its name. It's also possible to directly import some specific names from a module with a from-import statement: from math import ceil. Modules can also be renamed on import: import math as m.
  1. Description
  2. Esimerkit
Silmukoista while pohjautuu toistoon ehdon tarkastelun kautta - silmukan sisällä olevaa koodilohkoa suoritetaan niin kauan kuin silmukalle annettu ehto on tosi. Ehto määritetään samalla tavalla kuin ehtolauseissa, esim: while summa < 21. While-silmukat soveltuvat parhaiten sellaisiin tilanteisiin, joissa ei voida etukäteen selvittää montako toistoa tarvitaan - erityisesti syötteiden kysyminen käyttäjältä on tällainen tilanne.
  1. Description
  2. Examples
In Python with is a somewhat exception keyword in that it's not a control flow structure or definition of a new thing. On this course it's primarily used when opening files, e.g. with open("donkey.txt") as somefile:. All read or write operations on the file are carried out inside the with statement. When the with statement ends, Python automatically takes care of closing files opened in the with statement.