Python Moodle Flashcards
What is an algorithm?
A step by step sequence of instructions that if followed exactly will solve the problem under consideration.
Algorithms are like recipes: they must be followed exactly, they must be clear and unambiguous, and they must end.
What is a program?
A sequence of instructions that specifies how to perform a computation.
The differences between natural and formal languages include:
ambiguity, redundancy, and literalness
Source code is another name for:
the instrucions in a program, written in a high-level language.
What is the difference between a high-level programming language and a low-level programming language?
It is high-level if the program must be processed before it can run, and low-level if the computer can execute it without additional processing.
What is the difference between a compiler and interpreter?
Interpreter reads a high-level program line by line and performs computations.
A compiler reads the high-level program (soucre code) and translates it into object code. The object code is then executed without further translation.
Interpreter: line by line translation
Compiler: translates the whole book
What is debugging?
tracking down programming errors and correcting them
What type of errors extist and explain?
- Syntax Error
syntax = structure of the program
Syntax errors are mistakes in using the language. Examples of syntax errors are missing a comma or a quotation mark, or misspelling a word. This is typically found by the compiler/interpreter. - Runtime Error (=excpection)
Runtime, or execution-time, errors are found when a script or function is executing (=found by the interpreter). Ex. divide by 0. - Semantic Error (=logical error)
semantic = meaning of a program
A semantic error is a mistake in reasoning by the programmer, but it is not a mistake in the programming language (=can only be found by the programmer)
What is a token?
One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.
Python is a
- general-purpose programming language
- scripting language
- interpreted language
What is the order of the program execution process?
- Write the code
- Compile
- Debug
- Execute the compiled and debugged code
In a nutshell what are the key components of a computer program?
Input
Operations
Control Structures
Ouput
What is the truncated division operator?
ex. 9//5 = 1
–> ignores the remainder
What is the modulus operator?
ex. 7 % 3 = 1
1 % 5 = 1 (5*0 + 1)
–> keeps only the remainder
What are keywords?
Keywords define the language’s syntax rules and structure, and they cannot be used as variable names,
e.g. and, def, class, True, try, except, global
What is increment, bumping, and decrement?
increment: adding something to a variable
bumping: increment a variable by 1 ( x+= 1)
decrement: subtracting something to a variable
What to watch out for when using the input function?
Input function returns a string value
What to watch out for when choosing a variable name?
- begin with a letter
- no illigeal characters (+,$,..)
- no keywords
Write the Python code that displays the value of a,b,c in one line with the ‘+’ operator:
a = int(input(“please enter a number”))
b = input(“please enter a sentence”)
c = ‘the input sentence is: ‘
In order to use the + first, we have to make sure that all the variables have the same data type.
The value of b and c is a string but the value of a is an integer so we need to convert it to a string by using str().
print(str(a) + b + c)
Important difference between string and list?
Lists can be changed while strings are immutable.
How do we call a string that contains no characters?
empty string
What is the difference between lists and tuples?
lists:
[10, 20, 30, 40]
[“spam”, “bungee”, “swallow”]
mutable
tuples:
julia = (“Julia”, “Roberts”, 1967, “Duplicity”, 2009, “Actress”, “Atlanta, Georgia”)
immutable
How do you access the last character or middle character of the string fruit = “grape”?
lastchar = fruit[-1]
lastchar = fruit[len(fruit) - 1]
midchar = fruit[len(fruit) // 2]
What is a slice operator?
The slice operator [n:m] returns the part of the string starting with the character at index n and go up to but not including the character at index m.
What does the ‘+’ operator and ‘*’ operator do with lists?
fruit = [“apple”,”orange”,”banana”,”cherry”]
print([1,2] + [3,4])
print(fruit+[6,7,8,9])
print([0] * 4)
+ concatenate
* repeats items in a list
[1, 2, 3, 4]
[‘apple’, ‘orange’, ‘banana’, ‘cherry’, 6, 7, 8, 9]
[0, 0, 0, 0]
Beware when adding different types together! Python doesn’t understand how to concatenate different types together. Thus, if we try to add a string to a list with [‘first’] + “second” then the interpreter will return an error.
What does the count method do?
a = “I have had an apple on my desk before!”
print(a.count(“e”))
———————
z = [‘atoms’, 4, ‘neutron’, 6, ‘proton’, 4, ‘electron’, 4, ‘electron’, ‘atoms’]
print(z.count(“4”))
print(z.count(4))
print(z.count(“a”))
print(z[0].count(“a”))
print(z.count(“electron”))
It requires that you provide one argument, which you would like to count. The method then returns the number of times that the argument occurred in the string/list the method was used on
5
———————
0
3
0
1
2
What does the index method do?
music = “Pull out your music and dancing can begin”
bio = [“Metatarsal”, “Metatarsal”, “Fibula”, [], “Tibia”, “Tibia”, 43, “Femur”, “Occipital”, “Metatarsal”]
print(music.index(“m”))
print(music.index(“your”))
print(bio.index(“Metatarsal”))
print(bio.index([]))
print(bio.index(43))
The other method that can be helpful for both strings and lists is the index method. The index method requires one argument, and, like the count method, it takes only strings when index is used on strings, and any type when it is used on lists. For both strings and lists, index returns the leftmost index where the argument is found. If it is unable to find the argument in the string or list, then an error will occur.
14
9
0
3
song = “The rain in Spain…”
wds = song.split()
print(wds)
———————
song = “The rain in Spain…”
wds = song.split(‘ai’)
print(wds)
The split method breaks a string into a list of words.
[‘The’, ‘rain’, ‘in’, ‘Spain…’]
[‘The r’, ‘n in Sp’, ‘n…’]
wds = [“red”, “blue”, “green”]
glue = ‘;’
s = glue.join(wds)
print(s)
print(wds)
print(“***“.join(wds))
print(““.join(wds))
red;blue;green
[‘red’, ‘blue’, ‘green’]
redbluegreen
redbluegreen
What is printed by the following statements?
s = “python rocks”
print(len(s))
12 –> whitespace is a character
What is printed by the following statements?
L = [0.34, ‘6’, ‘SI106’, ‘Python’, -2]
print(len(L[1:-1]))
3
[n:m] –> n wird mitgezählt, m nicht
What will be stored in the variable ty below?
qu = “wow, welcome week!”
ty = qu.index(“we”)
5
When we get the index of a string that is longer than one character, we get the index for the first character in the string.
What will be stored in the variable ty below?
qu = “wow, welcome week! Were you wanting to go?”
ty = qu.count(“we”)
2
There is a difference between “we” and “We” which means there are only two in the string –> case sensitive
What is the ouput of this code?
for achar in “Go Spot Go”:
print(achar)
G
o
S
p
o
t
G
o
What is the range function range(n)?
ex. range(3)
starts at 0 and goes up to but not including n.
range(3) –> [0,1,2]
When is the for variable _ used?
for _ in range(3):
print(“This line will execute three times”)
print(“This line will also execute three times”)
When we don’t intend to ever refer to the loop variable
How many comparison operators exist in Python?
6
x == y
x != y
x > y
x < y
x >= y
x <= y
What does the ‘in’ operator?
The in operator tests if one string is a substring of another:
print(‘p’ in ‘apple’)
print(‘i’ in ‘apple’)
print(‘’ in ‘a’)
print(‘’ in ‘apple’)
True
False
True
True
What is the type of m?
l = [‘w’, ‘7’, 0, 9]
m = l[1:2]
It’s a list! A slice returns a list no matter how large the slice size is.
What is the type of m?
l = [‘w’, ‘7’, 0, 9]
m = l[1]
It’s a string! [1] indicates it is the second element ‘7’ in the list, and the quotes around the number mean that this is a string.
What is the type of a?
b = “My, what a lovely day”
x = b.split(‘,’)
z = ““.join(x)
y = z.split()
a = ““.join(y)
It’s a string!
The string is split into a list, then joined back into a string, then split again, and finally joined back into a string “Mywhatalovelyday”.
What is the output message of the following code:
x,y,z = 1,2,3
def sum_two(x,y,z):
return x+y, y+z, x+z
result = sum_two(x,y,z)
a,b = result[::2]
print(str(a) +str(b))
34
Yes, result = (3,5,4) after calling sum_two function. a, b = (3,4) after executing result[::2]. Finally it concatenates ‘3’ and ‘4’.
result[::2] –> anfang bis ende in 2er Schritten
element 0, 2, 4, … –> a,b = (3,4)
Array-based structure vs. linked-based structure:
Which data structure is better?
- The array-based structure generally takes less memory as compared to the linked-based structure if the collection is considered relatively full.
- The array-based structure is preferred if the total number of elements of a collection can be predetermined at the start of the program implementation.
- The linked-based structure is preferred if adding new elements and removing existing elements are regularly performed at random positions; although the array-based structure is more efficient for accessing elements at random.
Which of the following can be used in Python? There are multiple answers for this question.
primitive data types
abstract data types
user-defined data types
predefined data types
all of the above
primitive data types
abstract data types
user-defined data types
Abstract data type is the built-in data type in Python. True or false?
False, primitive data types is the built-in data type.
What is an example for aliasing?
a = [81, 82, 83]
b = a
print(a is b)
——-
True
Since variables refer to objects, if we assign one variable to another, both variables refer to the same object. In general, it is safer to avoid aliasing when you are working with mutable objects.
What does the ‘is’ operator?
We can test whether two names refer to the same object.
When is it useful to use cloning lists?
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference.
a = [81,82,83]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
What is printed by the following statements:
s = “Ball”
s[0] = “C”
print(s)
Error, strings are immutable.
What is printed by the following statements?
alist = [4,2,8,6,5]
blist = alist * 2
blist[3] = 999
print(alist)
[4,2,8,999,5,4,2,8,6,5]
[4,2,8,999,5]
[4,2,8,6,5]
[4,2,8,6,5]
What is printed by the following statements?
alist = [4,2,8,6,5]
alist = alist + 999
print(alist)
Error, you cannot concatenate a list with an integer.