Termbank
  1. A
    1. Absolute Path
    2. Ajonaikainen
      konseptit
    3. Alkio
      listat arvot
    4. Alustaminen
      muuttujat arvot
    5. Argumentti
      funktiot arvot
    6. Arvo
      arvot
    7. Assignment
      muuttujat arvot
    8. Assignment Operator
      muuttujat arvot operaattorit
    9. Attribute
      objektit
    10. Attribuutti
      Attribute
    11. Avainsana
      nimet
    12. Avausmoodi
      tiedostot
    13. Ajaminen
      Execution
    14. Aliohjelma
      Function
  2. B
    1. Boolean
      ohjausrakenteet tyypit
    2. Boolean Operator
      ohjausrakenteet
    3. Boolen operaattori
      Boolean Operator
    4. Branch
      ehtorakenteet try-rakenteet
    5. Builtin Function
      funktiot
    6. Bugi
      Ohjelmointivirhe
    7. break
      avainsanat toistorakenteet
  3. C
    1. Carriage return
      merkkijonot tiedostot pakeneminen windows
    2. Code Block
      funktiot ohjausrakenteet
    3. Code File
      konseptit
    4. Comparison Operator
      operaattorit ohjausrakenteet
    5. Condition
      ohjausrakenteet
    6. Conditional Statement
      ohjausrakenteet
    7. Conditional Structure
    8. Constant
      muuttujat arvot
    9. Ctrl + C
      Näppäimistökeskeytys
    10. Callback
      Takaisinkutsu
    11. continue
      avainsanat toistorakenteet
  4. D
    1. Data
    2. Data Structure
      konseptit listat sanakirjat
    3. Debugging
    4. Default Value
      funktiot arvot parametrit
    5. Dictionary
      tietorakenteet
    6. Dokumenttimerkkijono
      dokumentointi
  5. E
    1. Elementti
      Alkio
    2. Epätosi
      arvot
    3. Erotin
      merkkijonot listat tiedostot syöte
    4. Error Message
      ongelmanratkaisu
    5. Escape
      merkkijonot
    6. Evaluointi
      arvot lausekkeet
    7. Exception
      poikkeukset ohjaurakenteet
    8. Execution
      konseptit lausekkeet
    9. enumerate
      toistorakenteet listat
  6. F
    1. False
      Epätosi
    2. File Extension
      tiedostot
    3. Format
      merkkijonot tulostus
    4. Function
      funktiot
    5. Function Call
      funktiot lauseet
    6. Function Definition
    7. for
  7. G
    1. Generaattori
      objektit toistorakenteet
    2. Globaali muuttuja
      muuttujat arvot
    3. Global Scope
  8. H
    1. Hyppy
      ohjausrakenteet
    2. Hardkoodaus
      Kovakoodaus
  9. I
    1. if-lause
      Conditional Statement
    2. if-rakenne
      Conditional Structure
    3. Identifier
      muuttujat funktiot
    4. Indeksi
      listat arvot
    5. Indeksiosoitus
      listat arvot
    6. Indentation
      konseptit
    7. Infinite Loop
      toistorakenteet
    8. Input
      konseptit merkkijonot
    9. Interface
      konseptit funktiot moduulit
    10. import
      moduulit
  10. J
    1. Jäsenfunktio
      Metodi
  11. K
    1. Koodilohko
      Code Block
    2. Kutsu
      Function Call
    3. Key
      arvot sanakirjat
    4. Keyword Argument
      funktiot
    5. Kierros
      toistorakenteet
    6. Kirjasto
      moduulit
    7. Komentoriviargumentti
      terminaali
    8. Kommentti
      dokumentointi virheenetsintä
    9. Kovakoodaus
      arvot
    10. Kutsupyyntö
      funktiot
    11. Käsittelijä
      funktiot konseptit
    12. Käyttöliittymäelementti
    13. KeyboardInterrupt
      Näppäimistökeskeytys
    14. Koodi
      Source Code
    15. Komentorivi
      Terminal
    16. Komentokehote
      Terminal
    17. Kahva
      Tiedostokahva
  12. L
    1. Lause
      konseptit
    2. Lauseke
      konseptit
    3. Leikkaus
      listat
    4. Lista
    5. Literal
      arvot
    6. Liukuluku
      arvot tyypit
    7. Local Variable
  13. M
    1. Muotoilu
      Format
    2. Main Program
      konseptit
    3. Merkki
    4. Merkkijono
      arvot tyypit
    5. Method Call
      lausekkeet objektit
    6. Metodi
      objektit funktiot
    7. Module
    8. Monikko
      tietorakenteet listat
    9. Mutable
      konseptit listat arvot
    10. Muuntumaton
      konseptit merkkijonot arvot
    11. Määrittely
      konseptit
  14. N
    1. Name Conflict
    2. Namespace
      konseptit funktiot moduulit
    3. Nimeämätön vakio
      vakiot arvot
    4. Näppäimistökeskeytys
      poikkeukset
  15. O
    1. Objekti
      konseptit
    2. Olio
      Objekti
    3. Ohjausrakenne
      ehtorakenteet toistorakenteet try-rakenteet
    4. Ohjelmointityyli
    5. Ohjelmointivirhe
      ongelmanratkaisu
    6. Ominaisuus
      objektit
    7. Operand
    8. Operation
      lausekkeet
    9. Operator
    10. Optional Argument
      funktiot arvot parametrit
  16. P
    1. Paikanpidin
      merkkijonot tulostus
    2. Parameter
      funktiot
    3. Parametrization
    4. Poikkeus
      ongelmanratkaisu try-rakenteet
    5. Poikkeusten käsittely
      ohjausrakenteet poikkeukset
    6. Polku
    7. Precedence
    8. Printing
      konseptit merkkijonot
    9. Programming Problem
      ongelmanratkaisu
    10. Python Console
      työkalut
    11. Python Interpreter
      työkalut
    12. Presedenssi
      Sidontajärjestys
  17. R
    1. Referring
      muuttujat arvot objektit
    2. Rekursio
      funktiot konseptit
    3. Relative Path
    4. Return
      funktiot arvot
    5. Return Value
    6. Rivinvaihtomerkki
      merkkijonot tiedostot
  18. S
    1. Sapluuna
      merkkijonot konseptit
    2. Scope
      lohkot konseptit
    3. Sekvenssi
      tietorakenteet toistorakenteet konseptit
    4. Sidontajärjestys
      konseptit lausekkeet
    5. Suoritusjärjestys
      Sidontajärjestys
    6. Silmukkamuuttuja
      toistorakenteet muuttujat
    7. Solution Model
      ongelmanratkaisu
    8. Source Code
      konseptit
    9. Stub
      funktiot ongelmanratkaisu
    10. Syntaksi
      konseptit
    11. Syntax Error
      poikkeukset
    12. Silmukka
      Toistorakenne
    13. Stacktrace
      Traceback
  19. T
    1. Taikaluku
      Nimeämätön vakio
    2. try-rakenne
      Poikkeusten käsittely
    3. Takaisinkutsu
      funktiot
    4. Tallennusformaatti
      tiedostot merkkijonot
    5. Tapahtuma
      konseptit
    6. Tekstitiedosto
      tiedostot
    7. Terminal
      työkalut
    8. Testaaminen
      konseptit ongelmanratkaisu
    9. Tiedostokahva
      tiedostot objektit
    10. Tiedostonimi
      tiedostot merkkijonot
    11. Tila
      konseptit
    12. Toistorakenne
      ohjausrakenteet
    13. Tosi
      arvot
    14. True
      Tosi
    15. Traceback
      ongelmanratkaisu
    16. Type Conversion
      tyypit arvot funktiot
    17. Tyylisääntö
    18. Tyyppi
      arvot konseptit
  20. U
    1. User Interface
      konseptit
  21. V
    1. Variable
      konseptit arvot
    2. Vertailuarvo
  22. W
    1. while
      toistorakenteet
    2. with
      tiedostot
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 have been 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.
Desired Answer:
You need to submit three lines of Python code to the textbox below. These lines should:
  • 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)
Submit the lines in the given order
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
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.
Operaatio ja sen osat.
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
Desired answer:
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.
Desired Answer:
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
.
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.
Desired Answer:
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.
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
.
Desired Asnwer:
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.

Raiders of the Lost Function

Finding information from documentation pages is also an integral programming skill - of course we'll be practicing them on this course. Repeatedly.
Learning goals: Finding information from Python's documentation.
Introduction:
In this exercise you'll get to look at Python's builtin functions. Your task is to find a
function
that performs division with two numbers and returns two results: quotient and remainder.
Desired Answer:
Type function's name into the answer box below.
Write the name of the function here.
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.
Desired Answer:
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

height = 10
lid_radius = 2
print(calculate_volume(lid_radius, height))
print(calculate_area(lid_radius, height))
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))
Desired Answer:
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:
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.
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
.
Desired Answer:
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.
Desired Answer:
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.
Desired Answer:
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
Desired Answer:
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? "
Desired Answer:
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.
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:
Desired Answer:
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
Desired Answer:
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
Alkio (engl. item, element) on listan tai muun tietorakenteen sisältämä yksittäinen arvo. Useimmiten alkioista puhutaan juuri listojen yhteydessä. Tällöin alkiolla on arvon lisäksi paikka eli indeksi, joka kertoo sen sijainnin listassa etäisyytenä listan alusta. Niinpä siis listan ensimmäisen alkion indeksi on 0.
  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.
  1. Description
  2. Esimerkit
Avausmoodilla kerrotaan Pythonille (ja käyttöjärjestelmälle) millä tavalla tiedosto avataan. Tiedosto voidaan avata lukemista tai kirjoittamista varten. Oletuksena, eli jos avausmoodia ei erikseen määritellä, tiedosto avataan lukumoodissa ("r"). Kirjoitusmoodeja on kaksi:
  • "w", eli write, joka kirjoittaa tiedoston sisällön puhtaalta pöydältä hävittäen mahdollisesti aiemmin olemassa olleen saman nimisen tiedoston.
  • "a", eli append puolestaan kirjoittaa olemassaolevan tiedoston loppuun.
Molemmat kirjoitusmoodit luovat tiedoston, jos sitä ei vielä ole olemassa.
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.
Buitin functions are function that are included in the Python core. They can always be used without importing any modules or libraries.
Siinä missä UNIX-pohjaiset järjestelmät tuottavat \n-merkkejä rivinvaihdoiksi, Windows tuottaa \r\n-rivinvaihtoja, joissa r on carriage return -merkki. Se on kirjoituskoneiden peruja ja tarkoittaa toimenpidettä, jossa kirjoituspää siirretään takaisin rivin alkuun. Yleisesti ottaen tämä on lähinnä asia, joka on hyvä tietää – Python käsittelee molempia rivinvaihtoja kiltisti.
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.
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 !=
  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.
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 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.
Pythonissa dokumenttimerkkijono (engl. docstring) on kommentin kaltainen merkintä, mutta sillä on oma erityistarkoituksensa. Dokumenttimerkkijono merkitään yleensä kolmella lainausmerkillä (eli '''dokumentti''' tai """dokumentti""". Jos dokumenttimerkkijono on sijoitettu funktion def-rivin alapuolelle (sisennettynä), siitä tulee funktion dokumentaatio, jonka saa esiin help-funktiolla tulkissa. Samoin kooditiedoston alkuun sijoitettu dokumenttimerkkijono muuttuu moduuliin dokumentaatioksi. Dokumenttimerkkijonossa on hyvä kertoa funktion toimintaperiaate sekä selittää mitä sen parametrit ja paluuarvot ovat.
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. Esimerkit
Erotin (engl. separator) on merkkijonoihin ja tekstitiedostoihin liittyvä termi. Sillä tarkoitetaan tiettyä merkkiä, joiden kohdilta merkkijono on tarkoitus katkaista, kun se luetaan koodiin. Esimerkiksi, jos merkkijono sisältää tietoja, jotka on tarkoitus lukea listaan, erotin erottelee merkkijonon osat alkioiksi. Koodissa käytetään usein merkkijonojen split-metodia näissä tilanteissa – metodilla voidaan siis pätkiä erottimien kohdilta merkkijono listaksi.
  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.
Exception on yleisimpien poikkeusten pääluokka. Kutsumme sitä Pokémon-poikkeukseksi, koska jos sitä käyttää try-except-rakenteessa, except ottaa kiinni kaikki poikkeukset. Tämä ei ole hyvä asia, koska se tekee vikatilanteiden tulkitsemisen vaikeammaksi sekä ohjelman käyttäjälle, että koodarille itselleen – se ottaa nimittäin kiinni myös ohjelmointivirheet, jolloin et saa mitään hyödyllistä tietoa ohjelman kaatuessa.
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).
  1. Description
  2. Examples
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).
  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. Esimerkit
Generaattori (engl. generator) on erityinen objektityyppi, joka toimii esimerkiksi for-silmukassa listan tavoin. Generaattori ei kuitenkaan ole muistissa oleva kokoelma arvoja, vaan erityinen funktio, joka tuottaa arvoja laiskasti, eli sitä mukaa kuin sitä käydään läpi. Tästä johtuen generaattorin ”sisältöä” ei ole mahdollista tulostaa, eikä siitä voida valita alkioita indeksiosoituksella. Generaattorit eivät kuulu alkeiskurssin aihepiiriin.
  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.
  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.
  1. Description
  2. Esimerkit
Indeksi (engl. index) on kokonaislukuarvo, joka osoittaa alkion sijainnin järjestetyssä tietorakenteessa (lista, monikko, mutta myös merkkijono!). Indeksit alkavat nollasta, joten viimeinen indeksi on (rakenteen pituus - 1). Tätä voi ajatella etäisyytenä rakenteen alusta. Python tuntee myös negatiiviset indeksit, jolloin indeksi -1 viittaa aina viimeiseen alkioon, -2 toiseksi viimeiseen jne. Kun rakenteesta otetaan alkio indeksin perusteella, puhutaan usein osoittamisesta.
  1. Description
  2. Esimerkit
Kun käytetään tietorakenteen, esimerkiksi listan, indeksiä, puhutaan (indeksi)osoittamisesta. Tämä osoittaminen merkitään hakasuluilla, esim. arvosanat[0]. Indeksiosoitus palauttaa alkion. Pythonissa voidaan myös osoittaa välejä: arvosanat[1:4] jolloin palautetaan osajoukko, joka on samaa tyyppiä kuin alkuperäinen tietorakenne (eli listasta palautetaan lista). Tässä osoituksessa on huomioitava, että kaksoispisteen vasemmalla puolen on ensimmäinen alkio joka tulee mukaan ja oikealla puolella ensimmäinen joka ei tule mukaan (esimerkki palauttaisi siis 3 alkiota).
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
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
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.
Kierros (engl. iteration) on toistorakenteiden eli silmukoiden yhteydessä käytetty sana. Kierroksella viitataan siihen, kun silmukan alla sijaitseva koodi suoritetaan kertaalleen alusta loppuun – tämä on siis yksi kierros.
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. Materiaaliesimerkki
  3. Peruskäyttö
Komentoriviargumentti (engl. command line argument) tai -parametri on nimitys lisätiedolle, joka annetaan komennon yhteydessä kun ohjemaa käynnistetään komentoriviltä. Komentoriviargumentit erotetaan toisistaan tyypillisesti välilyönnillä. Esimerkiksi komennossa python koodi.py koodi.py on itse asiassa komentoriviargumentti. Komentoriviargumentteja voi käsitellä Python-koodissa sys-moduulin argv-muuttujan kautta.
  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.
Kutsupyyntö (eng. callback) on erityisesti nykyaikaisessa ohjelmoinnissa yleinen mekanismi, jossa toiselle - usein jonkun muun tekemälle - ohjelman osalle annetaan funktio, jota sen tulee kutsua toimintansa aikana. Jos tavallinen funktiokutsu vastaa puhelinsoittoa, kutsupyyntö on loogisesti soittopyyntö. Jos ohjelman osa käyttää kutsupyyntöä, sen dokumentaatio tyypillisesti kertoo, millaisen funktion sille voi antaa - erityisesti mitä parametreja funktiolla voi olla ja millainen arvo sen tulee palauttaa.
Käsittelijä(funktio) (engl. handler) on funktio, joka on kiinnitetty tapahtumaan siten, että sitä kutsutaan kun tarkkailtu tapahtuma havaitaan. Tämä johtaa siihen, että yleensä käsittelijää ei kutsuta samassa koodissa missä se on määritelty, vaan se toimii takaisinkutsuna. Käsittelijät liittyvät yleensä käyttöliittymä- ja pelikirjastoihin, joissa ohjelman pääsilmukka pyörii kirjaston sisällä ja tarkkailee tapahtumia. Käsittelijät ovat varsinaisen sovelluksen tapa toteuttaa omat toimintonsa tapahtumien kautta. Koska sovelluksen kirjoittaja ei voi vaikuttaa siihen miten käsittelijäfunktiota kutsutaan, sen parametrien ja paluuarvojen tulee vastata kirjaston antamia määrityksiä.
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. Esimerkit
Leikkaamisella (engl. slice) tarkoitetaan sitä, kun sekvenssistä (yleensä listasta, mutta myös merkkijonoista) otetaan osasekvenssi. Lopputuloksena on samaa tyyppiä oleva arvo, joka on kopio valitusta alueesta. Valinnassa merkitään aloitus- ja lopetusindeksit. Molemmat ovat tosin valinnaisia. Leikkaus merkitään sivu = kokoelma[5:10] joka ottaisi siis alkiot indekseistä 5…9. Kaksoispisteen jälkeinen luku on ensimmäinen indeksi jota ei oteta mukaan!
Leikkaaminen ei koskaan aiheuta IndexErroria!
  1. Description
  2. Esimerkit
Lista (engl. list) on järjestetty kokoelma arvoja, joka on Python-ohjelmoinnissa todellinen monitoimikone. Lista voi sisältää mitä tahansa arvoja, eikä sen kokoa tarvitse tuntea ennalta.
Listassa olevia arvoja kutsutaan alkioiksi. Jokaisella alkiolla on listassa paikka, jota kutsutaan indeksiksi. Indeksit alkavat nollasta! Kaiken tämän lisäksi lista on luonteeltaan muuntuva tietotyyppi. Kaikesta tästä on kerrottu hyvin paljon kolmosmateriaalissa.
Lista voi myös sisältää muita listoja. Tällä tavalla muodostettua tietorakennetta kutsutaan kaksiulotteiseksi listaksi (engl. two-dimensional list). Tietenkin sisäkkäisiä listoja (engl. nested list) voi olla kahtakin tasoa syvemmälle, jolloin ulottuvuuksien lukumäärä kasvaa vastaavasti. Tällöin puhutaan moniulotteisista listoista (engl. multidimensional list).
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.
  1. Description
  2. Muunnokset
Liukuluku (engl. floating point number, lyh. float) on tietokoneiden käyttämä desimaaliluvun approksimaatio. Tietokoneet eivät arkkitehtuurinsa vuoksi pysty käsittelemään oikeita desimaalilukuja, joten niiden tilalla käytetään liukulukuja. Liukuluvut saattavat aiheuttaa pyöristysvirheitä - tämä on hyvä pitää mielessä niitä käyttäessä.
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.
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.
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.
  1. Description
  2. Esimerkit
Metodi (engl. method) on funktio, joka on osa objektia eli objektin ominaisuus, jolla objekti usein muuttaa omaa tilaansa. Metodia kutsuttaessa käsiteltävä objekti tulee kutsun eteen: valinta.lower(). Metodeita kutsutaan myös joskus jäsenfunktioiksi (engl. member function).
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. Esimerkit
Monikko (engl. tuple) on ns. jäädytetty lista. Se on siis järjestetty kokoelma arvoja kuten listakin, mutta se on muuntumaton objekti - sen sisältöä ei siis voi muuttaa muuten kuin luomalla uuden kopion. Monikkoja voidaan siis ainoastaan luoda uusia ja lukea. Monikko merkitään yleensä kaarisulkeilla: (1, 2, 3), mutta myös pelkkä 1, 2, 3 on monikko.
Toisin kuin lista, monikko voi toimia sanakirjan avaimena.
  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.
  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.
Ohjausrakenne (engl. control flow) on yleisnimitys ohjelmointikielen sallimista keinoista, jotka hallitsevat jollain tavalla ohjelman suorituksen kulkua. Näihin rakenteisiin lukeutuvat kurssin puitteissa ehtorakenteet, toistorakenteet sekä poikkeusten käsittely.
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ä.
Ohjelmointivirhe eli bugi (engl. bug) on virhe ohjelman lähdekoodissa. Bugien seurauksena ohjelma ei välttämättä käynnisty ollenkaan, voi joissain tilanteissa toimia väärin ja joskus aiheuttaa jopa erittäin vakavia tietoturvaongelmia. Huolellinen ohjelmointi ja testaaminen – myös harvinaisilla nurkkatapauksilla – vähentää bugien todennäköisyyttä. Ohjelman havaitun virheellisen toiminnan aiheuttavan koodin etsimistä ja korjaamista kutsutaan debuggaukseksi.
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.
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.
  1. Description
  2. Parametrien valinta
  3. Lisämuotoilu
Paikanpidin (engl. placeholder) on yleisesti tilapäinen merkintä, joka on tarkoitus korvata toisella. Tällä kurssilla sitä käytetään lähinnä merkkijonojen muotoilun yhteydessä. Paikanpidin merkkijonon sisällä merkitään aaltosulkeilla ("Hei {}".format(nimi)). Merkkijonojen paikanpitimissä voi olla lisämäärityksiä kuten näytettävien desimaalien lukumäärä ("Aaseilla on keskimäärin {:.2f} jalkaa".format(keskiarvo)). Paikanpitimien tilalle sijoitetaan format-metodikutsun argumentit, normaalisti esiintymisjärjestyksessä. Ne voidaan kuitenkin myös numeroida tai käyttää avainsanoja.
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. Esimerkit
Poikkeus (engl. exception) on ohjelmointikielessä määritelty virhetilanne. Poikkeuksella on tyyppi (esimerkiksi TypeError), jota voi käyttää poikkeuksen käsittelyssä ohjelman sisällä sekä myös apuna virhetilanteen ratkaisussa. Tyypillisesti poikkeukseen liitetään myös viesti, joka kertoo mistä ongelmassa on kyse. Pythonissa poikkeuksia käsitellään try-except-rakenteilla.
  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.
  1. Description
  2. Esimerkit
Polku (engl. path) on tiedoston tai kansion sijainti kiintolevyllä. Polku voi olla absoluuttinen tai relatiivinen. Absoluuttinen polku sisältää kaikki kansiot aina juureen asti (esim. Windowsissa asemakirjain kuten C:), kun taas relatiivinen sisältää kansiot aktiiviseen kansioon asti (ts. siihen kansioon mistä ohjelma käynnistettiin). Polku esitetään ohjelmointikielissä yleensä merkkijonona, ja polun osat erotetaan kauttaviivalla /. Useimmiten polkuja muodostaessa kannattaa käyttää os.path-moduulin join-funktiota.
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.
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.
  1. Description
  2. Esimerkit
Rekursio (engl. recursion) on yleinen ohjelmointitermi, joka viittaa siihen, kun funktio kutsuu itseään. Rekursio on siis funktiopohjainen tapa luoda toistorakenne, jossa funktio välittää itselleen uusia argumentteja ja käsittelee omia paluuarvojaan. Rekursio on kätevä esimerkiksi puumaisia rakenteita käsitellessä – käsitellään yksi ”oksa” jollain tavalla, ja sitten rekursion avulla käsitellään tästä oksasta lähtevät oksat ja niin edelleen. Pythonissa rekursiota käytetään aika vähän. Osasyynä on sisäänrakennettu rekursiorajoitus, joka asettaa katon sille, kuinka monta kertaa funktio saa kutsua itseään.
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.
Rivinvaihtomerkki (engl. newline, line break, end of line; lyh. EOL) eli "\n" on merkki, joka tulostettaessa tai tiedostoon kirjoitettaessa saa aikaan rivinvaihdon.
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.
Sekvenssi (engl. sequence) on mikä tahansa arvo Pythonissa, jossa on tavaraa peräkkäin – esimerkiksi merkkijono, lista ja monikko kuuluvat näihin.
Matematiikasta tuttu sidontajärjestys (engl. precedence) määrittää sen, missä järjestyksessä lausekkeen operaatiot suoritetaan.
lopputulos = 10 + 2 * (2 + 3)
Yllä olevan koodin lopputulos on 20, sillä ensin lasketaan yhteen luvut 2 ja 3, joiden summa kerrotaan kahdella, ja johon lopuksi lasketaan vielä yhteen luku 10. Esimerkissä korkein presedenssi on siis sulkeilla, toisiksi korkein kertolaskulla ja matalin yhteenlaskulla.
Silmukkamuuttuja (engl. loop variable) on for-silmukan määrittelrivillä esitelty muuttuja, joka saa yksitellen kaikki läpikäytävän sekvenssin (esim. lista) arvot. Sen arvo siis vaihtuu jokaisella silmukan kierroksella. Yksinkertainen esimerkki materiaalista: for elain in elukoita:, jossa siis elain on silmukkamuuttuja. Mikäli läpikäytävä sekvenssi sisältää monikoita, silmukkamuuttujia voi olla myös useita: for opiskelija, arvosana in arvostelu:. Silmukkamuuttujat eivät ole erillisessä nimiavaruudessa, joten niiden tulee erota muista funktion/pääohjelman muuttujista.
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.
  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.
Syntaksi (engl. syntax) on koodin kielioppi. Esimerkiksi Pythonin syntaksi määrittää, millainen teksti on tulkittavissa Python-koodiksi. Jos teksti ei noudata koodin syntaksia, sitä ei voida suorittaa. Syntaksi antaa myös koodaajalle tietoa siitä, missä muodossa halutunlainen ohje tulee antaa.
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.
Tallennusformaatti on tiedoston "syntaksi", joka siis kertoo miten data on tiedostoon tallennettu. Tallennusformaatti asettaa rajat sille millaista dataa tiedostossa voidaan esittää. Sen perusajatus on se, että koodissa olevat tietorakenteet voidaan tallentaa tiedostoon jossain muodossa, ja myöhemmin ladata sieltä uudelleen. Tallennusformaatti voi seurata jotain alan standardia (esim. JSON), mutta lopullisesti on ohjelman tekijän vastuulla päättää mitkä tiedot ovat ohjelman kannalta relevantteja ja miten ne on paras esittää.
Tapahtuma (engl. event) on ohjelmointikäsite, jota käytetään yleisesti interaktiivisten sovellusten, jotka pyörivät reaaliajassa, yhteydessä. Näissä sovelluksissa on yleensä pääsilmukka, joka tarkkailee tapahtumia, joita voivat olla esimerkiksi: käyttäjä klikkaa hiirellä, käyttäjä painaa näppäimistön nappia, tietty aika on kulunut jne. Tapahtumiin voidaan kiinnittää käsittelijäfunktioita, jolloin funktiota kutsutaan aina kun tapahtuma havaitaan. Tällä tavalla helpotetaan merkittävästi interaktiivisten sovellusten ohjelmointia, koska itse sovellusta kirjoittaessa ei tarvitse huolehtia siitä miten ruudun tapahtumat tunnistetaan.
Periaatteessa tekstitiedosto (engl. text file) on mikä tahansa tiedosto, jonka sisältö voidaan lukea nätisti tekstieditorilla. Tämän kurssin kontekstissa kuitenkin tekstitiedosto on erityisesti sellainen tiedosto, jonka sisältöä käsitellään tekstinä Pythonissa. Eli siinä missä kooditiedostoja suoritetaan, tekstitiedostoja käytetään datan varastoimiseen ohjelman ajojen välillä.
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.
Tiedostokahva (engl. file handle) on erityinen objekti, jota Pythonissa käytetään avattuun tiedostoon viittaamiseen. Huomattavaa on, että kahva ei ole sama asia kuin tiedoston sisältö, mutta sen kautta voidaan lukea tiedoston sisältö tai kirjoittaa tiedostoon. Tiedostokahva saadaan käyttöön open-funktiolla, jolle määritetään avattavan tiedoston sijainti sekä avausmoodi, jossa se avataan, esim: with open("aasi.txt", "r") as tiedosto: avaa aasi.txt-tiedoston with-lauseessa (jossa tiedostot tulee yleensä avata) siten, että muuttujasta nimeltä tiedosto löytyy tiedostokahva.
Tiedostonimi (engl. filename) on tiedoston koko nimi, joka sisältää varsinaisen tiedostolle annetun nimen sekä tiedostopäätteen. Esimerkiksi aasisvengaa.py on kokonainen tiedoston nimi, jossa varsinainen annettu nimi on aasisvengaa ja pääte on .py.
Koodin sisällä tiedostojen nimet esitetään merkkijonoina.
Tila (engl. state) viittaa sananmukaisesti ohjelman tilanteeseen. Käytännössä ohjelman tila kattaa kaikki sen tila-avaruuteen (engl. state space) kuuluvat asiat, kuten muuttujien arvot, tiedostoissa olevan datan ja sen, mitä kohtaa koodista sillä hetkellä ollaan suorittamassa. Taattu keino saada aikaiseksi korjauskelvotonta spagettikoodia on käyttää niin kutsuttua globaalia tilaa (engl. global state) – rikos, johon syyllistyvät epäpuhtaat globaaleja muuttujia hyödyntävät funktiot.
Myöhemmillä, ohjelmoinnin käsitteitä formaalimmin tutkivilla kursseilla tutuksi tulevat muun muassa tilakoneet (engl. state machine) sekä tilattomat (engl. stateless) että tilalliset (engl. stateful) ohjelmat.
Toistorakenne tai silmukka (engl. loop) on ohjausrakenne, jonka alaisuuteen kirjoitettua koodia toistetaan joko tietty lukumäärä toistoja tai kunnes jokin ehto lakkaa toteutumasta. Toistorakenteiden avulla ohjelmat pystyvät jouhevasti palaamaan aiempaan kohtaan suoritusta ja niillä voidaan myös helposti käsitellä suuria määriä arvoja. Toistorakenteita ovat Pythonissa for- ja while-silmukat.
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
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.
Vertailuarvoa käytetään esim. listojen järjestämisessä. Vertailuarvo on listan alkiosta johdettu arvo, jota käytetään järjestämisperusteena. Esimerkiksi jos lista sisältää listoja, vertailuarvo voi olla jostain tietystä indeksistä otettu alkio. Se voi olla myös monimutkaisempi johdannainen, kuten listan alkioiden summa tai keskiarvo.
  1. Description
  2. Esimerkit
Avainsana break on erityinen komento, jota käytetään toistorakenteissa. Se päättää silmukan suorituksen välittömästi, ja koodin suoritus jatkuu ensimmäiseltä silmukan jälkeiseltä riviltä. Jos silmukassa oli else-osa, siihen ei mennä.
  1. Description
  2. Esimerkit
continue on toinen toistorakenteisiin liittyvä avainsana (toisen ollessa break). Toisin kuin break, joka lopettaa koko silmukan suorituksen, continue keskeyttää ainoastaan meneillään olevan kierroksen suorituksen – suoritus jatkuu siis seuraavasta kierroksesta. Huomaa, että tätä avainsanaa tarvitaan vain tilanteissa, joissa halutaan jättää osa kierroksesta suorittamatta, eli silmukan kierroksen loppuun ei ole tarpeen laittaa continue-avainsanaa.
  1. Description
  2. Esimerkit
enumerate on Pythonissa sisäänrakennettu funktion kaltainen erityisobjekti, joka tuottaa generaattoriobjektin. Sitä käytetään pääasiassa for-silmukoissa silloin, kun on tarpeen saada läpi käytävän listan alkioiden indeksit käyttöön silmukan sisällä. enumerate-objekti tuottaa monikkoja, joissa ensimmäisenä on alkion indeksi ja toisena itse alkio. Käyttöesimerkki: for i, hahmo in enumerate(muumilaakso):.
  1. Description
  2. Esimerkit
Pythonissa for on toinen silmukkatyyppi. Sen käyttötarkoitus on tietorakenteiden läpikäyminen – iterointi. Sitä käytetään erityisesti listojen kanssa. Yleisesti ottaen for-silmukkaa käytetään silloin, kun pystytään ennalta määrittämään montako kierrosta silmukkaa tulee pyörittää. Tietorakenteiden läpikäynnin lisäksi näihin lukeutuu tietyn toistomäärän tekeminen (esimerkiksi kymmenen toistoa). Silmukan määrittelyrivi on muotoa: for alkio in lista:, jossa alkion paikalle tulee silmukkamuuttujan nimi ja listan paikalla ilmoitetaan läpikäytävä tietorakenne.
  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. Esimerkit
Pythonissa with on hieman muista poikkeava avainsana, sillä se ei ole varsinaisesti ohjausrakenne tai uuden asian määrittely. Tällä kurssilla sitä käytetään pääasiassa tiedostojen avaamisessa, tyyliin with open("aasi.txt") as tiedosto:. Tiedoston luku- tai kirjoitusoperaatiot suoritetaan with-lauseen alla. Kun with-lohko päättyy, Python huolehtii automaattisesti with-lauseessa avattujen tiedostojen yms. sulkemisesta.