Python Fundamentals Flashcards

1
Q

How do you print ‘Hello, world!’ in Python?

A

print(“Hello, world!”)

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

How to create a date format with print()?

A

print(‘06’, ‘04’, ‘2003’, sep=’–’)

date – my birthday

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

How to ask a user to input their name?

A

input(“Enter your name: “)

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

What are two ways to write a multiline comments?

A

’#’To be
‘#’or not to be.

””” To be
or not to be.”””

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

How to make a variable with four different data types?

A

x = “Hello, world!”
x = 50 #int
x = 60.5 #float
x = 3j #complex

1 for text, 3 for numbers

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

How to check a data type?

A

By using type().
*print(type(x))

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

What are the conditional statements?

A

if–elif–else

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

How to use for loop in the range from 0 to 5?

A

for i in range(5):
print(i)

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

How to use while loop?

A

i = 0
while i < 5:
print(i)
i += 1

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

What are two loop control statements?

A
  1. break (exits the loop)
  2. continue (skips the current iteration)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to use enumerate() to get index and value in a loop?

A

items=[]
for i, item in enumerate(items):
print (i, item)

list ‘items’

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

How to use Addition, Subtraction, Multiplication, and Division Assignment Operator?

A

a += b #a = a + b
a -= b
a *= b
a /= b

a = a + b
a = a - b
a = a * b
a = a / b

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

How to make a function?

A

def function():
function body

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

What is the function return statement?

A

The statement used to terminate a function and return to the function caller with the provided value or data item.

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

What are two ways to format a print() function?

A

print(“Result is {}”.format(variable))
or
print(f”Result is {variable}”)

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

Особливості {} в print()?

A
  1. {} - це місце, куди підставляється значення, яке передається в .format().
  2. Якщо {} кілька, .format() може приймати стільки ж аргументів.
  3. У {} можна використовувати індекси. (print(“{1} loves {0}”)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to make a for loop with range() function?

A

for i in range(5):
print(i, end=” “)

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

Роль *args і **kwargs?

A

Дозволяють писати гнучкі функції, які можуть приймати змінну кількість аргументів.

*args - збирають дані у кортежі.

**kwargs - збирають дані у словники.

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

Як використовувати *args **kwargs для запису замовлень?

A

def order_summary (*items, **details):
print(“Замовлення містить: “, items)
print(“Деталі замовлення: “, details)

order_summary(“піца”, “сік”, адреса=”Київ, вул. Шевченка, 10”, час=”18:00”)

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

What is the syntax of walrus operator?

A

a := expression

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

What is the program for shortening a list (a = [1, 2, 3, 4, 5]) to three elements?

A

while (x := len(a)) > 2:
a.pop()
print(x)

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

What is the syntax of comparison operators?

  1. Greater than
  2. Less than
  3. Equal to
  4. Not equal to
  5. Grater than or equal to
  6. Less than or equal to
A
  1. x > y
  2. x < y
  3. x == y
  4. x != y
  5. x >= y
  6. x <= y
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the syntax of chaining comparison operators?

A

a op1 b op2 c

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

What are logical operators used to?

A

To combine conditional statements (multiple conditions).

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

What are logical operators?

A
  1. AND - returns True if both the operands are true (x and y).
  2. OR - returns True if either of the operands is true (x or y).
  3. NOT - returns True if the operand is false (not x).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the meaning of the Bitwise operators?

  1. &
  2. |
  3. ~
  4. > >
  5. «
A
  1. AND
  2. OR
  3. NOT
  4. XOR
  5. Right shift
  6. Left shift
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What are five data structures in Python and their syntax?

A
  1. List - [ ]
  2. Dictionary - { : }
  3. Tuple - ( )
  4. Set - { }
  5. String “ “ (“” “””, or “”” “””)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How to rewrite this code with a list comprehension?

List = []
for character in [1, 2, 3]:
List.append(character)
print(List)

A

List = [character for character in [1, 2, 3]]
print(List)

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

How to create and print a list?

A

list = [“I”, “Love”, “You”]
print(list)

26
Q

How to create a dictionary in Python and print() it?

A

dict = {1: ‘I’, 2: ‘Love’, 3: ‘You’}
print(dict)

27
Q

Rewrite the code so it uses dictionary comprehension.

keys = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
values = [1,2,3,4,5]

myDict = dict(zip(keys, values))

print(myDict)

A

keys = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
values = [1,2,3,4,5]

myDict = { k:v for (k, v) in zip(keys, values)}

print(myDict)

27
Q

What is the syntax of tuples?

A

tup = (“I”, “Love”, “You”)
print(tup)

28
Q

What are the characteristics of tuples?

A
  1. It is a succession of values of any kind.
  2. Elements in tuple are indexed by integers.
29
Q

What is the syntax of sets?

A

myset = {“I”, “Love”, “You”}
print(myset)

30
Q

What are the characteristics of sets?

A
  1. It is an unordered collection of data types.
  2. The data cannot be iterated or mutated.
  3. Contains no duplicate elements.
31
Q

What is the syntax of creating a string?

A

string1 = “I love you”

32
Q

What are the charateristics of strings?

A
  1. It cannot be changed once it’s created (immutable)
  2. Can be accessed by using the method of indexing.
  3. Negative adress references are used to access characters from the back.
  4. Strings can be combined with + operator.
33
Q

What is the syntax of string slicing?

A

print(string1[3:-2])

*3rd and 2nd last character

34
Q

Функція, що повертає кількість елементів у послідовності (рядок, список тощо)

35
Q

Функція, що визначає тип обʼєкта.

36
Q

Функції, що перетворюють значення у відповідний тип даних:

  1. Десяткове число
  2. Число з комою
  3. Рядок
A

int()
float()
str()

37
Q

Функція, що отримує введення від користувача.

38
Q

Функція, що обчислює суму елементів ітерабельного обʼєкта.

39
Q

Функції, що знаходять мінімальне та максимальне значення.

A

min(), max()

40
Q

Функція, що повертає відсортований список з ітерабельного обʼєкта.

41
Q

Функція, що генерує послідовність чисел.

42
Q

Функція, що додає лічильник до ітерабельного обʼєкта.

A

enumerate()

43
Q

Функція, що обʼєднує кілька ітерабельних обʼєктів у кортежі.

44
Q

Функція, що застосовує функцію для кожного елемента ітерабельного обʼєкта.

45
Q

Функція, що відбирає елементи, що відповідають певній умові.

46
Q

Функція, що відкриває файл для читання або запису.

47
Q

Функція, що перевіряє, чи є обʼєкт екземпляром певного класу.

A

isinstance()

48
Q

Функція, що повертає список артибутів та методів обʼєкта.

49
Q

Функція, що повертає унікальний ідентифікатор обʼєкта.

50
Q

Функція, що повертає абсолютне значення числа.

51
Q

Функція, що округлює число до заданої кількості десяткових знаків.

52
Q

Як створити клас у Python?

A

class MyClass:
pass

53
Q

Що таке метод __init__()?

A

Це конструктор класу, який автоматично викликається при створенні об’єкта. Використовується для ініціалізації атрибутів.

53
Q

Як створити об’єкт класу?

A

obj = MyClass()

53
Q

Як визначити метод у класі?

A

class MyClass:
def my_method(self):
print(“Hello”)

54
Q

Як успадкувати клас у Python?

A

class ChildClass(ParentClass):
pass

54
Q

Що таке self?

A

Це посилання на поточний об’єкт.

55
Q

Як створити приватний атрибут?

A

class MyClass:
def __init__(self):
self.__private_attr = 42

55
Q

Що таке інкапсуляція?

A

Приховування внутрішньої реалізації об’єкта. Реалізується через публічні, захищені та приватні атрибути (_, __).

55
Q

Як створити абстрактний клас у Python? (Payment method)

A

from abc import ABC, abstractmethod

class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
pass

55
Q

Що таке поліморфізм?

A

Поліморфізм дозволяє використовувати об’єкти різних класів через один і той самий інтерфейс (наприклад, викликати метод speak() у різних класах, навіть якщо реалізація різна).

56
Q

Що таке abstract property?

A

Це абстрактна властивість, яку обов’язково потрібно реалізувати в підкласі.

from abc import ABC, abstractmethod

class Product(ABC):
@property
@abstractmethod
def price(self):
pass

56
Q

Що таке getter, setter, deleter у Python?

A

class Person:
def __init__(self, name):
self._name = name

@property
def name(self):
    return self._name

@name.setter
def name(self, value):
    self._name = value

@name.deleter
def name(self):
    del self._name
56
Q

Синтаксис функції super().

A

class Parent:
def greet(self):
print(“Hi from Parent”)

class Child(Parent):
def greet(self):
super().greet()
print(“Hi from Child”)

56
Q

Що таке @classmethod?

A

Метод, який отримує доступ до самого класу, а не до об’єкта (cls замість self).

class MyClass:
count = 0

@classmethod
def increment(cls):
    cls.count += 1
56
Q

Що таке @staticmethod?

A

Метод, який не використовує self або cls, тобто не потребує ні об’єкта, ні класу.

class Math:
@staticmethod
def add(a, b):
return a + b