PYHTON Flashcards

1
Q

What is a module?

A

“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

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

What is function?

A

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

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

What is an object?

A

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”)

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

What is a class?

A

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

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

loops

A

while for

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

conditional statements

A

if, else, elif

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

data structures:
list
dictionaries
tuples

A

[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’}

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

Which function from the math module computes the Euclidian distance of a vector, stored as a list?

A

dist

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

What is random in the code below?
import random
x = random.randint(0, 100)

A

A module

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

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

a class

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

By convention, how does one call the first parameter of a method?
1) me
2) init
3) this
4) self
5) append
6) 0

A

self

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

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:

A

file.close()

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

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

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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)

A

1
a=[1,[2,3]]
but pop() deletes the inside list

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

What is the type of the following expression?
[1, 2, 3.5, 4][2]
1) int
2) float
3) str
4) list

A

element two of the list is a float.

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

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.

A

def cube(lst):
new_list = []
for x in lst:
new_list.append(x**3)
return new_list

list = [5, 8, 9]
print(cube(list))

15
Q

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.

A

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)

16
Q

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

A

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
17
Q

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.”””

A

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)

18
Q

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.

  1. sqrt and Turtle are a function and a class from the math and turtle modules: T/F
  2. sqrt and Turtle are functions in the math and turtle modules: T/F
  3. rd and plt are functions in the random and matplotlib.pyplot modules: T/F
  4. rd and plt are import aliases for the random and matplotlib.pyplot modules: T/F
A

1: true.
2: false.
3: false.
4: true.

19
Q

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

A
  • You can write for-loops that do not terminate.
  • You can have if statements within a for-loop
20
Q

{‘abc’:4}

A

dictionary

21
Q

(‘x’,4)

A

tuple

22
Q

‘1’+’2’

A

strings

23
Q

[e for e in range(7)]
[TRUE, FALSE, TRUE]

A

list

24
Q

Given the following code, what are the values a and b respectively, so that the code prints
[9, 8, 3] ?

x = [1, 2, 3]
y= [4, 5, 6]
y = x
x[a] = 9
y[b] = 8
print(y)

A

a= 0
b =1

25
Q

1.07
4 % 3
4 > 3
‘4//3’
5
7

A

float
integer (returns the remainder)
boolean
string
integer

26
Q

int / float

A

int whole number
-5 2 36 1000
float decimal
-314.0256 2.33

27
Q

Given the following code:
def g(b):
return b*6
class Pollax:
def __init__(self, x):
self.x = x
def add(self, a):
self.x += a
def getX(self):
return self.x

whats?
self.x
add
randit
getValue
random

A

self.x - instance variable
add - method

getValue - method
random - module
randit - function

28
Q

what is this?
r == ‘Q’
a=4
y[1:3]
w>4
[e for e in x if e > 0]

A

Logical expressions:
r == ‘Q’
w>4

Assignment:
a=4

Slicing:
y[1:3]

List comprehension:
[e for e in x if e > 0]

29
Q

what is the word “import” in python

A

keyword

30
Q

“Trapezoid Area Calculation
The area of a trapezoid is calculated as the product of the height (h) and the average of the parallel sides (a, b):
Area= (h(a+b))/2
Write a function that calculates and returns the area according to the provided formula. The function header is given: def TrapezoidArea(h, a, b)

A

def TrapezoidArea(h, a, b):
return ((h(a+b))/2

31
Q

Rewrite the following program: (factorial)
f = 1
j = 1
while j <= 4:
f *= j
j += 1
print(‘f =’, f)
which produces the output:
f = 24

A

f = 1
for j in range(1, 5): # The range function generates values from 1 to 4 (inclusive).
f *= j
print(‘f =’, f)