Topic 2 - Intro To Programming Flashcards
In order to create a code, what is the general algorithm you need to follow? (5 steps)
What steps do you need to return to if the code has an error?
- Gain necessary knowledge of the problem domain
- Analyze the problem, breaking it into pieces and repeat as necessary.
- Synthesize a solution
- Run the program
- Validate program results and correct problems that are identified.
If the code has an error, then you must go back to step 1,2 and 3 because the answer did not match with what we desired and so knowledge of problem domain may not match with this either.
What are the two common features of all programming languages?
- They allow us to control the behaviour of a computer
- They have defined syntactic and semantic rules.
-syntactic means the structure of a valid statement and semantic is the meaning of the statement. So does the combination of words that are used actually make sense?
Levels of abstraction, how does this determine how specific we need to be when writing a code?
In human language and high level programming languages we can be very general and say computer 3 + 5. We don’t have to explicitly say to say it out loud because people will automatically.
But low level programming languages and machine languages need more specific input such as computer this and then print it. And we have to indicate if it is a string or an integer or float, and we have to indicate how many decimals to round it to if needed.
What level is python?
A high level general purpose programming language that has helpful error messages and is easier to use in relation to its complexity.
How are computer programs stored? How is it run by the computer?
they are stored as a .py which can be viewed as a pdf of the code or can be run by a python interpreter to actually get output.
What is a variable in a computer program? What are the rules for a legal variable name? (6)
A variable is a named location in the memory of the computer. Try to name the variable for what it is so you immediately know what it holds.
This variable holds a value that can be brought back at any point in the code, and is very beneficial when repeating that value because it gives an easy way to change the value of that variable.
Legal variable names should:
-be meaningful
-must begin with a letter or an underscore (not a number)
-may contain a mixture of letters, numbers and underscores
-must not be a reserved word
-shouldn’t be a name already commonly used for a another purpose (such as min and max)
-shouldn’t be in all caps because that means you can’t change it ever again.
Example: Write a python program that converts pressure from kilopascals to atmospheres to pounds per square inch to millimeters of mercury.
What are the steps that should be taken in solving this?
- Make sure you have the necessary information such as:
What are the conversion factors between these units? - Write out the steps for how you would solve this problem using the computer:
a) Read a number of kPa from Joe user and store it because we need some input.
b) Preform the conversions to other pressure units using mathematical operations.
c) Display/report the results.
How does variable assignment work? Can an assignment include other variables in it? Like can you assign a variable to an expression with other variables?
Variable assignment works by placing the variable to the left and then putting a space and ONE equal sign. Then another space and you can put the value or expression that you want to assign that variable to.
The equal sign is called the assignment operator, and is always to the right of the variable and to the left of the arbitrarily complex expression.
So YES you can put other variables in the assignment as long as you define those variables somewhere before that assignment operator.
X = 4
You are saying that any time below this in the code, if you enter x the program will automatically plug in 4. Unless you put another line below where x = 5, then all x values from then on below will be 5.
What is a function?
A function is pre-existing code that performs useful tasks for us. It can be called by using its name, followed by round brackets that are used by the function, and these function results can be to the right of the variable assignment.
How do we get input? What does the input function do?
To get input, you put the input function down, and this will cause the program to wait until the user enters that input. You put input and then brackets, and then inside usually a statement telling the user what to input.
Input reads characters typed by the user as text, so if you want it to be read as a numerical value then you have to do float(input()) or int(input()), depending on the type of value you want it to be considered as. Always put int or float before the input. This is because things inside the bracket are called performed first, so the input is taken in and then converted to int or float. If you put float first then it wouldn’t assign input to the value entered and it would be undefined.
Float is assumed to be the same as a real number but is only an approximation because you have infinite real numbers to represent.
How do we report the output that we generate?
We use a print statement! You write in a quotations words that you want the code to directly print out. Then if you want a variable that you assigned a value to to be a part of that print statement, you end the quotations and then you out a comma and that variable.
So for the dog years example, you would do:
print(“I can’t believe”, name, “is”, age, “years old!”, “That is”, dogage, “in dog years!”) So essentially you are just reporting the variables and then putting in strings to connect those variables and make them make sense.
So essentially if you want to use numbers, text and variables you just have to separate them with commas. But if in quotes, then a string will be printed exactly as is stated within those quotes.
If you write print and then some word without quotations, python will look for the variable attached to that word. If there is none, then it will not be able to execute.
What order does a code always run in? If you change the assignment of a variable below a line where it was executing another assignment, will it change that above line?
A code always runs from top to bottom, so you have to ensure that the code has all the information it needs to do this.
If you change a variable assignment below, like say x=3 instead of x=4 like it was above, all the above lines will carry it out as x=4. But as soon as you get to the line where it is x=3, any x in any below lines will be carried out as 3 instead.
What does CPU stand for? CPU can only execute __________ __________ instructions, it can’t execute ____________ ___________ statements directly. So what approach does python use to convert this? What are the two possible options?
CPU stands for the central processing unit of a computer. CPU’s can only execute machine language instructions, not the programming language statements directly.
So there are two options to convert this:
1. Compile the program into machine language instructions (binary code, so each digit in the binary represents one bit and each character is represented by multiple bits. By having a certain combination of 0s and 1s attached to certain characters, the computer can understand what the code is asking it to do.
2. This approach is taken by python. The CPU uses a virtual machine that reads the program and performs the tasks required to run it. So it essentially is the middle man between the program and python who cant read the information, or in other words is an interpreter. However, it comes at a processing cost.
What are comments used for? How do you write a comment?
What do you always do at the top of a file?
What is a useful first step in creating a code?
Comments are used to organize your code and indicate to readers what parts of your code are carrying out what functions.
To write a comment, you put a hashtag symbol at the front of the line, and it will be completely ignored by the computer.
These lines should explain how or why something is being written, and they should add value. If the line says background(pink), then you don’t need to write a comment because it is already obvious what this means.
At the top of a file, you put a comment explaining what this program will do.
When beginning to create your code, add a comment for each step you want to take, and then fill in the space between each comment to carry out these desires.
What is a magic number? Why are they an issue? What can be done to counteract this issue?
A magic number is an unnamed and or poorly documented numeric constant without obvious meaning. So it is just a number that is used again and again but we are not sure why. Due to human error in entering these numbers, this could be an issue because you could make one error in entering the number and it could screw up the whole code. Plus, having numbers repeated like this could make it hard to understand the code and make it hard to detect errors because you have to go through the whole code to look for those errors.
To counteract this issue, we can assign a variable name to the values (especially conversion values) so that we only have to write out the number once and don’t have to worry about errors in writing those numbers out.
This also makes it easy to change the value of those conversion factors if needed.
What does this program do? And what are the main issues with it? (5) Do we need brackets in this program?
x = float(input())
y = 32.0 + x * 9.0/5.0
print(y)
This program takes in an x value as any real number and multiplies it by 9, and then divided by 5. Then it adds 32 and this becomes the new y value. This is converting Fahrenheit to Celsius. Then we have to tell the program to show that output, which is what the print(y) does.
There are a lot of issues with this program though.
1. There is no prompt in the brackets of the input so people can’t know what to put in as input (it could be anything)
2. X is a poor variable name, we need to make it more specific to the program, such as x being f and y being c.
3. The output is unlabelled, we are just printing a value but we did not attach a string to this to indicate what the output actually is.
4. There are no comments to describe the code and what each part is doing.
5. We have magic numbers, we want to label each number with names instead. Because these conversion factors could change.
What are the 7 main mathematical expressions that python supports? What are the symbols used for each?
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Integer division(//)
This is also called floor division. When you divide two values you then truncate the integer to the value to the left of the decimal place. So just cut off the decimals, don’t round in any way. - Remainder (%) — so you divide something by something this will output the remainder not the actual quotient. This can be used to differentiate between even and odd numbers because if you compute the remainder when divided by two it will be 0 for even and 1 for odd.
- Exponentiation (**)
What order of precedence does python follow? How does this determine the order of evaluation and do expressions require brackets? Where is the assignment operator in this order of operations?
Precedence is determined by BEDMAS (brackets, exponents, division and multiplication, addition and subtraction). For +/- and * and /, the order doesn’t matter, it is just whichever comes first from left to right. So python will go wherever brackets are and evaluate inside them first, and then they will carry on to the rest of bedmas. This means you don’t need brackets unless you want addition or subtraction to be carried out first.
B: ()
E: -x, x**y
D: x / y, x % y, x // y
M: x * y
A: x + y
S: x - y
Assignment operator: =
This is the value you stick to the variable so it should be the last step once the variable has had all the operations applied to it.
What does a = a + 2 mean? Is this allowed?
This just means that the new a (to the left of the assignment operator) is 2 greater then the old a. So now any time you use a it will be a different value than it was above this line. Although this statement doesn’t make sense looking at it, it is essentially just assigning a new value to a so it is allowed.
How do you carry out math functions that are more complex then the 7 we just talked about?
Math functions are available in the math module, and to get them we import these functions. To do this we write import math. The below this line we can write out our function, starting with math., and that will then input the desired function. So don’t do import math.function(x) right at the site, do import math above, and then do math.function(x) right at the site.
So if you want to do the square root, you would do:
Import math
math.sqrt(x), and in the x you would put the number you want to take the square root of.
What are the three types of errors that can occur when writing code? Explain each and when python notices they occur. Which is the most serious? How do you resolve each one?
Syntax errors: These errors are identified as the code is loaded (so pretty quick) and are just due to an invalid variable name (spelled incorrectly) or some error in spelling something. Python will display an error message for this, and the program will not even begin to run before this is noticed and it crashes. An example would be missing quotation marks around a string, adding an uppercase letter, or just misspelling a word so that it appears undefined to python.
Runtime errors: These errors are identified as the program runs, so essentially once the program runs to the place where the error occurs then it will crash. The code can then exist for a long time before the error occurs, which could be based on a certain input value that was put in. Often python will not indicate which line causes the problem. Some examples would be: an undefined variable — you get to that variable in the code and realize that it does not exist — trying to divide a number by zero, trying to access a file that doesn’t exist, calling on a function which has incorrect arguments entered, etc. These are all things that will show up once the program is run but not before.
Logic errors: This occurs when the program runs to completion but generate incorrect results. This problem is the most difficult to resolve because you have to rethink your entire program. To track down the issue, have the program print out all intermediate results and compare with the work you did by hand.
What are the 4 types of values that variables can hold?
- Integer: A round whole number.
- Float: Real number (approximation)
- Boolean: True or false value, only two possibilities.
- String: This is text and can be anything.
There are certain types of operations that can be applied to only certain variable types. What of the 4 possible variable values can be added, divided, multiplied, subtracted, etc?
Specifically, what if you did integer + integer? String + string? Integer + string? Float / integer? String to left multiplied by integer to right?
If you can’t divide string by string, is there a way to divide using these strings and adding something else?
Two integers or two float numbers can have any operation applied to them. Two strings can also be added, and it just forms a new string which combined the values in each string. You can’t multiply or divide strings though.
When you try to add a string and an integer, you get an error, unless you convert the number to a string and then combine the values. Even if you did 2 + “4”, it would produce an error (string error).
You CAN combine a float and an integer, but it will produce a float output (so with a decimal point).
Then if you try to multiply a string by an integer to the right, python will actually replicate the string as many times as indicated by the integer. For example, “5.0” * 3 =15” “5.0 5.0 5.0”. So it keeps it as a string and just repeats it.
Well if you put float(“string”) / float(“string”), then you will get a float number if those strings are numbers. This is because the float converts the string to a number and allows division to occur.
Write a program that reads the amount borrowed for a loan, the interest rate, and the length of the loan, and displays the monthly payment and total borrowing cost.
We would use the equation: P = iA/ (1 - (1 + i)^(-N))
Where P = payment amount
i = interest per payment period as a decimal value not a percent! (So not annual)
A = amount borrowed
N = total number of payments
To do this, first write out the steps:
- Read the amount to borrow, interest rate, and loan duration from the user.
amount = float(input(“How much money is being borrowed?”))
Rate = float(input(“Enter the interest rate as a decimal (0.05 for 5% per year)):)
Years = int(input(“Enter the loan duration in years: “))
- Convert from the entered units to the units needed by the formula.
Num_payments = years * 12 (because on payment per month)
Rate = rate/12 (so interest rate per payment period rather then per year)
- Compute the payment amount using the formula
Payment = rate *amount / (1- (1 + rate) ** -(num_payments)) - Compute the total cost of borrowing (how much extra money you paid due to interest)
Cost = payment * num_payments - amount
- Report the result
Print(“The payment amount for the loan is”, payment)
Print(“The total cost of borrowing is”, cost).