PYHTON Flashcards
What is a module?
“A module is a file containing Python definitions and statements.”
A module in Python is a file containing Python code. It can define functions, classes, and variables.
Modules are used to organize and encapsulate code. You can use them to break down your program into smaller, manageable parts.
To use a module in Python, you typically import it using the import statement.
import math
What is function?
A function in Python is a block of reusable code that performs a specific task. It takes input (arguments), processes it, and returns an output.
Functions make your code more organized, modular, and easier to read and maintain.
You can define your own functions in Python using the def keyword.
def add(x, y):
return x + y
What is an object?
An object is an instance of a class, which can have its unique state and behavior while following the class’s structure.
dog1 = Dog(“Buddy”)
dog2 = Dog(“Rex”)
What is a class?
A class is a blueprint or template for creating objects in Python. It defines the properties (attributes) and behaviors (methods) that the objects will have.
class Dog:
def __init__(self, name):
self.name = name
loops
while for
conditional statements
if, else, elif
data structures:
list
dictionaries
tuples
[LIST] : elements of any data type and MUTABLE
x = [1, 2 , “c”0”, 3.0093]
(TUPLES) : same at list but INMUTABLE
x = (1, 2 , “c”0”, 3.0093)
{DIC} : Dictionaries store key-value pairs. They are unordered, mutable, and accessed via their keys.
my_dict = {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’}
Which function from the math module computes the Euclidian distance of a vector, stored as a list?
dist
What is random in the code below?
import random
x = random.randint(0, 100)
A module
What is Worker in the code below?
x = Worker
y = x(999)
1) A function
2) A variable
3) A parameter
4) A module
5) A class
6) It is not possible to say
a class
By convention, how does one call the first parameter of a method?
1) me
2) init
3) this
4) self
5) append
6) 0
self
If the line below is already in the program (and
cannot be removed), what is most important to
also write in the program?
file = open(’ourfile.txt’, ’r’)
1) file.close()
2) text = file.readlines()
3) print(file)
4) for c in file.read()
5) with file.readlines() as lines:
file.close()
What is the difference between a function and a method
1) One can define their own functions
2) One can define their own methods
3) All methods are magic
4) A function is called on an object
5) A method is called on an object
6) Only functions can modify an object
7) Only methods can modify an object
One can define their own functions: This is correct. In many programming languages, you can define your own functions.
One can define their own methods: This is correct as well. You can define your own methods within classes in object-oriented programming.
A method is called on an object: This is correct. A method is a function that is associated with an object and operates on its data.
How many lists does the following code create?
a = [1, [2, 3]]
b = a
c = a[1]
d = a[1][0]
e = a[1][1]
print(a.pop)
1
a=[1,[2,3]]
but pop() deletes the inside list
What is the type of the following expression?
[1, 2, 3.5, 4][2]
1) int
2) float
3) str
4) list
element two of the list is a float.
The function cube(lst) takes a list as parameter and returns a new list with every value cubed (i.e. to the power of three).
Write down this function, as well as an example that uses this function to compute the cubes of 5, 8 and 9.
def cube(lst):
new_list = []
for x in lst:
new_list.append(x**3)
return new_list
list = [5, 8, 9]
print(cube(list))
The function capitalize takes a word as a parameter (as a string) and returns a new version of this word where the first letter is capitalized. The other letters remain unchanged.
For instance, ’hej’ becomes ’Hej’.
Write down the body of this function. Remember that str has a method upper that
returns a new string where all the letters are capitalized.
def capitalize(word):
if len(word) > 0:
return word[0].upper() + word[1:]
else:
return word # Return the original string if it’s empty
test = capitalize(“sofiaaaa”)
print(test)
The body of a function is written below. Write down the beginning of the function’s definition (it’s
signature) with name and parameters. Add a suitable docstring.
count = 0
for c in line:
if c == ’Q’:
count += 1
return count
def count_Q(line):
“””
This function counts the number of occurrences of the letter ‘Q’ in the given line.
Args: line (str): The input string in which 'Q' occurrences are counted. Returns: int: The count of 'Q' occurrences in the line. """ count = 0 for c in line: if c == 'Q': count += 1 return count
The function longestWord returns the longest word from a string. Remember the method split can be used to split a string into a list of words. Write the body of this function.
def longestWord(data):
“"”Returns the longest word found in input string data. Words are
defined as being delimited by whitespaces.”””
def longestword(data):
words = data.split()
longest = “”
for word in words:
if len(word) > len(longest):
longest = word
return longest
blah = “Returns the lonnnnngest word found in input string data Words are”
result = longestword(blah)
print(result)
import random as rd
import matplotlib.pyplot as plt
from math import sqrt
from turtle import Turtle
Given the code snippet above, are the following statements true or false?
To score a point on this exercise you need to get all 4 right.
- sqrt and Turtle are a function and a class from the math and turtle modules: T/F
- sqrt and Turtle are functions in the math and turtle modules: T/F
- rd and plt are functions in the random and matplotlib.pyplot modules: T/F
- rd and plt are import aliases for the random and matplotlib.pyplot modules: T/F
1: true.
2: false.
3: false.
4: true.
Choose one or more options:
* You can write for-loops that do not terminate.
* You can have if statements within a for-loop
* You cannot always replace a for-loop with an if statement.
* The statements in a for-loop must always run at least once.
* With the reserved word “continue,” you can exit a loop
- You can write for-loops that do not terminate.
- You can have if statements within a for-loop
{‘abc’:4}
dictionary
(‘x’,4)
tuple
‘1’+’2’
strings