This site uses cookies. Only cookies that are necessary for the site to
work or to remember your settings (like language) are used. This site does
not use any tracking cookies.
Learn more about our terms and conditions.
In this exercise we can finally make programs that are a bit more than simple calculation automatons. Execution can differ more drastically between runs of the same program because now the user has more options for interacting with the program. Compared to the last exercises these ones should be quite a bit more challenging when more different situations are entered into the equation. The last set of exercises also give your very first introduction to sub problems of the final project topics. They can be used as a very rough approximation what kinds of things will be encountered in the project.
Make a program that prompts for two integers, and figures out whether one of them is the other one's factor. Users are notified about invalid inputs. Below are some examples of how the program should look like to the user:
{{{
Input first number: 5
Input second number: 10
5 is a factor of 10.
Input first number: 9
Input second number: -3
-3 is a factor of 9.
Input first number: 7
Input second number: 4
Neither of the numbers is the other's factor.
Input first number: 2
Input second number: -2
2 is a factor of -2.
Input first number: 0
Input second number: 3
3 is a factor of 0.
Input first number: 0
Input second number: 0
0 is a factor of 0.
Input first number: aasi
This doesn't look like a number
Input first number: 0
Input second number: aasi
This doesn't look like a number
Let's start with the easy part: prompting the numbers. We should already know how to do this from the last exercises:
number_1=int(input("Input first number: "))number_2=int(input("Input second number: "))
The testing can be done with modulo. If the remainder is zero, the divider is the dividee's factor.
Let's think about how this program would branch. There are two possible prints: either one of the numbers is the other one's factor, or neither is. This could hint at there being two
branches
like seen below. At this stage we'll just use pass inside the branch for each
This results in an immediate problem: which one was the factor of the other? The conditional statement we devised doesn't give us that information. We'd need another test inside this branch to figure out which was which. We could do that by checking which number is smaller since a bigger number can't be the factor of a smaller number. We're not doing that though because it makes things unnecessarily complicated. Instead we split this branch into two branches:
With this we know that when in the first branch, number_2 was a factor of number_1, and likewise in the second branch we know it's the other way around. We can now replace the placeholder pass commands with prints. We do this by copying the text from the given examples and replacing numbers with
placeholders
. Notice the changing order of
arguments
between branches.
ifnumber_1%number_2==0:print(f"{number_2} is a factor of {number_1}.")elifnumber_2%number_1==0:print(f"{number_1} is a factor of {number_2}.")else:print("Neither of the numbers is the other's factor.")
Let's combine this with the input prompts we wrote earlier and try it out:
Input first number: 4
Input second number: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/media/sf_virtualshare/OA/code/H2/factor.py in
1 number_1 = int(input("Input first number: "))
2 number_2 = int(input("Input second number: "))
----> 3 if number_1 % number_2 == 0:
4 print(f"{number_2} is a factor of {number_1}.")
5 elif number_2 % number_1 == 0:
ZeroDivisionError: integer division or modulo by zero
Oh yeah, zero might be a problem since we're doing division with the numbers. We know that all numbers are factors of zero and zero is a factor of itself. In other words, if one of the numbers is zero, the other number will always be its factor. This time we're wiser and don't even try to put this inside one
branch
. Instead, we'll add two. This time it is also extremely important to consider the placement of these new branches. If the user
inputs
zero, code execution cannot be allowed to reach any
conditional statements
that contain division. This can be achieved by putting the new branches before the old ones. This works because only the first branch with a fulfilled
condition
is executed - everything after it in the same
conditional structure
is skipped. With this addition we have:
number_1=int(input("Input first number: "))number_2=int(input("Input second number: "))ifnumber_1==0:print(f"{number_2} is a factor of {number_1}.")elifnumber_2==0:print(f"{number_1} is a factor of {number_2}.")elifnumber_1%number_2==0:print(f"{number_2} is a factor of {number_1}.")elifnumber_2%number_1==0:print(f"{number_1} is a factor of {number_2}.")else:print("Neither of the numbers is the other's factor.")
Let's try again:
Input first number: 4
Input second number: 0
4 is a factor of 0.
We're now golden. At least as long as the user actually
inputs
integers. We still need to handle invalid inputs. This can be done with a try-except structure that catches the ValueError
exception
- like we did in the material.
try:number_1=int(input("Input first number: "))number_2=int(input("Input second number: "))exceptValueError:print("This doesn't look like a number")
This is fine, sort of, except if we actually put it as-is in the beginning of the program, we achieve new problems:
Input first number: donkey
This doesn't look like a number
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/media/sf_virtualshare/OA/code/H2/factor.py in
4 except ValueError:
5 print("This doesn't look like a number")
----> 6 if number_1 == 0:
7 print(f"{number_2} is a factor of {number_1}.")
8 elif number_2 == 0:
NameError: name 'number_1' is not defined
If you look carefully you can see that the notification was printed like we wanted. Unfortunately the program still crashed. The culprit is the NameError caused by line 6 in the code. We really got our work cut out for us... The crux of the problem is that the execution of line 2 is interrupted immediately when the int function fails. This means that number_1 was never defined. Obviously there's little point in going through the conditional structure if we don't have two numbers to compare. The correct behavior would be to skip rest of the program if there is an exception in the input part. We can achieve this by adding an else branch to our try structure and pushing the rest of the code inside it:
try:number_1=int(input("Input first number: "))number_2=int(input("Input second number: "))exceptValueError:print("This doesn't look like a number")else:ifnumber_1==0:print(f"{number_2} is a factor of {number_1}.")elifnumber_2==0:print(f"{number_1} is a factor of {number_2}.")elifnumber_1%number_2==0:print(f"{number_2} is a factor of {number_1}.")elifnumber_2%number_1==0:print(f"{number_1} is a factor of {number_2}.")else:print("Neither of the numbers is the other's factor.")
Understanding the above construct is of extreme importance for completing exercises in this page. Study it to your heart's content. Now the program works:
Input first number: donkey
This doesn't look like a number
This exercise contains tasks that will ask you to stop the program execution when an error is detected. This means that notifying the user about their error should be the last executable line in that particular branch in the program. The structure of the program has to be designed in a way that every error notification happens inside a control structure in such a way that there will be nothing left to execute after it. If you try to google how to exit a Python program, you can easily find answers using the quit and exit functions. However, these cannot be used for two reasons.
The first reason is related to learning: one major goal of this exercise is to learn to control the flow of the program with control structures - without shortcuts. Shortcuts can be used when the fundamentals of program flow control have been learned. The other reason is technical: these functions will shut down the entire Python process. The checkers work by importing the returned program as part of themselves to run it and call its functions. Therefore, these forbidden functions will not only close the returned program, they will also close the checker. As a result you will get the dreaded "The checking program was unable to finish" error.
Sometimes screen geometry requires knowing an object's position in relation to another object or an axis. For instance if we want a creature that moves towards the nearest edge, we first need to find out which direction the closest edge is to. In this exercise you'll get to implement a simple conditional statement that is used for drawing politically oriented squares. Their color depends on their position: red for left, blue for right.
Learning goals: [!hint-poliittiset-neliöt-if!]Controlling program flow with[!hint!] a
conditional structure
. Recognizing halves of a coordinate system.
Goal: A program that draws squares with colors that depend on their x coordinates
Introduction:
Just like the previous warmup exercise, we've once again given you a template for your code. All code must once again be written inside the function.
squares.py
fromturtleimport*defdraw_square(side,x,y):# write a function that draws a draws# a square with either red or blue fill# depending on the starting x position# being positive (blue) or negative (red)draw_square(40,-100,100)draw_square(60,100,-100)draw_square(100,-50,-20)draw_square(80,90,30)done()
Function Specification:draw_square
Parameters
:
side length (integer)
starting point x coordinate (integer)
starting point y coordinate (integer)
The function draws one square with a fill color that depends on its starting x coordinate being negative or positive For negative x coordinate
value
you must use "red" and for positive you must use "blue".
Main Program:
The code in the given template's
main program
should draw the squares shown in the picture if the function has been implemented correctly. Note: the way you turn when drawing a square affects their placement - your result may not be exactly the same as this picture (these have been drawn by turning right)!
List of Turtle Commands:
No new commands in this one, but all commands are listed here for convenience. You won't need all of them.
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 fillend_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) insidereset()# 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 drawingdown()# puts the pen back down setx(x)# sets the pen's x coordinate to the given valuesety(y)# sets the pen's y coordinate to the given valuecircle(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
Much like any other public organization, the police is having some IT problems. In their desperation, they've approached you with an offer that you cannot refuse: your task is to make a program for calculating the speed of a car, when given distance traveled and time frame. You promptly set forth to implement your herculean task.
Learning goals: Using
placeholders
to insert results and other numbers into
strings
.
Goal: A program that prompts for travel distance and time traveled, and prints the corresponding speed in a neat little output.
Main Program Specification:
The program prompts for two
floats
. The police's ability to input numbers via keyboard has severely deteriorated due to excessive smartphone use so it's best for everyone that we give nice notifications about invalid
inputs
. In case the police accidentally inputs proper floats, the program should print the given numbers and the calculated speed as kilometers per hour. As you can see from the examples, all numbers must be printed with 2 decimal precision. You need to use f strings to achieve this. Using the round function will only leave you biting dust.
If you get style warnings about long lines, you can split a long string into multiple lines simply by partitioning it like this. The f prefix needs to be added to all parts that contain placeholders.
print("This do be a really really really long line of text ""and if you also want to add placeholders it's gonna get even longer...")
You can get an example for exception handling from the the example in this exercise page. This example can be applied here quite directly.
Use Example:
Input distance traveled (m): 50.0
Input elapse time (s): 3.0
The speed of a car traveling 50.00 meters in 3.00 seconds is 60.00 km/h.
Input distance traveled (m): 50.0m
You need less donuts, and more number inputting.
Input distance traveled (m): 50.0
Input elapse time (s): minute
You need less donuts, and more number inputting.
The raw contents of a computer's memory is often presented with hexadecimal numbers, i.e. base 16 numbers where the letters a to f stand for 10 to 15. It's also typical to include leading zeros to show how many bits are stored in memory. One hex digit is 4 bits. This is convenient because the memory slot sizes are always powers of 2, and the smallest possible is 8 bits - i.e. 2 hex digits. This means the size of the memory slot is always easily seen from the number of hex digits. In this exercise we're transforming integers to hexes with the desired amount of leading zeros.
Learning goals: Finding and using more than one
string
method
to achieve the desired string.
Goal: A program that transforms an integer into a hexadecimal number with leading zeros
Introduction:
You can transform a number into a string representation of a hexadecimal number with the hex
function
:
In[1]:hex(452)Out[1]:'0x1c4'
The "0x" is a commonly used prefix to denote a hexadecimal number. It's especially important for numbers that don't happen to contain the the a-f digits.
Function Specification:format_hex
Parameters
:
the integer to convert
number of bits to represent
Returns
:
string representation of the desired hex
The function must convert the number to a hexadecimal representation and then format it to contain the desired amount of hex digits. Because one hex digit is four bits, the desired length can be achieved with integer division. For the result of this function, we don't want the "0x" prefix. It would mess with the leading zeros anyway, so it needs to be removed.
So you have two things to do: remove the prefix and then add leading zeros. Both feats can be achieved with string methods - several of them in fact. The order of doing these is worth considering as well. If the number happens to be too big to be represented with the desired number of bits, just ignore the limitation. The bit count should only be used as a minimum this time. Remember to return the result!
You can test string methods and the execution order in the
Python console
which makes it a lot easier to see what each method returns. In the console you can retrieve the latest result with the _ character. For instance if you'd type this character to the console after the given example, it would give you "0x1c4".
Using integer division is recommended, and best achieved with the //
operator
.
Main Program:
Make a main program that prompts the user for an integer and the amount of bits to use in the representation. If either of the inputs is not an integer, the program gives an error message and doesn't resume. In other words just like the previous exercise, except the numbers are converted to integers instead of floats. After receiving two integers the main program
calls
the function you just implemented and prints its
return value
. The examples below show you the strings for using in prompts and output.
Use Examples:
Give an integer: 5
Give hexadecimal length (number of bits): 16
0005
Give an integer: 349798384653
Give hexadecimal length (number of bits): 64
00000051719bc40d
Give an integer: 255
Give hexadecimal length (number of bits): 8
ff
Give an integer: donkey
Integer please
Give an integer: 252
Give hexadecimal length (number of bits): 2.5
Integer please
And finally a sample that shows what should happen when the number of bits is too small (i.e. nothing special):
Give an integer: 4892
Give hexadecimal length (number of bits): 4
131c
In this exercise you get to program a traditional calculator. It's not the most exciting apparatus in existence but teaches a lot of useful things about processing inputs and program structure.
Learning goals: Using nested
control structures
in a way that all
branches
work as intended. Checking user inputs with
exception
handling.
Goal: A calculator that prompts from an operation and its operands.
Main Program Specification:
The user selects an whether they want to do addition, subtraction, multiplication or division by
inputting
an
operator
. If the user tries to input something else, the program throws them out after printing "Selected operation doesn't exist". After the operator is properly selected, the program prompts for two numbers and prints the operation's result. Unless, of course, the user inputs something else than numbers. In that case they're once again thrown out with the message "I don't think this is a number". Likewise if the user tries to divide with zero, the program gives them an error message "This program can't reach infinity". The program must calculate with
floats
.
In this task it is particularly important to keep in mind what was told about quitting programs at the beginning of the exercise material. Do not use the quit or exit functions!
Use Examples:
Choose operation (+, -, *, /): +
Give 1st number: 12.8
Give 2nd number: no i wont
I don't think this is a number
Choose operation (+, -, *, /): +
Give 1st number: aasisvengaa
I don't think this is a number
Real world voting machines have all sorts of complications and security risks. Luckily we're on a basic course so we can ignore all of those, and simply create a program that counts votes and shows the results. No way anyone can cheat an election with this one.
Learning goals: Reading and updating the contents of a
dictionary
. Using
functions
with
mutable
values.
Goal: A program where user(s) can vote on things, and see the results.
Introduction:
Create two voting dictionaries that can be used to test your functions. Both have "yay", "nay", and "idk" as options, and finally a separate key for votes that were invalid. The second vote has some initial results.
dictionary that contains earlier votes, and where the new vote is stored
The function displays the choices of the vote, and prompts the user to input one of them. Converting the input to lowercase letters is recommended. After getting input from the user, the function adds one to the voted choice. You need to retrieve the old vote count using the input as a
key
, and you also need to
assign
the updated vote count back to the same key. If the user's input is not a valid option in the dictionary, one is added to the "error" key's value instead. Note that this function should not return anything because it's modifying a mutable value.
2nd Function Specification:show_results
Parameters:
dictionary containing the results
The function
prints
the voting results so that the votes received by each choice are presented with bars made of # characters. Each result is on its own line. E.g.
Yay : #####
Nay : ######
Idk : #
Error: ###
Justifying the colons and bars is not required int his exercise.
Main Program:
In your main program you should call the functions for both dictionaries. Do the following things for each dictionary:
print a line about what is being voted
call the vote function
call the show_results function
Please take care that your program only has two functions that are called with different
arguments
. There is no need to do separate functions for each poll! The main program checking assumes you've used the given dictionaries, and that tax renewal is voted first.
Examples:
The example below shows the vote function being called once for each poll.
Should we implement the tax renewal?
Give your vote, the options are:
yay, nay, idk
> errrr
Yay :
Nay :
Idk :
Error: #
Vote Winnie the Pooh for president?
Give your vote, the options are:
yay, nay, idk
> yay
Yay : #############
Nay :
Idk : #####
Error: ####
You only need to do one of these exercises. Each of them is related to one of the course project topics. Choose the one that is in line with your chosen topic. These tasks are not required for minimal course completion.
The purpose of this assignment is to give you your first vector of attack for the Minestomper course project. It teaches you some basic truths about how a 2 dimensional grid works in program code. In addition you learn some useful programming concepts, in particular how to use dictionaries to store messages. Having messages in dictionries is commonly used in programs, like in the checkers in this course.
Learning goals: Comparing numbers in
conditional structures
. You will also learn that the last index of an N length series is not N if the indexing starts from 0. Other topics include: drafting a solution on paper, and how to use data values inside the program while leaving long
strings
for output purposes only.
Goal: A program that prompts for field dimensions and tile coordinates, and gives information about the tile's position in the field.
Introduction:
We'll start by creating a
dictionary
that contains messages for each position category. You need to have this in your code with this exact name.
MESSAGES={"outside":"The tile is outside the field.","corner":"The tile is in the corner of the field.","edge":"The tile is on the edge of the field.","middle":"The tile is in the middle of the field."}
1st function specification:position_in_field
Parameters
:
tile x coordinate (integer)
tile y coordinate (integer)
field width (integer)
field height (integer)
Returns
:
a keyword associated with the position (
string
)
This function returns one of the aforementioned dictionary's
keys
depending on where the tile denoted by x and y coordinates is on the field (defined by width and height given as parameters). The function must examine whether the tile is outside the field, in a corner, or on the edge. If it's none of these, it's in the middle. To retiterate, the function returns one of the dictionary's keys, e.g. if the tile is outside, the return statement should be return"outside".
Note: The origin of the field coordinates is (0, 0). Look at the examples carefully to see how this affects the results. Also, bear in mind that each pair of coordinates is a tile. Draw a field on paper and write numbers along each edge - this way you can easily see how coordinates relate to positions in the field.
2nd function specification:print_position
Parameters:
a keyword that denotes the position (string)
This function prints the tile's position in human-readable form. In other words it says whether the tile is outside, in the corner, on the edge or in the middle. The printout must be retrieved from the dictionary using the function's
parameter
as a
key
. This function should actually be just one line of code if you recall that
variables
can be used as dictionary keys. Oh and please take the instruction about printing from the dictionary seriously - the checker will change the messages between tests.
This function is not allowed to call the previous function!
Main Program:
Implement a program that prompts the user for field width and height, and after these, horizontal and vertical coordinates (i.e. x and y). However if the field size is too small it gives an error message (see examples below) and stops execution immediately (like in the calcunator earlier). After prompting for coordinates, the program prints a message indicating the chosen tile's location in the field. This is best achieved with the functions you just implemented: the first one returns the location keyword, and the second one prints the corresponding message.
All
strings
for prompts and prints can be found in the examples below.
Use Examples:
Input field width: 0
Input field height: 0
You can't fit a single tile on a field that small!
Input field width: -6
Input field height: 999
You can't fit a single tile on a field that small!
Input field width: 1
Input field height: 1
Input x coordinate: 0
Input y coordinate: 0
The tile is in the corner of the field.
Input field width: 5
Input field height: 8
Input x coordinate: 4
Input y coordinate: 3
The tile is on the edge of the field.
Input field width: 13
Input field height: 7
Input x coordinate: 2
Input y coordinate: 2
The tile is in the middle of the field.
Input field width: 4
Input field height: 4
Input x coordinate: 4
Input y coordinate: 4
The tile is outside the field.
The solution to this exercise might come in handy in the Spectral Matters course project. You are tasked with writing a program that calculates and prints the equation of a line, with all edge cases covered.
Learning goals: Comparing numbers in
conditional structures
. Controlling program flow to make correct statements about the results. Calculating the equation of a line.
Goal: Program that calculates the equation of a line and prints it.
Function specification:calculate_parameters
Parameters
:
x coordinate of the first point (float)
y coordinate of the first point (float)
x coordinate of the second point (float)
y coordinate of the second point (float)
Returns
:
line's slope (float)
line's y intercept (float)
Use the following equations for the slope and the y intercept:
from the user, and let them know the equation for the line that goes through those points if it's possible to calculate one. In addition the program should recognize two special cases: the user inputting the same point twice, and the user inputting a vertical line. To keep this at least a bit simple, user inputs are not checked this time. The program does have to handle
floats
though, and also print them neatly rounded to three decimal precision.
The best way to go about implementing the program is to use nested try and if structures. The easiest way to know whether it's possible to calculate the equation is to call the function inside a try
branch
. It gives some
exception
if it can't do its calculations. There is also a small catch regarding negative intercept: you must print the minus sign as an operator in the equation - you can't blindly throw the intercept into a format! It should also be completely left out if it's zero.
As usual, you can see the
strings
from the examples below.
Use Examples:
Input x coordinate of the first point: 0
Input y coordinate of the first point: 0
Input x coordinate of the second point: 0
Input y coordinate of the second point: 0
Sorry to break it to you but these points are the same.
Input x coordinate of the first point: -1
Input y coordinate of the first point: 100
Input x coordinate of the second point: -1
Input y coordinate of the second point: -100
The line is vertical, it doesn't have an equation.
Input x coordinate of the first point: 2
Input y coordinate of the first point: 3.1
Input x coordinate of the second point: 6.7
Input y coordinate of the second point: 8.51
Line equation: y = 1.151x + 0.798
Input x coordinate of the first point: -8
Input y coordinate of the first point: 4.5
Input x coordinate of the second point: -5
Input y coordinate of the second point: 4.5
Line equation: y = 0.000x + 4.500
Input x coordinate of the first point: 3.141457
Input y coordinate of the first point: -6.12433
Input x coordinate of the second point: 0
Input y coordinate of the second point: 50
Line equation: y = -17.866x + 50.000
Input x coordinate of the first point: 5.76
Input y coordinate of the first point: 4.6
Input x coordinate of the second point: 2
Input y coordinate of the second point: -5
Line equation: y = 2.553x - 10.106
Input x coordinate of the first point: 2
Input y coordinate of the first point: 2
Input x coordinate of the second point: 4
Input y coordinate of the second point: 4
Line equation: y = 1.000x
As there is not universal agreement in how to represent certain things, you can sometimes run into a situation where different tools have different presentations for the same thing. In this task we're looking at a single box from two different perspectives. This problem relates particularly to the image cutting project work as one of the tools we use there uses a coordinate system where the origin as at the bottom left corner while another has the origin at the top left. That, and they also have a different way to represent a rectangle.
Learning goals: Reading and updating contents of a dictionary. Coordinate system reversion.
Goal: A program where the user can move existing boxes and see where they end up in a reversed coordinate system.
In order to test the functions you can define a couple of boxes in your program.
This function informs the user about the current location of the box (in coordinate system A terms), and prompts for changes to its position (x and y coordinates). It will then update the dictionary by the changed amount. This function should not return anything as it updates an existing dictionary.
2nd function specification:convert_representation
Parameters:
dictionary that describes a box
the height of the area that contains the box (integer)
Returns
:
x coordinate of the box's left edge
x coordinate of the box's right edge
y coordinate of the box's top edge
y coordinate of the box's bottom edge
The diagram below shows the same box in two different coordinate systems, with two different representations. The origin of coordinate system A is in the bottom left corner and y axis values grow upward. This coordinate system is often used in mathematics, based on the notion that number growing means up. The box is represented in the same way as in the dictionaries by specifying its bottom left coordinates, its width, and its height.
The origin in coordinate system B is in the top left corner, and y axis values grow downward. This coordinate system is commonly used by computer programs, and is based on the order in which humans would read text from the screen. In addition to different origin, the box is now defined by the x coordinates of its left and right edges, and the y coordinates of its top and bottom edges. Both images also include a maximum value for y, 160. This number acts as a reference value that is needed in order to have the box be in the same place visually.
The purpose of this function is to take a box represented in coordinate system A, and return the values in coordinate system B that would place the box in the same spot between the y axis and the maximum y value.
Main Program:
Make a main program that calls both functions for each box. For each box the program should print the coordinate system B coordinates returned by the second function.
In the last exercises we made a function that converts polar coordinates to cartesian coordinates. We also said that this is done frequently with objects that move on the screen. This time we're getting a bit closer to practice. This exercise is about updating the position of a moving object on an (x, y) plane, based on its heading and velocity. A convenient way to describe an object with multiple properties is to use a dictionary. While this exercise doesn't particularly qualify as a game yet, it makes you implement a mechanism that is repeated frequently enough.
Learning goals: Reading and updating the contents of a
dictionary
. Using
functions
with
mutable
objects.
Goal: Bunch of functions that prompt the user for heading and velocity and update the position of an object based on them.
Introduction:
Fetch your solution for A Sinful Function from the previous set of exercises, and copy the convert_to_xy function from it. You should not change this function! You should also create a couple of dictionaries in your
main program
so that you can test your functions. These contain the
This function prints a character's position and then prompts the user to
input
heading as degrees and speed (as arbitrary units). The
strings
to be used in printing and prompting can be found from the use examples at the end. Both inputs are taken as floats and assigned as values for the corresponding keys in the dictionary. Please note that the function returns nothing. It doesn't need to because it modifies a
mutable
object. Also, remember to use the function's parameter when accessing the dictionary.
2nd function specification:update_position
Parameters
:
dictionary with the above key-value pairs
This function calculates a new position for a character based on the heading and speed found from a dictionary. These two values can actually be interpreted as polar coordinates. Gee, was there a function to convert this into how much the cartesian coordinates change...? It may have been that such a function takes the angle as radians, and the dictionary has it as degrees. Rumor has it that the math module can help with that.
Please note that when the function is tested, the character's starting point won't always be (0, 0). Your function needs to, well, function, even when the character starts from another point. Because we calculated the change of coordinates from the heading and speed, the change of each coordinate needs to be added to the position values in the character dictionary (i.e. you need to replace them with updated values).This function also modifies a mutable object, so it should not return anything.
Main Program
Make a main program that prompts moves from two players, both of whom have their own character on the playing field. It prints whose turn it is, and then calls both functions to process that player's character dictionary. Finally it prints the new position of the character, as shown in the examples. The process is repeated for the second player. By doing this you can make sure that your functions work properly when given different dictionaries.
Use Examples:
Player 1's turn
Character is currently at (0, 0)
Give heading as degrees: 180
Give speed: 10
New position: (-10, 0)
Player 2's turn
Character is currently at (50, 50)
Give heading as degrees: 45
Give speed: 5
New position: (54, 54)
Player 1's turn
Character is currently at (0, 0)
Give heading as degrees: 30
Give speed: -4
New position: (-3, -2)
Player 2's turn
Character is currently at (50, 50)
Give heading as degrees: 210
Give speed: 4
New position: (47, 48)
Hints
Messages
Give feedback on this content
Was this task useful for learning?
Comments about the task?
Give feedback on this content
Comments about these exercises
?
Description
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.
Absolute path to the downloads folder in windows is typically something like this:
C:\Users\donkey\Downloads\
and in Unix based systems:
/home/donkey/Downloads
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).
Description
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.
Alustaminen on ihan tavallinen muuttujaan sijoitus:
nimi="Tomomi"
Yleisemmin alustamisesta puhutaan, kun halutaan alustaa esim. tyhjä lista sitä varten, että sinne myöhemmin lisätään alkioita:
Yllä kuvatun toiminallisuuden toteuttaminen ilman, että lista alustetaan ennen silmukkaa, olisi hyvin hankalaa.
Description
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.
Alla funktiokutsu, jossa on kaksi argumenttia: muuttuja tulos sekä lukuarvo 2
round(tulos,2)
Round-funktion helpin avulla voimme nähdä, että nämä arvot sijoittuvat parametreihin number ja ndigits (joista jälkimmäinen on valinnainen)
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.
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.
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.
We are cutting a few corners when saying that and and or return boolean values. Full disclosure: and returns either the first operand that equals False, or - if both equal True - the latter operand; whereas or return the first operand that equals True, or - if both equal False - the latter operand. You can inspect this behavior in the Python console. For the purposes of this course this makes no difference because we're mostly using the results of comparison operators are only used in conditional statements that don't care if a value is actually True/False or just one that is equivalent to one of them.
You don't actually have to limit yourself to using these operators in conditional statements:
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.
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.
The last terminal incarnation of the example program in the material was done like this
python collection.py collection.json copy.json
Inside the program the arguments were read with this function:
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.
Description
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.
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.
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.
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.
In this game related example the height and width of a map are defined as constants. Using the numbers 800 and 400 in code would make it less clear what they are. In addition if these values are needed elsewhere in the program, they only need to be changed here:
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 defprompt_length(question,maximum=10): function definition, the maximum parameter has been made optional by giving it the default value of 10.
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.
Example dictionary definition:
Esimerkki sanakirjan määrittelystä:
Updating values and creating new key-value pairs is also done with square braces:
In[1]:course={...:"name":"Elementary Programming",...:"feedback":5...:}In[2]:course["feedback"]=1In[3]:course["comment"]="Can't deal with this sober"In[4]:courseOut[4]:{'name':'Elementary Programming','feedback':1,'comment':"Can't deal with this sober"}
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.
Description
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!
File "unitvector.py", line 1defcalculate_unit_vector(x0,y0,x1,y1)^SyntaxError: invalid syntax
For example this error message is here to inform about a syntax error in code file unitvector.py on its very first line. The syntax error in this case would mean that a colon was missing from the end of the function definition.
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 is a scenario in programming where the program cannot proceed as instructed. Exceptions have a type (e.g. TypeError) that can be used in handling the exception within the program. Type can also be useful when trying to solve the issue if it is not intended. In most cases exceptions also come with a message that gives more details about what caused the issue. In Python exceptions are handled with try-except structures.
The exception message given by the interpreter is usually something like this
This program calculates the volume and area of a ball when its circumference is known
Input ball circumference: 23
Traceback (most recent call last):
File "ball.py", line 14, in
radius = calculate_radius(circumference)
File "ball.py", line 10, in calculate_radius
return circumference / (PI * 2)
TypeError: unsupported operand type(s) for /: 'str' and 'float'
Where the last line tells which type of exception happened, and potentially additional information about the problem.
Exception is the base class of most common exceptions. We also call it the Pokémon exception because if you use it in a try-except structure it will catch all the exceptions. In most cases this is not a good thing. It makes interpreting problem situations more difficult for both the user, and you, the developer. The latter is due to the fact that it will also catch any mistakes you made in your code, and you won't get any useful information when the program isn't behaving correctly.
Execution or running means going through a program or code snippet so that the instructions written within are carried out by the computer. Python interpreter executes code one statement at a time. While this is ongoing the program is "running". Execution ends when there is no more code to run, there's an unrecoverable error or when the program ends itself.
File extension is the part of the file's name that is on the right side of the last period in the name. They are commonly used for indicating file types. Image files for instance often have .png or .jpg as their extension. Python code files usually have .py at the end (e.g. donkeyswings.py).
File handle is a special object that Python uses to refer to an opened file. Most important note is that the handle is not the same as the file's contents - the handle can be used to read the contents, or write to the file. A file handle is obtained with the open function with the file's location (path) and the opening as arguments. E.g. withopen("donkey.txt","r")assomefile: 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.
Description
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.
Any integer or string that represents a float can be converted to a float with the float function:
The format method of strings is a powerful way in Python to insert values of variables into text that is either printed or saved to a file. Formatting works by defining placeholders in strings (e.g. {:.2f}) for marking spots where the format method arguments will be placed. Example: "Interval between donkey's ears is {:.2f}".format(measurement).
Note: format is an older way for general string formatting. Using f strings is a more modern way. However, there are still uses for the good old format method too.
In[1]:print("Hi, your name is {} and in your previous life you were a {}.".format("norusu-kun","walrus")Hi,yournameisnorusu-kunandinyourpreviouslifeyouwereawalrus.
Using indices in choosing the parameters. Typically useful when the same argument is used multiple times in the template string.
In[1]:print("Apples {1}{0} and bananas {2}{0}, {3}{0} in total.".format("kg",2,3,5)Apples2kgandbananas3kg,5kgintotal
It's even clearer when you use named placeholders
In[1]:print("Apples {apples}{unit} and bananas {bananas}{unit}, {total}{unit} in total.".format(...:apples=2,bananas=3,total=5,unit="kg")Apples2kgandbananas3kg,5kgintotal
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.
Below is an example of a function that's typical for a game character moving within a closed region. The boundaries of the region have been defined as constants.
WIDTH=800HEIGHT=400defcalculate_new_position(x,y,x_direction,y_direction,speed):""" Calculates the position of a character based on its current position, directional vector and speed. The character cannot move out of bounds. Returns the character's new position. """x=max(0,min(x+x_direction*speed,WIDTH))y=max(0,min(y+y_direction*speed,HEIGHT))returnx,y
The statements used inside the function are complex enough that it's better to separate them from the rest of the code. In the rest of the code a character's position would be update by calling this function:
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.
The code snippet displayable_result=round(15.234589,2) has a function call where the round function is called with two arguments: 15.234589 and 2. After exiting, the function call is replaced by its return value, 15.23. Therefore the variable will ultimately be assigned the value 15.23.
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).
WIDTH=800HEIGHT=400defcalculate_new_position(x,y,x_direction,y_direction,speed):""" Calculates the position of a character based on its current position, directional vector and speed. The character cannot move out of bounds. Returns the character's new position. """x=max(0,min(x+x_direction*speed,WIDTH))y=max(0,min(y+y_direction*speed,HEIGHT))returnx,y
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.
fori,animalinenumerate(animals):
Although we don't use generators on the course, the enumerate object works like a generator. However, Python's documentation uses the separate "enumerate object" name for it.
Description
Esimerkit
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ä.
Pythonissa kaikki pääohjelmatason muuttujat ovat globaalsti luettavissa. Jotta muuttujaan voidaan sijoittaa globaalisti, se täytyy erikseen määritellä globaaliksi ennen muokkausta:
inventaario-listaa ei tarvitse erikseen merkitä globaaliksi, koska siihen ei kirjoiteta. Sen sijaan jos rivi globaln jätetään pois, tuloksena on UnboundLocalError.
Joskus on tarpeen jakaa ohjelman sisällä tietoa globaalisti. Tällä kurssilla tästä esimerkkinä on ohjelman tilan välittäminen käsittelijäfunktioille. Globaalien muuttujien sijaan ohjelmalle voidaan rakentaa tilasanakirja, jossa sijaitsevat kaikki arvot, joita tarvitaan käsittelijäfunktioiden sisällä:
Näin toimittaessa globaalisti käytetään vain yhtä muuttujaa usean sijaan. Lisäksi sanakirjan esittely ohjelman alussa kertoo kätevästi, mitkä tiedot ovat osa ohjelman tilaa.
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.
Hypystä (engl. jump) puhuttaessa tarkoitetaan ohjausrakenteen aiheuttamaa siirtymistä, jonka jälkeen ohjelman suoritus jatkuukin jostain muualta kuin seuraavalta koodiriviltä.
matka=10ifmatka>=50:# Ehtolause on epätosi, joten…print("Vielä on pitkä matka.")# …ohjelman suoritus hyppää tänne.
Description
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.
Naming conventions define what kinds of identifiers can be given to things in the code. In most programming languages acceptable identifiers consist of lower and upper case letters, numbers and underscores. In addition identifiers should be descriptive of the things they represent. E.g. a good name for an object's width would be width whereas a would be bad. Languages also often have style guides about how identifiers should be written.
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.
Description
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.
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.
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.
whileTrue:# Code that's repeated infinitely
The normal way to build an infinite loop (on purpose) in Python is to make a while loop that has True as its condition.
Typically a loop like this contains some kind of mechanism that can be used to eventually exit it. Most commonly there's a branch with either break or return somewhere inside.
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.
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.
A function's interface is defined by its def and return statements
This function's incoming interface is that it needs to be given a single argument - a ball's circumference as a number. Its outgoing interface is that it return two values: the ball's area and its volume.
Description
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.
On the following line
animals=["donkey","dog","moose"]
the values "donkey", "dog" and "moose" are items in the animals list. Furthermore
Iteration is a concept related to loops. One iteration of a loop means executing the code inside the loop once.
Description
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.
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.
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.
Alla on pätkä piiristo-moduulin yhdestä funktiosta (loput voit katsoa moduulin koodista)
def_piirra_pariton_rinnankytkenta(piiri,komponentit,pituusyksikko):""" Piirtää rinnankytkennän, jossa on pariton määrä komponentteja. Kytkentä piirretään piirtokursorin nykyiseen sijaintiin, ja piirron päätteeks kursorin sijainti päivitetään. ... """# Jaetaan komponentit kahteen puoliskoon ja keskikomponenttiinkeski=len(komponentit)//2vasen=komponentit[:keski]oikea=komponentit[keski+1:]piiri.add(e.DOT)# tallennetaan keskilinjan sijaintipiiri.push()# piirretään vasemman puolen komponentitfori,kompinenumerate(vasen[::-1]):piiri.add(e.LINE,d="left",l=1)# ...
Huomaa miten funktion toiminta on kuvattu dokumenttimerkkijonossa, ja miten kommenteilla on kerrottu mitä missäkin vaiheessa tehdään.
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.
Description
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: foranimalinanimals: where animal is the loop variable. If the sequence contains tuples (or lists), a for loop can also have multiple loop variables: forstudent,gradeingrading:. 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.
Description
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.
Merkkijonon määrittely:
nimi="kapteeni mursuviiksi"nimi='norusu-kun'
monirivisen merkkijonon määrittely:
vitsi="""Nalle Puh oli palailemassa koodaus-allnighterista. Puolivälissä matkaa hän huomasi olevansa Ihaan pihalla."""
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.
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".
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()
Muuntumattomuus tarkoittaa pääasiassa sitä, että kaikki operaatiot palauttavat kopion:
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.
Description
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.
Ykkösmateriaalissa esiintyvässä tehtävässä 0.8 on taikaluku:
koko=40*0.8nopeus=10*0.8kantama=200*0.8
Ratkaisuksi tarjotaan vakion esittelyä
SKAALAUS=0.8
huomaa miten se, että vakiolle annetaan nimi, kertoo heti enemmän siitä mikä tämä mystinen 0.8 ylipäätään on.
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.
Keskeytykset ovat oleellinen asiasisältö Laiteläheinen ohjelmointi - ja Käyttöjärjestelmät-kursseilla. Näppäimistökeskeytys on itse asiassa tietty UNIX-signaali nimeltä SIGINT, joka on mahdollista lähettää prosessille ”ilman käsiä”:
Laitetaan ikisilmukka pyörimään terminaalissa avattuun Python-tulkkiin.
>>> whileTrue:... pass...
Avataan toinen terminaali, selvitetään Python-tulkin prosessin numero ja lähetetään signaali:
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.
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.
Operation is a term used for anything carried out by an operator in the code. Mathematical operations are typical examples. An operation consists of an operator and one or two operands. For instance 5 + 5 is an operation.
Operator is a name for symbols that define an operation in mathematics and programming. Operators always appear with at least one operand, but often two. An example of an operator would be + symbol which denotes an addition operation.
An argument in a function call is an optional argument if its corresponding parameter has been given a default value. This means that it's possible to call the function without giving that argument. If there are multiple optional arguments for a function, they are often given using keyword arguments.
Parameter is a variable defined along with a function. They are variables that are assigned values from arguments when the function is called. In other words when values are transferred in a function call, they are called parameters from the function's point of view. E.g. in defprompt_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.
Description
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.
An absolute path in Windows (note: Windows uses backslash, but Python also accepts slash)
Relative path when the program has been run in the Documents folder of the Windows example:
Programming/donkeygotchi.py
Description
Additional formatting
Placeholder is by general definition a way to mark a spot that will be replaced by something else later. In this course they are primarily used with string formatting. A placeholder within an formatting string is marked with curly braces (f"Hi {name}"). Placeholders in strings can also contain additional formatting specifiers like setting the number of decimals to show (f"Donkeys have {average:.2f} legs on average"). When a placeholder is resolved, it is replaced by the value of the variable or statement inside the curly braces.
Format specification in placeholders can also be used to add leading zeros
In[1]:print(f"Serial number {12:04}")Serialnumber0012
or set the number of decimals shown:
In[1]:importmathIn[2]:print(f"Approx. value of pi: {math.pi:.4f}")Approx.valueofpi:3.1416
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.
Python mahdollistaa vielä joustavamman poikkeusten käsittelyn try-except-rakenteen else- ja finally-lohkoilla. Yhteenvetona:
try-lohkon koodia suoritetaan siihen saakka, kunnes se loppuu, tai kun try-lohkon koodi aiheuttaa poikkeuksen.
except-lohkon koodi suoritetaan ainoastaan, jos try-lohkon koodissa törmätään except-lohkolle määriteltyyn poikkeukseen.
else-lohko suoritetaan vain siinä tapauksessa, että try-lohko suoritettiin onnistuneesti ilman poikkeuksia.
finally-lohko suoritetaan lopuksi aina riippumatta siitä, onnistuiko try-lohkon koodi vai aiheuttiko se poikkeuksen.
Precedence, of math fame, defines in which order various operations in a statement are resolved.
result=10+2*(2+3)
The result of this statement is 20 because the sum of 2 and 3 is resolved first, followed by multiplying the result by 2, and finally adding the multiplication result to 10. In this example the highest precedence is held by the operation in braces, followed by multiplication, and then finally addition.
Precedence defines the execution order of instructions or operations on a line of code. Operations of different type have different precedence in execution order. These can be found from the link below. Operations with same precedence are executed from left to right. Like in mathematics, the order can be changed by using parentheses.
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.
Printing without newline (shown in default console where the difference is more apparent)
>>> print("donkey",end="")donkey>>>
Printing multiple values in one line using separator other than space:
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.
Description
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.
You know that you have successfully started IPython if you see something like this:
Python 3.7.0 (default, May 7 2019, 09:44:49)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
On the contrary if you something like below, you are in the vanilla Python console:
Python 3.7.0 (default, May 7 2019, 09:44:49)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
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.
Description
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.
Description
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.
In the example below the value of the distance variable is returned
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 returnTrue 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.
Description
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.
In this example x is in the global scope and therefore its value can be accessed inside the function. Meanwhile variable is only accessible in the function's scope which means that while it's possible to define another_variable that depends on it inside the same function. However, because it's only within that function's scope, the print call in the main program will cause a NameError
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.
The example file in the first exercise of 4. exercises
A sequence is any value in Python that is a series of things - for instance, string, list and tuple are all sequences.
Description
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.
In[1]:doggos=["doggo","woofer","doge","floofer","pupper"]In[2]:doggos[:2]Out[2]:['doggo','woofer']In[3]:doggos[2:3]Out[3]:['doge']In[4]:doggos[3:]Out[4]:['floofer','pupper']In[5]:doggos[2:-1]Out[5]:['doge','floofer']In[6]:doggos[4:10]# note going outside the listOut[6]:['pupper]
Slices can also have a third parameter which can be used for skipping over items, or even make a reversal for the list:
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.
Description
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.
Below is an example of a stub function that already has proper parameters, and returns a value of the correct type
defchoose_values(data,start,end):return[]
This function can be called in the program and its return value used without causing exceptions - it just doesn't really do anything.
Syntax is the grammar of code. It defines what kind of text counts as valid Python. If code doesn't conform to the correct syntax, it cannot be executed. Syntax also informs a programmer about the correct formatting for each stement in the programming language.
Syntax error is an exception that happens when the Python interpreter inspects a code file before executing it and notices something broken in there, i.e. code that is written incorrectly. A code with syntax errors is not run at all.
One common syntax error is unbalanced parentheses. This results in a strange error message in the sense that Python reports the next line as the cause of the error. Remember to check previous lines as well when you receive strange syntax errors!
Takaisinkutsu (engl. callback) on yleinen ohjelmoinnissa käytetty menetelmä, jossa funktio ottaa parametrin kautta vastaan funktion kutsuttavakseen heti (synkroniset takaisinkutsut) tai joskus tulevaisuudessa (asynkroniset takaisinkutsut). Nimensä menetelmä on saanut soittopyynnöstä: kutsuttavaa funktiota, jolle jokin funktio välitetään argumenttina, ”pyydetään” kutsumaan tätä annettua funktiota. Pythonissa listojen sort()-metodin key-parametri on esimerkki callback-funktioiden käytöstä. Usein käyttöliittymiä toteutettaessa käyttöliittymäelementteihin kytketään callback-funktioita.
Terminal, command line, command prompt and shell' are different names to the text based interace of an operating system. It is used for text-based operating system commands and for running terminal programs. On this course we mostly move around with cd (change directory) and use ipython command to run code files and start the Python console.
In Windows you can open the terminal by typing cmd to the start menu search
In Mac OS X you can start the terminal by typing terminal to Finder
In Linux you can open the terminal from the desktop by pressing Ctrl + Alt + T or by typing terminal to the search
Testaamalla eli kokeilemalla (engl. test) selvitetään, toimivatko hartaasti näppäillyt koodirivit halutulla tavalla. Testejä suorittamalla siis etsitään koodista mahdollisia ohjelmointivirheitä. Ohjelmien testaaminen on jopa niin olennaista, että joidenkin alan työntekijöiden tehtävänä on ainoastaan automatisoitujen testien ohjelmointi. Lovelace-järjestelmän tarkistimet testaavat järjestelmään lähetetyt koodit.
Generally text file is any file that can be read with a text editor. In this course's context we use text file to refer to files that are handled as text inside Python. We do this to separate them from code files that are run with Python. Text files are used in this course to store data between runs of the program.
Tosi (engl. true) on toinen kahdesta mahdollisesta totuusarvosta ja toisen, eli epätoden, vastakohta. Sitä voidaan pitää lopputuloksena loogisissa ja vertailuoperaatorioissa, jotka pitävät paikkansa. Esimerkiksi vertailuoperaatio 5>4 pitää paikkansa, joten kyseinen operaatio evaluoituu todeksi. Pythonissa totta merkitään avainsanalla True.
Description
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 program → f → g.
Alla traceback, joka syntyy jos käyttäjän virheellistä syötettä ei käsiteltäisi oikein kokoelma-ohjelmassa:
Kappaleiden lukumäärä: 0.5
Traceback (most recent call last):
File "kokoelma.py", line 238, in
lisaa(kokoelma)
File "kokoelma.py", line 154, in lisaa
n = kysy_luku("Kappaleiden lukumäärä: ")
File "kokoelma.py", line 44, in kysy_luku
luku = int(input(kysymys))
ValueError: invalid literal for int() with base 10: '0.5'
Huomaa, että virheen aiheuttanut rivi on alimpana, ja sen yläpuolella siihen pääohjelmasta johtaneet funktiokutsut.
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.
You can use the tuple function to freeze a list into a tuple:
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.
Below are some common type conversions
In[1]:int(input("Give an integer: ))Giveaninteger:4Out[1]:4In[2]:float(4)Out[2]:4.0In[3]:float("1e3")Out[3]:1000.0In[4]:str(5.0)Out[4]:'5.0'In[5]:int(2.7)Out[5]:2In[6]:tuple([1,2,3])Out[6]:(1,2,3)
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.
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ä!
Arvon tyypin voi saada esiin type-funktiolla:
>>> type(3+3j)<class 'complex'>
jos halutaan tarkistaa onko arvo jotain tyyppiä (kuten tarkistimissa tehdään säännöllisesti), tähän käytetään yleensä isinstance-funktiota. Sille voidaan antaa myös useita tyyppejä monikkona yhden sijaan.
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.
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.
whileTrue:value=input("Give a donkey's tail length (leave empty to quit): ")ifnotvalue:break
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.
One common use case is in a loop that processes a list and for some reason or another needs to skip certain values:
forvalueinresults:ifvalue==0:continue# do something to the value
Note: the above is equal to
forvalueinresults:ifvalue!=0:# do something to the value
Usually continue is only used when the processing is complex, and the latter solution would introduce too many nested structures to the code.
Description
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: fori,characterinenumerate(moomin_valley):.
Enumeration is usually used in for loops when both the index and the item are needed:
f(ormat) string is a special string that is used for inserting values from variables or simple clauses inside a piece of text. This is also called string interpolation in programming terminology. This kind of a string is marked by prefixing it with a lowercase f. You can include placeholders inside the string by using curly braces, and writing variable names or clauses inside them.
Example: f"Interval between donkey's ears is {measurement:.2f} inches" (assuming that a variable named measurement has been definied previously)
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 foritemincollection: where item would be the name of the loop variable, and collection would be the data structure that is being iterated over.
In Python modules are "activated" by import statements. In normal use (e.g. importmath) 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: frommathimportceil. Modules can also be renamed on import: importmathasm.
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.
Tyypillinen while-silmukka:
summa=0whilesumma<21:summa+=random.randint(1,10)
toisenlainen tyypillinen while-silmukka, joka on ikuinen
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. withopen("donkey.txt")assomefile:. 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.
withopen("results.txt")asresults:# the file is now open, and we can read its contentsresult_rows=results.readlines()# the file is now closed, but we can still access the contents# because they were saved to program memory earlierforrowinresult_rows:print(", ".join(row))# however we can no longer do anything with file handle in results variableresults.read()