Termbank
  1. A
    1. Absolute Path
    2. Ajonaikainen
      konseptit
    3. Alustaminen
      muuttujat arvot
    4. Argumentti
      funktiot arvot
    5. Arvo
      arvot
    6. Assignment
      muuttujat arvot
    7. Assignment Operator
      muuttujat arvot operaattorit
    8. Attribute
      objektit
    9. Attribuutti
      Attribute
    10. Avainsana
      nimet
    11. Ajaminen
      Execution
    12. Aliohjelma
      Function
  2. B
    1. Boolean
      ohjausrakenteet tyypit
    2. Boolean Operator
      ohjausrakenteet
    3. Boolen operaattori
      Boolean Operator
    4. Branch
      ehtorakenteet try-rakenteet
    5. Bug
      ongelmanratkaisu
    6. Bugi
      Bug
    7. Builtin Function
      funktiot
    8. break
      avainsanat toistorakenteet
  3. C
    1. Callback
      funktiot
    2. Carriage Return
      merkkijonot tiedostot pakeneminen windows
    3. Code Block
      funktiot ohjausrakenteet
    4. Code File
      konseptit
    5. Command Line Argument
      terminaali
    6. Comparison Operator
      operaattorit ohjausrakenteet
    7. Comparison Value
    8. Condition
      ohjausrakenteet
    9. Conditional Statement
      ohjausrakenteet
    10. Conditional Structure
    11. Constant
      muuttujat arvot
    12. Control Structure
      ehtorakenteet toistorakenteet try-rakenteet
    13. Ctrl + C
      Näppäimistökeskeytys
    14. Callback
      Takaisinkutsu
    15. continue
      avainsanat toistorakenteet
  4. D
    1. Data
    2. Data Format
      tiedostot merkkijonot
    3. Data Structure
      konseptit listat sanakirjat
    4. Debugging
    5. Default Value
      funktiot arvot parametrit
    6. Dictionary
      tietorakenteet
    7. Docstring
      dokumentointi
  5. E
    1. Epätosi
      arvot
    2. Error Message
      ongelmanratkaisu
    3. Escape
      merkkijonot
    4. Evaluointi
      arvot lausekkeet
    5. Event
      konseptit
    6. Exception
      poikkeukset ohjaurakenteet
    7. Execution
      konseptit lausekkeet
    8. Elementti
      Item
    9. enumerate
      toistorakenteet listat
  6. F
    1. False
      Epätosi
    2. File Extension
      tiedostot
    3. File Handle
      tiedostot objektit
    4. Filename
      tiedostot merkkijonot
    5. Float
      arvot tyypit
    6. Format
      merkkijonot tulostus
    7. Function
      funktiot
    8. Function Call
      funktiot lauseet
    9. Function Definition
    10. for
  7. G
    1. Generator
      objektit toistorakenteet
    2. Globaali muuttuja
      muuttujat arvot
    3. Global Scope
  8. H
    1. Handler
      funktiot konseptit
    2. Hyppy
      ohjausrakenteet
    3. Hardkoodaus
      Kovakoodaus
  9. I
    1. if-lause
      Conditional Statement
    2. if-rakenne
      Conditional Structure
    3. Identifier
      muuttujat funktiot
    4. Indentation
      konseptit
    5. Index
      listat arvot
    6. Index Subscription
      listat arvot
    7. Infinite Loop
      toistorakenteet
    8. Input
      konseptit merkkijonot
    9. Interface
      konseptit funktiot moduulit
    10. Item
      listat arvot
    11. Iteration
      toistorakenteet
    12. import
      moduulit
  10. J
    1. Jäsenfunktio
      Method
  11. K
    1. Koodilohko
      Code Block
    2. Kahva
      File Handle
    3. Kutsu
      Function Call
    4. Key
      arvot sanakirjat
    5. Keyword Argument
      funktiot
    6. Kirjasto
      moduulit
    7. Kommentti
      dokumentointi virheenetsintä
    8. Kovakoodaus
      arvot
    9. Käyttöliittymäelementti
    10. KeyboardInterrupt
      Näppäimistökeskeytys
    11. Koodi
      Source Code
    12. Komentorivi
      Terminal
    13. Komentokehote
      Terminal
  12. L
    1. Lause
      konseptit
    2. Lauseke
      konseptit
    3. List
    4. Literal
      arvot
    5. Local Variable
    6. Loop
      ohjausrakenteet
    7. Loop Variable
      toistorakenteet muuttujat
  13. M
    1. Muotoilu
      Format
    2. Main Program
      konseptit
    3. Merkki
    4. Merkkijono
      arvot tyypit
    5. Method
      objektit funktiot
    6. Method Call
      lausekkeet objektit
    7. Module
    8. Mutable
      konseptit listat arvot
    9. Muuntumaton
      konseptit merkkijonot arvot
    10. Määrittely
      konseptit
  14. N
    1. Name Conflict
    2. Namespace
      konseptit funktiot moduulit
    3. Newline
      merkkijonot tiedostot
    4. Nimeämätön vakio
      vakiot arvot
    5. Näppäimistökeskeytys
      poikkeukset
  15. O
    1. Objekti
      konseptit
    2. Olio
      Objekti
    3. Ohjelmointityyli
    4. Ominaisuus
      objektit
    5. Opening Mode
      tiedostot
    6. Operand
    7. Operation
      lausekkeet
    8. Operator
    9. Optional Argument
      funktiot arvot parametrit
  16. P
    1. Paikanpidin
      merkkijonot tulostus
    2. Parameter
      funktiot
    3. Parametrization
    4. Path
    5. Poikkeus
      ongelmanratkaisu try-rakenteet
    6. Poikkeusten käsittely
      ohjausrakenteet poikkeukset
    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. Recursion
      funktiot konseptit
    2. Referring
      muuttujat arvot objektit
    3. Relative Path
    4. Return
      funktiot arvot
    5. Return Value
  18. S
    1. Silmukka
      Loop
    2. Sapluuna
      merkkijonot konseptit
    3. Scope
      lohkot konseptit
    4. Separator
      merkkijonot listat tiedostot syöte
    5. Sequence
      tietorakenteet toistorakenteet konseptit
    6. Sidontajärjestys
      konseptit lausekkeet
    7. Suoritusjärjestys
      Sidontajärjestys
    8. Slicing
      listat
    9. Solution Model
      ongelmanratkaisu
    10. Source Code
      konseptit
    11. State
      konseptit
    12. Stub
      funktiot ongelmanratkaisu
    13. Syntaksi
      konseptit
    14. Syntax Error
      poikkeukset
    15. Stacktrace
      Traceback
  19. T
    1. Taikaluku
      Nimeämätön vakio
    2. try-rakenne
      Poikkeusten käsittely
    3. Takaisinkutsu
      funktiot
    4. Terminal
      työkalut
    5. Testaaminen
      konseptit ongelmanratkaisu
    6. Text File
      tiedostot
    7. Tosi
      arvot
    8. True
      Tosi
    9. Traceback
      ongelmanratkaisu
    10. Tuple
      tietorakenteet listat
    11. Type Conversion
      tyypit arvot funktiot
    12. Tyylisääntö
    13. Tyyppi
      arvot konseptit
  20. U
    1. User Interface
      konseptit
  21. V
    1. Variable
      konseptit arvot
  22. W
    1. while
      toistorakenteet
    2. with
      tiedostot
Completed: / exercises

3. Exercises: The Loop Tightens

These exercises are starting to approach the territory of so-called real programs. In particular the new things we learned in the material removes the previous limitation of having to use fixed number for data handled by the program, and for how many times instructions are done in the code. Repetition opens up a whole world of possibilities, but also requires new patterns of thought. The course project exercises in this page are particularly challenging but at the same time they do provide rather concrete building blocks for the project.

Learning Goals

Using loops and lists in problem solving. Solving even larger problems than before as we're released from the restrictions we had last time. Central concepts this time around are lists and loops. For the latter, both for and while loops will have their uses, and our hope is that these exercises will demonstrate the purpose of each. When it comes to lists, one important aspect is to learn how to design useful data structures.

Example

At the end of the second material we had an idea about a program that converts measurements from US customary the-radius-of-dumbledores-robe-hem-after-extinguishing-a-fire type of units to sane SI system units. We just didn't have the capability to handle measurements en masse because we didn't know anything about lists. Well, now we know! Let's make a program where the user can input multiple measurements results, unit and everything, and the program converts them to the corresponding SI units. Because the program has been designed for processing measurement data, navigating in menus should be minimized - therefore all units should be converted automatically regardless of what quantity they are. We are going to ditch temperature though because it doesn't fit the same factor-unit pattern with the rest.
We have no idea how to handle files yet so the program itself is going to be just a temporary solution. Although, technically, we could use
terminal
input/output control to take measurements from a file and even save the results into a file...
At the end of the second material we had something along these lines and it worked for length:
LENGTH_FACTORS = {
    "in": 0.0254,
    "\"": 0.0254,
    "ft": 0.3048,
    "'": 0.3048,
    "yd": 0.9144,
    "mi": 1609.344
}

def convert_to_meters(measurement):
    value = measurement["value"]
    unit = measurement["unit"]
    try:
        meters = value * LENGTH_FACTORS[unit]
    except KeyError:
        measurement["invalid"] = True
    else:
        measurement["unit"] = "m"
        measurement["value"] = meters

measurement = {"unit": "donkey", "value": 4.64}
print("{:.3f} {}".format(measurement["value"], measurement["unit"]))
print("is")
convert_to_meters(measurement)
if not measurement.get("invalid", False):
    print("{:.3f} {}".format(measurement["value"], measurement["unit"]))
else:
    print("Invalid unit")

Solution

The first problem to solve is: how to determine both the conversion factor and the target unit from the source unit? This could be done with a colossal
conditional structure
but ain't no one got the patience to maintain that. In the original example we took the factors from a
dictionary
. Nothing prevents us from using
data structures
as dictionary values - instead of just a factor we can therefore put a
tuple
that includes both conversion factor and target unit. At the same time we can add all units to the same dictionary.
UNITS = {
    "in": (2.54, "cm"),
    "\"": (2.54, "cm"),
    "ft": (30.48, "cm"),
    "'": (30.48, "cm"),
    "yd": (0.9144, "m"),
    "mi": (1.609344, "km"),
    "oz": (28.349523125, "g"),
    "lb": (0.45359237, "kg"),
    "cp": (2.365882365, "dl"),
    "pt": (4.73176473, "dl"),
    "qt": (0.946352946, "l"),
    "gal": (3.785411784, "l")    
}
We can get the conversion factor from this structure by casting the following spell: UNITS[unit][0], and the target unit with: UNITS[unit][1]. In other words we first find the tuple that corresponds with a
key
, and then from within the tuple the value we wanted with
index subscription
. Using this information, the above function can be changed into convert_to_si as follows:
def convert_to_si(measurement):
    value = measurement["value"]
    unit = measurement["unit"]
    try:
        # first item in the tuple is the factor
        si_value = value * UNITS[unit][0]
    except KeyError:
        measurement["invalid"] = True
    else:
        # second item in the tuple is the new unit
        measurement["unit"] = UNITS[unit][1]
        measurement["value"] = si_value
This function still modifies an existing dictionary and therefore doesn't need to return anything. Next we need to actually get measurements from somewhere. Because we want to make a program that can eventually process actual data files, we'll make a function that creates a list of measurements by prompting them from the user. We could also do the conversion immediately after
input
but because manual input is not the ultimate goal of the program, calling the conversion function should not be placed into the input function. The input function is just a data source. Input is processed with split like we learned in the material.
def read_measurements():
    print("Input measured values and units separated with spaces. Leave empty to quit.")
    measurements = []
    while True:
        value_unit = input("Input measurement: ").strip()
        if not value_unit:
            return measurements
        try:
            value, unit = value_unit.split(" ")
            value = float(value)
        except ValueError:
            print("Enter measurements in the specified format")
        else:
            measurements.append({
                "unit": unit,
                "value": value
            })
This function implements something that was skipped in the material: how to handle quitting the program when the input is splitted. This usually requires handling the input in two phases - first the entire input is taken into a variable which can show whether it's empty, and only after that we try to convert into a usable form. Conveniently both lines in the try
branch
produce ValueError if they go wrong, so we can get away with just one except statement. Valid measurements are appended to the measurements
list
as dictionaries that have the same structure as the previous example. These functions can be combined in the main function:
def main()
    measurements = read_measurements()
    for measurement in measurements:
        convert_to_si(measurement)
One interesting aspect with this solution is that the list that actually contains the measurements is never modified - only the dictionaries within it are changed. This shows quite nicely how
mutable
types work. We still need some way to show the results. Because this program is intended for bigger plans, printing should also be done in its own function.
def print_measurements(measurements):
    for measurement in measurements:
        if measurement.get("invalid"):
            print("Invalid measurement {value:.3f} {unit}".format(**measurement))
        else:
            print("{value:.3f} {unit}".format(**measurement))
Because the function itself doesn't do anything special, we've thrown in a trick that we didn't show in the material. It's possible to unpack the dictionary to act as format method
keyword arguments
. In other words the dictionary keys will become keywords, and they can be used as
placholders
in the format template. **measurement could be replaced with value=measurement["value"], units=measurement["unit"]. Of course if you use this trick you have to make sure the dictionary actually contains the keys to match the placholders.
As a final touch we add a call to this print function to the main function, and then we call the main function itself from the actual main program with a familiar structure:
try:
    main()
except KeyboardInterrupt:
    print("Measurement processing interrupted")
The whole program:
converter.py
UNITS = {
    "in": (2.54, "cm"),
    "\"": (2.54, "cm"),
    "ft": (30.48, "cm"),
    "'": (30.48, "cm"),
    "yd": (0.9144, "m"),
    "mi": (1.609344, "km"),
    "oz": (28.349523125, "g"),
    "lb": (0.45359237, "kg"),
    "cp": (2.365882365, "dl"),
    "pt": (4.73176473, "dl"),
    "qt": (0.946352946, "l"),
    "gal": (3.785411784, "l")    
}

def convert_to_si(measurement):
    value = measurement["value"]
    unit = measurement["unit"]
    try:
        # first item in the tuple is the factor
        si_value = value * UNITS[unit][0]
    except KeyError:
        measurement["invalid"] = True
    else:
        # second item in the tuple is the new unit
        measurement["unit"] = UNITS[unit][1]
        measurement["value"] = si_value

def read_measurements():
    print("Input measured values and units separated with spaces. Leave empty to quit.")
    measurements = []
    while True:
        value_unit = input("Input measurement: ").strip()
        if not value_unit:
            return measurements
        try:
            value, unit = value_unit.split(" ")
            value = float(value)
        except ValueError:
            print("Enter measurements in the specified format")
        else:
            measurements.append({
                "unit": unit,
                "value": value
            })

def print_measurements(measurements):
    for measurement in measurements:
        if measurement.get("invalid"):
            print("Invalid measurement {value:.3f} {unit}".format(**measurement))
        else:
            print("{value:.3f} {unit}".format(**measurement))
        
def main():
    measurements = read_measurements()
    for measurement in measurements:
        convert_to_si(measurement)
    print_measurements(measurements)
    
try:
    main()
except KeyboardInterrupt:
    print("Measurement processing interrupted")
As a bonus trick we'll show how you could enter a batch of measurements to the program, at least on the Linux command line. Let's say we have the following file of measurements. The empty line at the end is very important!
measurements.txt
23 in
12.4 oz
54 mi
2.45 yd
5.31 gal
This could be fed to our program like this:
/some/folder$ python3 converter.py < measurements.txt
Input measured values and units separated with spaces. Leave empty to quit.
Input measurement: Input measurement: Input measurement: Input measurement: Input measurement: Input measurement: 58.420 cm
351.534 g
86.905 km
2.240 m
20.101 l
The only eyesore here is how the input prompt is printed for each line in the file. But not to worry, in the next material we learn to read files properly with Python.

General Exercises

All of these are required.

Warmup Exercise

The Downward Spiral

Loops allow programmers to unleash their artistic talents (or lack of). Loops can be used in combination with some simple arithmetics to draw shapes and lines that change based on a pattern. In this example we're drawing some pleasantly patterned spirals.
Learning goals: How to do a predetermined number of iterations with a
loop
. We also recall how to define
optional arguments
for functions.
Goal: Make a program that draws patterned spirals that have adjustable parameters: color, radius, radius growth and pen weight.
Function specification: draw_spiral
  • Parameters
    :
    • spiral's color (color string or three value tuple)
    • number of arcs (quarter circle) to draw (integer)
    • spiral's starting radius (integer)
    • radius growth (float)
    • pen weight (integer) -
      default value
      1
First thing to do in the function is to set the color and pen weight. Rest of the drawing commands are done inside a loop with a number of iterations equal to number of arcs. Each iteration draws a 90 degree arc after which the radius is incremented by radius growth. Note that the
loop variable
is not necessarily used for anything.
Main Program Specification:
The main program can consist of the following lines:
draw_spiral("black", 20, 10, 3)
draw_spiral("red", 10, 20, 4, 3)
draw_spiral("blue", 10, -20, -4, 3)
done()
These should draw the piece of art shown in the example.
List of Turtle Commands:
forward(x)   # makes the turtle move forward x pixels, e.g. forward(42)
left(a)      # makes a left turn of a degrees, where a is an integer, e.g.. left(40)
right(a)     # makes a right turn of a degrees, where a is an integer, e.g.. right(40)
color(c)     # sets color. c is a color value. In this exercise, you can use basic values such as "red", "yellow", "blue", e.g. color("red")
begin_fill() # begins a fill; any lines drawn after this are treated as boundaries for the fill
end_fill()   # stops a fill; this command indicates that we're happy with our boundaries, and it's ok to pour the selected color (by the color command) inside
reset()      # if you make a mistake, you can use this command to clear everything and return the Turtle to its origin.
up()         # lifts the pen up so that it can be moved without drawing
down()       # puts the pen back down 
setx(x)      # sets the pen's x coordinate to the given value
sety(y)      # sets the pen's y coordinate to the given value
circle(r)    # draws a circle with radius r; this happens by moving the pen a full 360 degree circle from its current position constantly steering to the left
pensize(w)   # sets the pen's weight to w
In addition we're now going to use the first optional argument of the circle function:
circle(r, a) # draws an arc with radius r and sector angle a
Examples:
Masterpiece drawn by the given main program.
Warning: You have not logged in. You cannot answer.

Main Exercises

Prompt Automata

A whole lot of unnecessary work goes into creating and maintaining prompt loops for all inputs in a program just to check whether the user's actually given numbers. Let's automate this process a bit by creating one function that can be used whenever an integer needs to be prompted in a program, and we need to check that the input really was an integer. The function we create in this exercise is a very handy tool, and we will use it in the other exercises as a base. We even recommend using it in the course project.
Learning goals: Making a
loop
that is repeated until the user gives a valid
input
. Writing a reusable function.
Goal: A function that prompts the user for an integer until it gets one. The function has customizable prompt and error messages that can be given as
arguments
.
Function specification: prompt_input
  • Docstring
    :
"""
Prompts the user for an integer using the prompt parameter.
If an invalid input is given, an error message is shown using
the error message parameter. A valid input is returned as an
integer.
"""
  • Parameters
    :
    • the input prompt message to display (string)
    • error message to display for invalid input (string)
  • Returns
    :
    • The user's input as an integer (integer)
The function must present an input prompt with the given message until the user gives a valid integer. Whenever the user gives an invalid input, the error messages receives as the second parameter is printed, and the prompt is repeated. When the user's input is valid, it is returned as an integer. There's a particular example in the material you may find helpful.
Main Program Specification:
In the main program we want to call the function twice with different arguments in order to show neatly it handles prompts using different messages. We've saved you the trouble of coming up with one by providing this code:
number = prompt_input(
    "Give an integer: ",
    "You did not give an integer"
)
print("You gave the {} integer! Good job!".format(number))
moogles = prompt_input(
    "How many moogles are in the Moogle Village? ",
    "This is not a valid number of moogles!"
)
print("There are {} moogles in the village.".format(moogles))
Use Examples:
When the above main program is executed, you should get the something like this if your function woks correctly:
Give an integer: donkey
You did not give an integer
Give an integer: sixtynine kappa
You did not give an integer
Give an integer: 5
You gave the 5 integer! Good job!
How many moogles are in the Moogle Village? 7.5
This is not a valid number of moogles!
How many moogles are in the Moogle Village? 1
There are 1 moogles in the village
Warning: You have not logged in. You cannot answer.

A Prime Exercise

This is an exercise about prime numbers. That said. the more important part of this exercise is to use functions as tools and to reuse existing code. Both functions that will form the solution to this exercise could easily be taken out and used in another program without modifications. This is possible because well-designed tool functions don't do anything extra - they only do exactly what they promise, and return a value that can be used in further processing.
Learning goals: Using
loop variable
with the range function and ending a
loop
with return. Reusing and modifying an existing
function
.
Goal: A program that prompts the user for an integer and tells whether it's a prime.
Before You Begin:
You need the prompt_input function from the previous exercise. Copy it to your code file. You also need to slightly modify it.
Function modification: prompt_input
  • Docstring
    :
"""
Prompts the user for an integer using the prompt parameter.
If an invalid input is given, an error message is shown using
the error message parameter. A valid input is returned as an
integer. Only accepts integers that are bigger than 1.
"""
  • Parameters
    :
    • the input prompt message to display (string)
    • error message to display for invalid input (string)
  • Returns
    :
    • the user' input as integer (integer)
In addition to what it did previously, the function must also repeat the prompt if the given integer is smaller than or equal to 1. The same error message is used in all error scenarios.
Function Specification: check_prime
  • Docstring:
Checks whether an integer is a prime number. Returns False
if the number isn't a prime; if it is a prime, returns True
  • Parameters:
    • number to check (integer)
  • Returns:
    • whether the number is a prime (
      boolean
      )
The function has to use some suitable method to determine whether the given number is a prime. You can investigate suitable methods with Google or Wikipedia!. You may find out that modulus (%) is a useful operator for this task. You may also find it useful to know that range accepts more than one
argument
. You can try stuff out in the
Python console
!
As the above specification should show, this function returns a value that indicates whether the number was a prime - it does not print the information!
Main Program
Specification:
The main program prompts the user for a number using the modified promp function. Then it uses the check function to determine whether the number was prime, and prints a statement based on the
return value
.
Use Examples:
Give an integer that's bigger than 1: 1
You had one job
Give an integer that's bigger than 1: four
You had one job
Give an integer that's bigger than 1: 9
This is not a prime
Give an integer that's bigger than 1: 7
This is a prime
Warning: You have not logged in. You cannot answer.

Course Project Exercises 1

Do one of these, preferably the one that matches your course project topic.

Field Day

Grids are usually represented as two-dimensional lists, i.e. as a list that contains other lists where each inner list corresponds to a row in the grid, and each item in the inner lists is one the content of one square or tile. In this exercise we'll take our first proper look at such lists, and particularly at what kinds of loops are required for iterating through them. We'll take a short break from sweeping mines, and instead head into the countryside to examine what kinds of animals can be found from the nearby fields... Even so, the princples here very much apply in the Minestomper course project.
Learning goals: Using nested
for loops
to iterate through 2-dimensional lists.
Goal: A program that examines all tiles in a field and tells what animals were there.
Before You Begin:
We're going to use a dictionary once again. The reason is that in the field lists, animals are marked with single characters, but we want to print their actual names in the output. The following dictionary connects the identifiers to the animals:
ANIMALS = {
    "s": "sheep",
    "d": "doggo",
    "@": "cat",
    "m": "moogle",
    "c": "chocobo"
}
1st function specification: explore_tile
  • Docstring
    :
"""
Explore a tile - if there is an animal, prints the
location and name of the animal
"""
  • Parameters
    :
    • the character in the tile (
      string
      )
    • row number
    • column number
Information about the animal is printed if its identifier character is found from the dictionary. If it's not there, nothing is printed. The print is in the form "Tile (5, 6) contains donkey" where 5 is the x coordinate and 6 is the y coordinate. It's almost like we've seen this before... Note that y matches the row number, and x matches column number.
The checker reserves the rights to modify the given dictionary, which must be taken into account in your implementation.
2nd function specification: explore_field
  • Docstring:
"""
This function explores an entire field by calling the explore_tile
function for each tile in the field.
"""
  • Parameters:
    • 2-dimensional list that represents a field
The function must go through all tiles is in the field. This is best done with for loops. Because we need each tile's coordinates for the check_tile function, we need both the contents of rows and tiles along with their
indices
. Keep in mind that the outer index is used to select the rows, and therefore corresponds to the y coordinate.
Main Program Specification:
The main program is not checked, but having one is really helpful when testing the program. Define an example field, and call the explore_grid function. We've given you a field. We trust your ability to write a
function call
at this point.
field = [
    [" ", "s", " ", " ", "m"],
    [" ", "d", "@", "d", " "],
    ["c", " ", "s", "d", " "]
]
Example Use:
Running the main program with the given field should print:
Tile (1, 0) contains sheep
Tile (4, 0) contains moogle
Tile (1, 1) contains doggo
Tile (2, 1) contains cat
Tile (3, 1) contains doggo
Tile (0, 2) contains chocobo
Tile (2, 2) contains sheep
Tile (3, 2) contains doggo
Not that if you have gotten the coordinates mixed in both functions, you will get the correct print but your functions individually don't work correctly.
Warning: You have not logged in. You cannot answer.

A Pointed Line

In this exercise you'll get to work on the process of creating a new list based on an existing one. This technique is typically needed e.g. when some formula needs to be applied to all values in a list. This might also be useful for the Spectral Matters course project.
Learning goals: Creating a new
list
by using
items
of an existing list.
Goal: A program that calculates intermediate points of a line between two endpoints.
Before You Begin:
The calculate_parameters function that was created in last time's exercises is needed again. Go grab it from your answer.
1st function specification: prompt_two_numbers
  • Docstring
    :
"""
Prompts two floats from the user, separated by a space. The prompt
is repeated until the user gives a valid input. Both numbers are
returned as floats.
"""
  • Parameters
    :
    • prompt string (
      string
      )
  • Returns
    :
    • x coordinate of the point (
      float
      )
    • y coordinate of the point (float)
Prompts the user to
input
two floats separated by a space, using the given prompt string. The prompt is repeated until the user gives a valid input. If there is an error, the function prints "Give two numbers separated by a space". When the input is valid, both numbers are returned as floats.
2nd function specification: determine_points
  • Docstring:
"""
Produces a list of values that are the y values of a line with
the given slope and y intercept, from a list of x values.
"""
  • Parameters:
    • line slope (float)
    • line y intercept (float)
    • list of x values (list of floats)
  • Returns:
    • list of y values (list of floats)
The function must create a new list with the calculated y coordinate values.
Main Program Specification:
The program prompts the user for two points aby using the brand new prompt_two_numbers function. You can see the
argument
string in the examples below. After prompting, the program prints a list of y coordinates that are calculated from a list of x coordinates and the line parameters.
You can use the following list of x coordinates in your program:
x_axis = [
    0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5,
    2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.25, 4.5, 4.75, 5.0
]
The checker will naturally test your functions with other lists as well. In order to get a print that matches the examples, you can use the loop shown below. It uses the end keyword argument of print to swap the newline at the end of each print to a single space. We can't use the join method here because the lists don't contain strings.
for y in y_axis:
    print("{:.4f}".format(y), end=" ")
Use Examples:
Input first point: donkey
Give two numbers separated by a space
Input first point: 0 0
Input second point: 1 1
Line y values are:
0.0000 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000 1.7500 2.0000 2.2500 2.5000 2.7500 3.0000 3.2500 3.5000 3.7500 4.0000 4.2500 4.5000 4.7500 5.0000
Input first point: 0.0 1.0
Input second point: 0
Give two numbers separated by a space
Input second point: 1.0 0.0
Line y values are:
1.0000 0.7500 0.5000 0.2500 0.0000 -0.2500 -0.5000 -0.7500 -1.0000 -1.2500 -1.5000 -1.7500 -2.0000 -2.2500 -2.5000 -2.7500 -3.0000 -3.2500 -3.5000 -3.7500 -4.0000
Input first point: 0 0
Input second point: 2 1
Line y values are:
0.0000 0.1250 0.2500 0.3750 0.5000 0.6250 0.7500 0.8750 1.0000 1.1250 1.2500 1.3750 1.5000 1.6250 1.7500 1.8750 2.0000 2.1250 2.2500 2.3750 2.5000
Input first point: -5 5
Input second point: 0 0
Line y values are:
0.0000 -0.2500 -0.5000 -0.7500 -1.0000 -1.2500 -1.5000 -1.7500 -2.0000 -2.2500 -2.5000 -2.7500 -3.0000 -3.2500 -3.5000 -3.7500 -4.0000 -4.2500 -4.5000 -4.7500 -5.0000
Warning: You have not logged in. You cannot answer.

Engineer's Little Helper

In this exercise you get to create a function that will immensely enhance the user experience in the Run, Circuit! Run! course project: inputting components and their values using unit prefixes (kilo, mega, milli, micro etc.)
Learning goals: Separating unit prefix from a
string
. Retrieving a multiplier from a
dictionary
.
Goal: A program that can convert a unit prefix into its corresponding multiplier.
Before You Begin:
In order to make the conversion smooth, it's best to define a dictionary at the beginning of the program. The dictionary should have unit prefix symbols as
keys
and their corresponding multipliers as values. You can find the unit prefixes from here. We want a dictionary that has all units from the table in the link except deca (i.e. all with one character symbol). Use "u" for micro because it's easier to type than "μ".
Function specification: convert_prefix
  • Docstring
    :
"""
Converts the given number and (optional) unit prefix into the
corresponding float.
"""
  • Parameters
    :
    • number to convert (
      string
      )
  • Returns:
    :
    • converted number (float)
This
function
takes the value from its parameter and returns the corresponding float value, or None if the value wasn't valid. The conversion should be done using the dictionary we asked you to define. The checker will reject solutions with as many
branches
as there are unit prefixes
. There are a couple of problems to solve here: how to take out the (optional) unit prefix from the string, and how to convert the whole thing into a float.
Main Program Specification:
The main program should prompt the user for a value to convert until they provide a valid one. The main program also prints the result of the conversion. If the value is not valid (i.e. your function returns None), the program prints "Input was not valid" and prompts again. Note that the program should end after one valid input as you can see from the examples.
Use Examples:
Input value to convert: 2k
2000.0
Input value to convert: 1.5G
1500000000.0
Input value to convert: 220
220.0
Input value to convert: 2B
Input was not valid
Input value to convert: iceT
Input was not valid
Input value to convert: 0.1m
0.0001
Note also that if a value is very big or small, Python automatically converts it to exponential notation. The following happens automatically:
Input value to convert: -560p
-5.6e-10
Warning: You have not logged in. You cannot answer.

Course Project Exercises 2

Do one of these as well.

B Class Action

The followers of the path of the Minestomper will find mastering the secrets of this exercise useful. Your task is to assist a brave hero in counting the amount of ninjas surrounding them. In order to attain the rank of apprentice in the Minestomper skill tree, you'll get to implement this function that could also be used for counting mines...
Learning goals: Handling surrounding cells in a 2-dimensional
list
and counting certain characters from them.
Goal: A program that counts the number of ninjas surrounding a tile.
Function specification: count_ ninjas
  • Doctstring
    :
"""
Counts the ninjas surrounding one tile in the given room and
returns the result. The function assumes the selected tile does
not have a ninja in it - if it does, it counts that one as well.
"""
  • Parameters
    :
    • x coordinate of the selected tile (integer)
    • y coordinate of the selected tile (integer)
    • a data structure representing a room (list that contains lists that contain single character strings)
  • Returns
    :
    • number of ninjas (integer)
There are at most 8 surrounding tiles - diagonals are counted. You always need to make sure you're not trying to count ninjas from out of bounds (nor should you count ones from opposite walls if the index goes negative). Those desiring to become master minestompers should implement the counting with
loops
.
The function must work with rooms of any size. This means that you have to measure the boundaries inside the function from the list structure that represents a room (using the len function).
Main Program Specification:
You should make a main program for testing. You can use the following room:
room = [['N', ' ', ' ', ' ', ' '],
        ['N', 'N', 'N', 'N', ' '],
        ['N', ' ', 'N', ' ', ' '],
        ['N', 'N', 'N', ' ', ' '],
        [' ', ' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' ', ' ']]
In addition you may want to add a few calls to your function and print the resuls to see whether your counting works correctly.
Warning: You have not logged in. You cannot answer.

Walker - Measurement Ranger

This exercise should be helpful in dealing with Spectral Matters. This is a relatively common problem where we have two lists with data - one contains measurement points, and the other the corresponding measured values - and we want to select a matching slice from both of them. In order to succeed, a reverse index lookup is needed - you need to figure out the indices of measurement points.
Learning goals: Finding
indices
from
lists
with boundary values that are not among the list's
items
.
Goal: A program that finds the desired slice from a list of measurement points, and the corresponding slice from the measured values list.
Before You Begin:
The prompt_two_numbers function from the previous exercise can be used in this one as well. This time we're not prompting for a coordinate pair, but rather two points from the same axis. But hey, it doesn't matter because we can just change the prompt thanks to making the function flexible enough. No need to modify this function.
Function specification: find_indices
  • Docstring:
"""
Finds two endpoints from a list of numerical data so that the resulting
the values between the selected indices are between the given minimum 
and maximum boundaries. Returns the two indices.
"""
  • Parameters
    :
    • measurement point series (list of floats)
    • selected minimum boundary (float)
    • selected maximum boundary (float)
  • Returns:
    • starting index for the selection (integer)
    • end index for the selection (integer)
The function must find the index for the first
item
that's bigger than (or equal to) the minimum boundary
- this is the start index. It also needs to find the first item that's bigger than the maximum - the index of this item is the end index. In accordance with how
slicing
works in Python, the end index is the first index that will not be included. If the maximum is bigger than the last item in the list, use the list's length for the end index. If both are bigger, return the list's length for both.
Main Program Specification:
The main program needs two lists: first list contains the measurement points, and second list contains measured values. The lists are shown below. Of course the checker will try your functions with other lists as well.
m_points = [
    10.000, 10.244, 10.429, 10.576, 10.589, 10.606, 10.714, 10.794, 10.879, 10.99,
    11.263, 11.448, 11.596, 11.836, 11.869, 11.936, 12.174, 12.182, 12.243, 12.282,
    12.285, 12.297, 12.363, 12.417, 12.629, 12.71, 12.816, 13.138, 13.153, 13.215,
    13.27, 13.32, 13.367, 13.368, 13.923, 13.97, 14.171, 14.204, 14.235, 14.382,
    14.481, 14.581, 14.588, 14.645, 14.7, 14.704, 14.711, 14.803, 14.936, 15.000
]
m_values = [
    30.4, 74.165, 118.615, 54.293, 174.187, 162.399, 25.643, 181.571, 151.84, 147.307,
    85.115, 81.337, 65.852, 127.676, 10.409, 131.279, 32.595, 89.49, 40.263, 32.712,
    114.974, 7.967, 131.166, 124.827, 172.936, 145.234, 156.433, 118.446, 2.253, 69.263,
    99.249, 23.344, 119.2, 169.069, 187.976, 113.63, 173.847, 193.978, 54.206, 60.27,
    199.026, 167.434, 138.631, 3.259, 23.886, 88.825, 49.804, 109.179, 62.388, 126.052
]
In order to test your program, you can use the prompt_two_numbers function to get the minimum and maximum boundaries from the user, and then print the corresponding slice of measurement values.
Use Examples:
Give two measurement points separated by space: harry
Give two numbers separated by a space
Give two measurement points separated by space: 11
Give two numbers separated by a space
Give two measurement points separated by space: 11 13
Measured values in the selected range:
[85.115, 81.337, 65.852, 127.676, 10.409, 131.279, 32.595, 89.49, 40.263, 32.712, 114.974, 7.967, 131.166, 124.827, 172.936, 145.234, 156.433]
Give two measurement points separated by space: 10.606 11.936
Measured values in the selected range:
[162.399, 25.643, 181.571, 151.84, 147.307, 85.115, 81.337, 65.852, 127.676, 10.409, 131.279]
Give two measurement points separated by space: 10 15
Measured values in the selected range:
[30.4, 74.165, 118.615, 54.293, 174.187, 162.399, 25.643, 181.571, 151.84, 147.307, 85.115, 81.337, 65.852, 127.676, 10.409, 131.279, 32.595, 89.49, 40.263, 32.712, 114.974, 7.967, 131.166, 124.827, 172.936, 145.234, 156.433, 118.446, 2.253, 69.263, 99.249, 23.344, 119.2, 169.069, 187.976, 113.63, 173.847, 193.978, 54.206, 60.27, 199.026, 167.434, 138.631, 3.259, 23.886, 88.825, 49.804, 109.179, 62.388, 126.052]
Warning: You have not logged in. You cannot answer.

Overwhelming Resistance

Handling resistors is one of the more simple calculations when it comes to electric circuits. They'll be a good first step towards the Run, Circuit! Run! course project. In this exercise you'll get to calculate simple serial and parallel connections.
Learning goals: Gathering user
inputs
to
lists
and using these lists in calculations.
Goal: A program that can calculate the total impedance of serial and parallel connections for resistors.
1st function specification: prompt_values
  • Docstring
    :
"""
Prompts floats from the user until an empty input is given.
Given values are returned as a list.
"""
  • Returns
    :
    • given values as list of floats (
      list
      )
The function must implement a
loop
that is repeated until the user's input is empty ("", i.e. its truthfulness is False). You should initialize an empty list at the beginning of the function, and then collect all valid floats given by the user into it. Invalid inputs are rejected with an error message.
2nd function specification: calculate_serial
  • Docstring:
"""
Calculates the serial total resistance for the list of given
resistor values.
"""
  • Parameters:
    • list of resistor values (list of floats)
  • Returns:
    • total resistance (float)
Calculates the total resistance for the given list of resistors and returns it. Simple.
3rd function specification: calculate_parallel
  • Docstring:
"""
Calculates the parallel total resistance for the list of given
resistor values.
"""
  • Parameters:
    • list of resistor values (list of floats)
  • Returns:
    • total resistance (float)
Calculates the parellel total resistance. This is not as simple. You must calculate the inverse values for each resistor inside your function, because the values inside the list it receives have not been inverted yet.
Main Program Specification:
The program must use the prompt_values function to get resistors from the user and finally report the total serial and parallel resistances for these resistors. If the user doesn't input any resistors, you need to skip the calculations - parallel calculation would cause an
exception
in this case.
Use Examples:
Input resistor value: 0
Component value must be bigger than zero
Input resistor value: 100
Input resistor value: 200
Input resistor value: 300
Input resistor value: 

Serial resistance: 600.0
Parallel resistance: 54.54545454545455
Input resistor value: One Ohm
Component value must be bigger than zero
Input resistor value: 1.00
Input resistor value: Two Ohms
Component value must be bigger than zero
Input resistor value: 2.00
Input resistor value: 

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