Python Fundamentals Flashcards
How do you print ‘Hello, world!’ in Python?
print(“Hello, world!”)
How to create a date format with print()?
print(‘06’, ‘04’, ‘2003’, sep=’–’)
date – my birthday
How to ask a user to input their name?
input(“Enter your name: “)
What are two ways to write a multiline comments?
’#’To be
‘#’or not to be.
””” To be
or not to be.”””
How to make a variable with four different data types?
x = “Hello, world!”
x = 50 #int
x = 60.5 #float
x = 3j #complex
1 for text, 3 for numbers
How to check a data type?
By using type().
*print(type(x))
What are the conditional statements?
if–elif–else
How to use for loop in the range from 0 to 5?
for i in range(5):
print(i)
How to use while loop?
i = 0
while i < 5:
print(i)
i += 1
What are two loop control statements?
- break (exits the loop)
- continue (skips the current iteration)
How to use enumerate() to get index and value in a loop?
items=[]
for i, item in enumerate(items):
print (i, item)
list ‘items’
How to use Addition, Subtraction, Multiplication, and Division Assignment Operator?
a += b #a = a + b
a -= b
a *= b
a /= b
a = a + b
a = a - b
a = a * b
a = a / b
How to make a function?
def function():
function body
What is the function return statement?
The statement used to terminate a function and return to the function caller with the provided value or data item.
What are two ways to format a print() function?
print(“Result is {}”.format(variable))
or
print(f”Result is {variable}”)
Особливості {} в print()?
- {} - це місце, куди підставляється значення, яке передається в .format().
- Якщо {} кілька, .format() може приймати стільки ж аргументів.
- У {} можна використовувати індекси. (print(“{1} loves {0}”)
How to make a for loop with range() function?
for i in range(5):
print(i, end=” “)
Роль *args і **kwargs?
Дозволяють писати гнучкі функції, які можуть приймати змінну кількість аргументів.
*args - збирають дані у кортежі.
**kwargs - збирають дані у словники.
Як використовувати *args **kwargs для запису замовлень?
def order_summary (*items, **details):
print(“Замовлення містить: “, items)
print(“Деталі замовлення: “, details)
order_summary(“піца”, “сік”, адреса=”Київ, вул. Шевченка, 10”, час=”18:00”)
What is the syntax of walrus operator?
a := expression
What is the program for shortening a list (a = [1, 2, 3, 4, 5]) to three elements?
while (x := len(a)) > 2:
a.pop()
print(x)
What is the syntax of comparison operators?
- Greater than
- Less than
- Equal to
- Not equal to
- Grater than or equal to
- Less than or equal to
- x > y
- x < y
- x == y
- x != y
- x >= y
- x <= y
What is the syntax of chaining comparison operators?
a op1 b op2 c
What are logical operators used to?
To combine conditional statements (multiple conditions).
What are logical operators?
- AND - returns True if both the operands are true (x and y).
- OR - returns True if either of the operands is true (x or y).
- NOT - returns True if the operand is false (not x).
What is the meaning of the Bitwise operators?
- &
- |
- ~
- > >
- «
- AND
- OR
- NOT
- XOR
- Right shift
- Left shift
What are five data structures in Python and their syntax?
- List - [ ]
- Dictionary - { : }
- Tuple - ( )
- Set - { }
- String “ “ (“” “””, or “”” “””)
How to rewrite this code with a list comprehension?
List = []
for character in [1, 2, 3]:
List.append(character)
print(List)
List = [character for character in [1, 2, 3]]
print(List)
How to create and print a list?
list = [“I”, “Love”, “You”]
print(list)
How to create a dictionary in Python and print() it?
dict = {1: ‘I’, 2: ‘Love’, 3: ‘You’}
print(dict)
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)
keys = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
values = [1,2,3,4,5]
myDict = { k:v for (k, v) in zip(keys, values)}
print(myDict)
What is the syntax of tuples?
tup = (“I”, “Love”, “You”)
print(tup)
What are the characteristics of tuples?
- It is a succession of values of any kind.
- Elements in tuple are indexed by integers.
What is the syntax of sets?
myset = {“I”, “Love”, “You”}
print(myset)
What are the characteristics of sets?
- It is an unordered collection of data types.
- The data cannot be iterated or mutated.
- Contains no duplicate elements.
What is the syntax of creating a string?
string1 = “I love you”
What are the charateristics of strings?
- It cannot be changed once it’s created (immutable)
- Can be accessed by using the method of indexing.
- Negative adress references are used to access characters from the back.
- Strings can be combined with + operator.
What is the syntax of string slicing?
print(string1[3:-2])
*3rd and 2nd last character
Функція, що повертає кількість елементів у послідовності (рядок, список тощо)
len()
Функція, що визначає тип обʼєкта.
type()
Функції, що перетворюють значення у відповідний тип даних:
- Десяткове число
- Число з комою
- Рядок
int()
float()
str()
Функція, що отримує введення від користувача.
input()
Функція, що обчислює суму елементів ітерабельного обʼєкта.
sum()
Функції, що знаходять мінімальне та максимальне значення.
min(), max()
Функція, що повертає відсортований список з ітерабельного обʼєкта.
sorted()
Функція, що генерує послідовність чисел.
range()
Функція, що додає лічильник до ітерабельного обʼєкта.
enumerate()
Функція, що обʼєднує кілька ітерабельних обʼєктів у кортежі.
zip()
Функція, що застосовує функцію для кожного елемента ітерабельного обʼєкта.
map()
Функція, що відбирає елементи, що відповідають певній умові.
filter()
Функція, що відкриває файл для читання або запису.
open()
Функція, що перевіряє, чи є обʼєкт екземпляром певного класу.
isinstance()
Функція, що повертає список артибутів та методів обʼєкта.
dir()
Функція, що повертає унікальний ідентифікатор обʼєкта.
id()
Функція, що повертає абсолютне значення числа.
abs()
Функція, що округлює число до заданої кількості десяткових знаків.
round()
Як створити клас у Python?
class MyClass:
pass
Що таке метод __init__()?
Це конструктор класу, який автоматично викликається при створенні об’єкта. Використовується для ініціалізації атрибутів.
Як створити об’єкт класу?
obj = MyClass()
Як визначити метод у класі?
class MyClass:
def my_method(self):
print(“Hello”)
Як успадкувати клас у Python?
class ChildClass(ParentClass):
pass
Що таке self?
Це посилання на поточний об’єкт.
Як створити приватний атрибут?
class MyClass:
def __init__(self):
self.__private_attr = 42
Що таке інкапсуляція?
Приховування внутрішньої реалізації об’єкта. Реалізується через публічні, захищені та приватні атрибути (_, __).
Як створити абстрактний клас у Python? (Payment method)
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
pass
Що таке поліморфізм?
Поліморфізм дозволяє використовувати об’єкти різних класів через один і той самий інтерфейс (наприклад, викликати метод speak() у різних класах, навіть якщо реалізація різна).
Що таке abstract property?
Це абстрактна властивість, яку обов’язково потрібно реалізувати в підкласі.
from abc import ABC, abstractmethod
class Product(ABC):
@property
@abstractmethod
def price(self):
pass
Що таке getter, setter, deleter у Python?
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
Синтаксис функції super().
class Parent:
def greet(self):
print(“Hi from Parent”)
class Child(Parent):
def greet(self):
super().greet()
print(“Hi from Child”)
Що таке @classmethod?
Метод, який отримує доступ до самого класу, а не до об’єкта (cls замість self).
class MyClass:
count = 0
@classmethod def increment(cls): cls.count += 1
Що таке @staticmethod?
Метод, який не використовує self або cls, тобто не потребує ні об’єкта, ні класу.
class Math:
@staticmethod
def add(a, b):
return a + b