Mooc,fi Flashcards

1
Q

Computer programs consist of

A

commands, each command instructing the computer to take some action. A computer executes these commands one by one. Among other things, commands can be used to perform calculations, compare things in the computer’s memory, cause changes in how the program functions, relay messages or ask for information from the program’s user.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Arithmetic operations

A

You can also put arithmetic operations inside a print command. print(2 + 5), Notice the lack of quotation marks around the arithmetic operations above. Quotation marks are used to signify strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

strings

A

are sequences of characters. They can consist of letters, numbers and any other types of characters, such as punctuation. Strings aren’t just words as we commonly understand them, but instead a single string can be as long as multiple complete sentences. Strings are usually printed out exactly as they are written.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Commenting

A

Any line beginning with the pound sign #, also known as a hash or a number sign, is a comment. This means that any text on that line following the # symbol will not in any way affect how the program functions. Python will simply ignore it.

Comments are used for explaining how a program works, to both the programmer themselves, and others reading the program code.
When the program is run, the comment will not be visible to the user

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Input

A

refers to any information a user gives to the program. Specifically, the Python command input reads in a line of input typed in by the user. It may also be used to display a message to the user, to prompt for specific input.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

variable

A

a variable is a location for storing some value, such as a string or a number. This value can be used later, and it can also be changed.

the value stored in a variable can change. In the previous section we noticed that the new value replaces the old one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Referencing a variable

A

A single variable can be referred to many times in a program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Choosing a good name for a variable

A

It is often useful to name variables according to what they are used for. For example, if the variable contains a word, the name word is a better choice than, say, a.

There is no set limit to the length of a variable name in Python, but there are some other limitations. A variable name should begin with a letter, and it can only contain letters, numbers and underscores _.

Lowercase and uppercase letters are different characters. The variables name, Name and NAME are all different variables. While this rule has a few exceptions, we will ignore those for now.

It is a common programming practice in Python to use only lowercase characters in variable names. If the variable name consists of multiple words, use an underscore between the words. While this rule also has a few exceptions, we will ignore those for now.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Integers

A

Integers are numbers that do not have a decimal or fractional part, such as -15, 0 and 1.

Notice the lack of quotation marks here. In fact, if we were to add quotation marks around the number, this would mean our variable would no longer be an integer, but a string instead. A string can contain numbers, but it is processed differently.

For integer values the + operator means addition, but for string values it means concatenation, or “stringing together”.

If we do want to print out a string and an integer in a single command, the integer can be cast as a string with the str function, and the two strings can then be combined normally.

The print command also has built-in functionalities that support combining different types of values. The simplest way is to add a comma between the values. All the values will be printed out regardless of their type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Printing with f-strings

A

So called f-strings are another way of formatting printouts in Python. The syntax can initially look a bit confusing, but in the end f-strings are often the simplest way of formatting text.

With f-strings the previous example would look like this:

result = 10 * 25
print(f”The result is {result}”)

A single f-string can contain multiple variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Floating point numbers

A

Floating point number or float is a term you will come across often in programming. It refers to numbers with a decimal point. They can be used much in the same way as integer values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

end = “”

A

For example:

print(“Hi “, end=””)
print(“there!”)

Sample output
Hi there!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Arithmetic operations

A

Operator Purpose Example Result
+ Addition 2 + 4 6
- Subtraction 10 - 2.5 7.5
* Multiplication -2 * 123 -246
/ Division (floating point result) 9 / 2 4.5
// Division (integer result) 9 // 2 4
% Modulo 9 % 2 1
** Exponentiation 2 ** 3 8

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

The order of operations is familiar from mathematics

A

first calculate the exponents, then multiplication and division, and finally addition and subtraction. The order can be changed with parentheses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Operands, operators and data types

A

A calculation usually consists of operands and operators.
The data type of an operand usually determines the data type of the result: if two integers are added together, the result will also be an integer. If a floating point number is subtracted from another floating point number, the result is a floating point number. In fact, if a single one of the operands in an expression is a floating point number, the result will also be a floating point number, regardless of the other operands.

Division / is an exception to this rule. Its result is a floating point number, even if the operands are integers. For example 1 / 5 will result in the floating point number 0.2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Integer division operator //

A

If the operands are integers, it will produce an integer. The result is rounded down to the nearest integer
x = 3
y = 2

print(f”/ operator {x/y}”)
print(f”// operator {x//y}”)
prints out

Sample output
/ operator 1.5
// operator 1

17
Q

Numbers as input

A

We have already used the input command to read in strings from the user. The same function can be used to read in numbers, but the string produced by the function must then be converted to a numeric data type in the program code. In the previous section we cast integers as strings with the str function. The same basic principle applies here, but the name of the casting function will be different.

A string can be converted into an integer with the function int. The following program asks the user for their year of birth and stores it in the variable input_str. The program then creates another variable year, which contains the year converted into an integer. After this the calculation 2021-year is possible, using the user-supplied value.

input_str = input(“Which year were you born? “)
year = int(input_str)
print(f”Your age at the end of the year 2021: {2021 - year}” )

18
Q

conditional statement

A

with a block of code which is executed only if the condition in the statement is true.

In a conditional statement the keyword if is followed by a condition, such as a comparison of two values. The code block following this header line is only executed if the condition is true.

age = int(input(“How old are you? “))

if age > 17:
print(“You are of age!”)
print(“Here’s a copy of GTA6 for you.”)

print(“Next customer, please!”)

19
Q

Comparison operators

A

Operator Purpose Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
>= Greater than or equal to a >= b
< Less than a < b
<= Less than or equal to a <= b

20
Q

Indentation

A

Python recognises that a block of code is part of a conditional statement if each line of code in the block is indented the same. That is, there should be a bit of whitespace at the beginning of every line of code within the code block. Each line should have the same amount of whitespace.

You can use the Tab key, short for tabulator key, to insert a set amount of whitespace.

21
Q

Statement

A

A statement is a part of the program which executes something. It often, but not always, refers to a single command.

For example, print(“Hi!”) is a statement which prints out a line of text. Likewise, number = 2 is a statement which assigns a value to a variable.

A statement can also be more complicated. It can, for instance, contain other statements. The following statement spans three lines:

if name == “Anna”:
print(“Hi!”)
number = 2
In the above case there are two statements (a print statement and an assignment statement) within a conditional statement.

22
Q

Block

A

A block is a group of consecutive statements that are at the same level in the structure of the program. For example, the block of a conditional statement contains those statements which are executed only if the condition is true.

if age > 17:
# beginning of the conditional block
print(“You are of age!”)
age = age + 1
print(“You are now one year older…”)
# end of the conditional block

print(“This here belongs to another block”)
In Python blocks are expressed by indenting all code in the block by the same amount of whitespace.

NB: the main block of a Python program must always be at the leftmost edge of the file, without indentation:

23
Q

Expression

A

An expression is a bit of code that results in a determined data type. When the program is executed, the expression is evaluated so that it has a value that can then be used in the program.

Here are a few examples of expressions:

Expression Value Type Python data type
2 + 4 + 3 9 integer int
“abc” + “de” “abcde” string str
11 / 2 5.5 floating point number float
2 * 5 > 9 True Boolean value bool
Because all expressions have a type, they can be assigned to variables:

the variable x is assigned the value of the expression 1 + 2
x = 1 + 2
Simple expressions can be assembled together to form more complicated expressions, for example with arithmetic operations:

the variable y is assigned the value of the expression ‘3 times x plus x squared’
y = 3 * x + x**2

24
Q

Function

A

A function executes some functionality. Functions can also take one or more arguments, which are data that can be fed to and processed by the function. Arguments are sometimes also referred to as parameters. There is a technical distinction between an argument and a parameter, but the words are often used interchangeably. For now it should suffice to remember that both terms refer to the idea of some data passed to the function.

A function is executed when it is called. That is, when the function (and its arguments, if any) is mentioned in the code. The following statement calls the print function with the argument “this is an argument”:

print(“this is an argument”)
Another function you’ve already used often is the input function, which asks the user for input. The argument of this function is the message that is shown to the user:

name = input(“Please type in your name: “)
In this case the function also returns a value. After the function has been executed, the section of code where it was called is replaced by the value it returns; it is another expression that has now been evaluated. The function input returns a string value containing whatever the user typed in at the prompt. The value a function returns is often stored in a variable so that it can be used in the program later on.

25
Q

Data type

A

Data type refers to the characteristics of any value present in the program. In the following bit of code the data type of the variable name is string or str, and the data type of the variable result is integer or int:

name = “Anna”
result = 100
You can use the function type to find out the data type of any expression. An example of its use:

print(type(“Anna”))
print(type(100))
Sample output
<class ‘str’>
<class ‘int’>

26
Q

Syntax

A

Similarly to natural languages, the syntax of a programming language determines how the code of a program should be written. Each programming language has its own specific syntax.

The syntax of Python specifies, among other things, that the first line of an if statement should end in a colon character, and the block of the statement should be indented:

if name == “Anna”:
print(“Hi!”)
If the syntactic rules of the programming language are not followed, there will be an error:

if name == “Anna”
print(“Hi!”)
Sample output
File “test.py”, line 1
if name == “Anna”
^
SyntaxError: invalid syntax

27
Q

Debugging

A

If the syntax of the program is correct but the program still doesn’t function as intended, there is a bug in the program.

Bugs manifest in different ways. Some bugs cause an error during execution. For example, the following program

x = 10
y = 0
result = x / y

print(f”{x} divided by {y} is {result}”)
causes this error:

Sample output
ZeroDivisionError: integer division or modulo by zero on line 3
The problem here is mathematical in nature: division by zero is not allowed, and this halts the execution of the program.

Errors during execution are usually rather easy to fix, because the error message states the line of code causing the error. Of course the actual reason for the bug might be somewhere quite different than the line of code causing the error.

Sometimes a bug in the program is revealed because the result the code produces is wrong. Discovering and locating this type of bug can be challenging.

Programming jargon refers to discovering the causes of bugs as debugging. It is an extremely important skill in any programmer’s toolbox. Professional programmers often spend more time debugging than writing fresh code.

28
Q

The function len

A

can be used to find out the length of a string, among other things. The function returns the number of characters in a string.

29
Q

Typecasting

A

When programming in Python, often we need to change the data type of a value. For example, a floating point number can be converted into an integer with the function int:

temperature = float(input(“Please type in a temperature: “))

print(“The temperature is”, temperature)

print(“…and rounded down it is”, int(temperature))
Sample output
Please type in a temperature: 5.15
The temperature is 5.15
…and rounded down it is 5

Notice the function always rounds down, and not according to the rounding rules in mathematics. This is an example of a floor function.

Sample output
Please type in a temperature: 8.99
The temperature is 8.99
…and rounded down it is 8

30
Q

conditional statement.

A

there can never be an else branch without an if branch before it. The if-else construction as a whole forms a single conditional statement.

31
Q

Alternative branches using the elif statement

A

Often there are more than two options the program should account for. For example, the result of a football match could go three ways: home wins, away wins, or there is a tie.

A conditional statement can be added to with an elif branch. It is short for the words “else if”, which means the branch will contain an alternative to the original condition. Importantly, an elif statement is executed only if none of the preceding branches is executed.

32
Q

Alphabetically last

A

Python comparison operators can also be used on strings. String a is smaller than string b if it comes alphabetically before b. Notice however that the comparison is only reliable if

the characters compared are of the same case, i.e. both UPPERCASE or both lowercase
only the standard English alphabet of a to z, or A to Z, is used.

33
Q

Logical operators

A

You can combine conditions with the logical operators and and or. The operator and specifies that all the given conditions must be true at the same time. The operator or specifies that at least one of the given conditions must be true.

For example, the condition number >= 5 and number <= 8 determines that number must simultaneously be at least 5 and at most 8. That is, it must be between 5 and 8.

number = int(input(“Please type in a number: “))
if number >= 5 and number <= 8:
print(“The number is between 5 and 8”)
Meanwhile, the condition number < 5 or number > 8 determines that number must be either less than 5 or greater than 8. That is, it must not be within the range of 5 to 8.

number = int(input(“Please type in a number: “))
if number < 5 or number > 8:
print(“The number is not within the range of 5 to 8”)

34
Q

truth table contains the behaviour of these operators

A

a b a and b a or b
False False False False
True False False True
False True False True
True True True True

Especially in programming, logical operators are often called Boolean operators.

35
Q

The operator not

A

negates a condition:

a not a
True False
False True

36
Q

Simplified combined conditions

A

The condition x >= a and x <= b is a very common way of checking whether the number x falls within the range of a to b. An expression with this structure works the same way in most programming languages.

Python also allows a simplified notation for combining conditions: a <= x <= b achieves the same result as the longer version using and. This shorter notation might be more familiar from mathematics, but it is not very widely used in Python programming, possibly because very few other programming languages have a similar shorthand.

37
Q

Simple loops

A

Another central technique in programming is repetition, or iteration.

Another central technique in programming is repetition, or iteration.