Simple Data Types / Прості типи даних

Day 1. Logic, Syntax, and Data Types of Python / День 1. Логіка, синтаксис та типи даних у Python

Python basics for UBDS^2026, 13-17 July 2026, Uzhhorod, Ukraine

Plan / План: - Installation and setup with uv / Встановлення та налаштування за допомогою uv - Jupyter notebooks / Jupyter notebooks - Variables and operators / Змінні та оператори - Int and float / Цілі та дійсні числа - Strings / Рядки - Lists and tuples / Списки та кортежі - Dictionaries / Словники - Functions and OOP / Функції та ООП

Variables and Comments / Змінні та коментарі

In Python, you can easily create variables to store different types of data. There is no need to declare the variable type beforehand. Use # to add comments to your code.

//

В Python ви можете легко створювати змінні для зберігання різних типів даних. Немає потреби оголошувати тип змінної заздалегідь. Використовуйте # для додавання коментарів у ваш код.

# This is a comment
# Це коментар
var = 10
print(var)
# Variables can be overwritten with a different type (dynamic typing)
# Змінні можна перезаписувати іншим типом (динамічна типізація)
var = "Hello, world!"
print(var)
print(type(var))  # type() shows the data type / показує тип даних

Variable naming rules / Правила іменування змінних

Variable names can contain letters, digits, and underscores, but must start with a letter or underscore. Python has reserved keywords that cannot be used as variable names.

//

Імена змінних можуть містити літери, цифри та підкреслення, але повинні починатися з літери або підкреслення. Python має зарезервовані слова, які не можна використовувати як імена змінних.

# Valid variable names / Правильні імена змінних
cell_count = 150
_temperature = 36.6

Simple Data Types / Прості типи даних

  • Integers (int) / Цілі числа
  • Floating-point numbers (float) / Числа з плаваючою крапкою (дійсні числа)
  • Strings (str) / Рядки
  • Booleans (bool) / Логічні/булеві змінні

Numerical data types: int and float / Числові типи даних: int та float

  • int (integer) represents whole numbers, both positive and negative, without a decimal point. Examples: -3, 0, 42.
  • float (floating-point number) represents real numbers, which can include a decimal point. Examples: 3.14, -0.001, 2.0.

//

  • int (ціле число) представляє цілі числа, як додатні, так і від’ємні, без десяткової крапки. Приклади: -3, 0, 42.
  • float (число з плаваючою крапкою) представляє дійсні числа, які можуть містити десяткову крапку. Приклади: 3.14, -0.001, 2.0.
# Creating integers and floats / Створення цілих та дійсних чисел
age = 25          # integer / ціле число
temperature = -4  # integer / ціле число

pi = 3.14159      # float / дійсне число
weight = 75.5     # float / дійсне число

# The type() function tells us the type of data / Функція type() показує тип даних
print("Age:", age, "Type:", type(age))
print("Pi:", pi, "Type:", type(pi))

Mathematical operations / Математичні операції

Python supports standard arithmetic operations. Let’s see how they work with numbers.

//

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

# Basic arithmetic / Базова арифметика
a = 15
b = 4

print("Addition / Додавання:", a + b)
print("Subtraction / Віднімання:", a - b)
print("Multiplication / Множення:", a * b)
print("Division / Ділення (always float / завжди float):", a / b)
# Integer division, remainder, exponent / Цілочисленне ділення, залишок, підведення до степеня
print("Integer division / Цілочисленне ділення:", a // b)
print("Remainder / Залишок від ділення (модуль):", a % b)
print("Exponentiation / Піднесення до степеня:", a ** b)
# Python follows standard mathematical order of operations
# Python слідує стандартному порядку математичних операцій
complex_calculation = (a + b) * 2 - (a / 3)
print("Result / Результат:", complex_calculation)

Type conversion / Перетворення типів

You can convert between types using int(), float(), str() functions. When you perform operations with mixed types, Python converts automatically.

//

Ви можете перетворювати типи за допомогою функцій int(), float(), str(). При операціях з різними типами Python конвертує автоматично.

# Explicit type conversion / Явне перетворення типів
x = 5
print(float(x), type(float(x)))  # int to float

# float to int truncates the decimal part / відкидає дробову частину
y = 3.7
print(int(y), type(int(y)))  # 3, not 4
# Automatic conversion: int + float = float
# Автоматичне перетворення: int + float = float
result = 5 + 2.0
print(result, type(result))

# String to number / Рядок у число
number_str = "42"
print(int(number_str) + 8)  # 50

⚠️ Common pitfalls with numbers / Типові проблеми з числами

Numbers in Python have some non-obvious behaviors that are important to understand.

//

Числа в Python мають деякі неочевидні особливості, які важливо розуміти.

# Division by zero / Ділення на нуль
# Causes ZeroDivisionError / Викликає ZeroDivisionError

result = 10 / 0   # ZeroDivisionError: division by zero
# Float precision issue / Проблема точності float
# Floats are stored in binary format, leading to small rounding errors
# Дійсні числа зберігаються у двійковій системі, що призводить до малих похибок округлення

print(0.1 + 0.2)          # Expected 0.3? / Очікували 0.3?
print(0.1 + 0.2 == 0.3)   # False!
# Python int has no size limit / Python int не має обмежень на розмір
big_number = 10 ** 100
print("Big int:", big_number)

# But float has limits / Але float має обмеження
print(1e308)   # OK, largest finite float / найбільший скінченний float
print(1e309)   # inf, overflow / переповнення!

Strings (str) / Рядки

  • A string is a sequence of characters enclosed in single quotes ('...') or double quotes ("...").

//

  • Рядок — це послідовність символів, взята в одинарні ('...') або подвійні лапки ("...").
# Creating strings / Створення рядків
word_1 = "Hello"
word_2 = 'UBDS^3'

# Concatenation — joining strings with + / Конкатенація — об'єднання рядків через +
message = word_1 + " " + word_2 + "!"
print(message)
# String repetition / Множення рядків
print("One" * 3)
print("-" * 30)  # Useful for visual separators / Корисно для роздільників

String indexing and slicing / Індексація та зрізи рядків

Each character in a string has an index, starting from 0. You can access substrings using slicing.

//

Кожен символ рядка має індекс, починаючи з 0. Ви можете отримати підрядки за допомогою зрізів.

# Indexing and slicing / Індексація та зрізи
text = "Biology"
print("First char / Перший символ:", text[0])     # B
print("Last char / Останній символ:", text[-1])   # y
print("Slice [1:4]:", text[1:4])                  # iol
print("Length / Довжина:", len(text))             # 7

String methods / Методи рядків

Strings have many useful built-in methods for text manipulation.

//

Рядки мають багато корисних вбудованих функцій (методів) для роботи з текстом.

# Case and whitespace methods / Методи регістру та пробілів
text = "  jupyter notebook is AWESOME!  "

print("Original / Оригінал:", repr(text))
print("Uppercase / Великими літерами:", text.upper())
print("Lowercase / Малими літерами:", text.lower())
print("Strip whitespace / Видалення пробілів:", repr(text.strip()))
# Replace and f-strings / Заміна та f-рядки
text = "  jupyter notebook is AWESOME!  "
print("Replace / Заміна:", text.replace("AWESOME", "GREAT"))
print("Capitalize / З великої літери:", text.strip().capitalize())

# f-strings — formatted strings / форматовані рядки
version = 3
print(f"I am learning Python {version}")  # f-string is very useful! / дуже зручний!

⚠️ Common pitfalls with strings / Типові проблеми з рядками

Strings are immutable — once created, individual characters cannot be changed.

//

Рядки є незмінними — після створення окремі символи не можна змінити.

# Cannot concatenate string and number directly
# Не можна об'єднати рядок і число напряму
# result = "Age: " + 25  # TypeError: can only concatenate str to str

# Solution: convert to string / Рішення: перетворити на рядок
result = "Age: " + str(25)
print(result)
# Strings are immutable / Рядки є незмінними
text = "Hello"
text[0] = "h"  # TypeError: 'str' object does not support item assignment
# IndexError: index out of range / Індекс за межами рядка
print(text[100])  # IndexError: string index out of range

Boolean data type (bool) / Логічний тип даних (bool)

  • Represents truth values: True and False. Note the capitalization!
  • Used for logical operations and control flow.

//

  • Відповідає істинним значенням: True (Істина) та False (Хиба). Зверніть увагу на велику літеру в нписанні.
  • Використовується для логічних операцій та керування потоком програми.
# Creating booleans and comparisons / Створення логічних змінних та порівняння
is_ubds_cool = True
print("Is UBDS^3 cool? / Чи крута UBDS^3?:", is_ubds_cool)

# Comparison operators / Оператори порівняння
x = 10
y = 20
print("x == y (Equal / Дорівнює):", x == y)
print("x < y (Less than / Менше):", x < y)
print("x != y (Not equal / Не дорівнює):", x != y)
# Logical operators (and, or, not) / Логічні оператори (та, або, ні)
a = True
b = False

print("a and b:", a and b) # True only if BOTH are True / True лише якщо ОБИДВА True
print("a or b:", a or b)   # True if AT LEAST ONE is True / True якщо ХОЧА Б ОДНЕ True
print("not a:", not a)     # Inverts the value / Інвертує значення

Truthiness / Булева інтерпретація інших типів

Any Python value can be interpreted as bool. Empty and zero values are False, everything else is True.

//

Будь-яке значення Python може бути інтерпретоване як bool. Порожні та нульові значення — це False, все інше — True.

# Truthiness examples / Приклади істинності
print("bool(0):", bool(0))          # False
print("bool(1):", bool(1))          # True

print("bool(''):", bool(""))        # False - empty string / порожній рядок
print("bool('Hi'):", bool("Hi"))    # True

print("bool([]):", bool([]))        # False - empty list / порожній список
print("bool([1]):", bool([1]))      # True

Sequence and Mapping Types / Типи послідовностей та відображень

  • Lists and nested lists (list) / Списки та вкладені списки (list)
  • Methods for lists / Методи списків
  • Operations on lists / Операції над списками
  • Tuples (tuple) / Кортежі (tuple)
  • Dictionaries (dict) / Словники (dict)
  • Methods for dictionaries / Методи словників

Lists (list) / Списки

A list is an ordered, mutable collection of items. It can contain items of different types.

//

Список — це впорядкована, змінна (її можна змінювати) колекція елементів. Вона може містити елементи різних типів.

# Creating lists / Створення списків
str_list = ["one", "two", "three"]
mixed_list = [1, "hello", 3.14, True]

print("String list:", str_list)
print("Mixed list:", mixed_list)

List Slicing / Індексація списків

# Accessing elements by index (starts from 0)
# Доступ до елементів за індексом (починається з 0)
print("First element / Перший елемент:", str_list[0])
print("Last element / Останній елемент:", str_list[-1])
int_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1,]

# Acces to the range of elemets
# Доступ до зрізу елементів списку
print(int_list[1:3])

# Acces to the subset of lements
# Доступ до зрізу елементів списку з певним кроком індексів
print(int_list[1:8:2])

List Methods / Методи списків

# Adding elements / Додавання елементів
numbers = [10, 20, 30]

numbers.append(40)  # Add to the end / Додати в кінець
print("After append / Після додавання:", numbers)

numbers.insert(1, 15)  # Insert at index 1 / Вставити за індексом 1
print("After insert / Після вставки:", numbers)
# Removing elements and slicing / Видалення елементів та зрізи
numbers.remove(20)  # Remove specific value / Видалити конкретне значення
print("After remove / Після видалення:", numbers)

# Slicing [start:end], end not included / Зрізи, кінець не включається
print("Slice [1:3] / Зріз [1:3]:", numbers[1:3])

Nested Lists / Вкладені списки

# Lists can contain other lists / Списки можуть містити інші списки
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

print("First row / Перший рядок:", matrix[0])
print("Element at row 1, col 2 / Елемент у 1-му рядку, 2-му стовпці:", matrix[0][1])

⚠️ Common pitfalls with lists / Типові проблеми зі списками

# IndexError: accessing beyond list length
# IndexError: доступ за межі списку
str_list = ["one", "two", "three"]

# Always check length / Завжди перевіряйте довжину
print("List length / Довжина списку:", len(str_list))

print(str_list[10])  # IndexError: list index out of range
# Shallow copy trap / Пастка поверхневого копіювання
a = [1, 2, 3]
b = a          # b is NOT a copy, it references the same list
               # b НЕ копія, це посилання на той самий список
b.append(4)
print("a:", a)  # [1, 2, 3, 4] a also changed / a теж змінився
print("b:", b)  # [1, 2, 3, 4]

# To make a real copy / Щоб зробити справжню копію:
c = a.copy()
c.append(5)
print("a:", a)  # [1, 2, 3, 4] unchanged / не змінився
print("c:", c)  # [1, 2, 3, 4, 5]

Tuples (tuple) / Кортежі

Similar to lists, but immutable (cannot be changed after creation). Useful for fixed data.

//

Схожі на списки, але незмінні (не можуть бути змінені після створення). Корисно для фіксованих даних.

# Creating tuples / Створення кортежів
coordinates = (10, 20)
colors = ("red", "green", "blue")

print("Coordinates:", coordinates)
print("First color:", colors[0])
# Tuple unpacking / Розпакування кортежу
x, y = coordinates
print(f"x = {x}, y = {y}")
# Tuples CANNOT be changed / Кортежі НЕ МОЖНА змінювати
coordinates[0] = 15  # TypeError: 'tuple' object does not support item assignment

Dictionaries (dict) / Словники

Dictionaries store data in key-value pairs. They are unordered and mutable. Keys must be unique.

//

Словники зберігають дані у вигляді пар “ключ-значення”. Вони невпорядковані та змінні. Ключі мають бути унікальними.

Dictionaries Creation and Data Access / Створення словників та доступ до даних

# Creating dictionaries / Створення словників
student = {"name": "Anna",
           "age": 20,
           "major": "Biology"}

print("Student dict / Словник студента:", student)
print("Student name / Ім'я студента:", student["name"])
# Alternative way with .get method / Альтернативний підхід з методом .get

print("Student name / Ім'я студента:", student.get("name"))

Updating Dictionary Items / Оновлення вмісту словника

# Methods for dictionaries / Методи для словників
student["grade"] = "A" # Add new key-value / Додати нову пару
student["age"] = 21    # Update existing value / Оновити наявне значення

print("Updated dict / Оновлений словник:", student)

# Dict methods / Методи словників щоб отримати всі ключі або всі значення
print("Keys / Ключі:", list(student.keys()))
print("Values / Значення:", list(student.values()))

Removing Dictionary Items / Видалення елементів словника

  • del: removes an item using its key / видалення елементу за ключем
  • pop(): removes the item with the given key and returns its value / видалення елементу за ключем із поверненням значення, що видаляється
  • clear(): removes all items from the dictionary / видалення всіх елементів словника
  • popitem(): removes and returns the last inserted key–value pair / видалення останньї доданої пари ключ-значення із поверененням пари, що видаляється
del student['age']
print(student)
removed_val = student.pop('grade')
print(removed_val)
print(student)
last_item = student.popitem()
print(last_item)
print(student)
student.clear()
print(student)

Nested Dictionaries / Вкладені словники

# with key "grade" is avalibale the nested dictionary / під ключем "grade" знаходиться вкладений словник
new_student = {"name": "Bob",
               "age": 22,
               "major": "Biology",
               "grades":{"biology":"A",
                         "chemistry":"A",
                         "math":"C"}}

print(new_student)
print(new_student["age"])
print(new_student["grades"]["math"])

⚠️ Common pitfalls with dictionaries / Типові проблеми зі словниками

# KeyError: accessing a non-existent key
# KeyError: доступ до неіснуючого ключа
print(student["phone"])  # KeyError: 'phone'
# Safe access with .get() / Безпечний доступ через .get()
print(student.get("phone", "N/A"))  # Returns default if key missing / Повернe значення за замовчуванням
print(student.get("name", "N/A"))   # Returns "Anna"

Sets of values (set) / Словники

A set is a data structure used to store multiple items in a single variable. Sets do not allow duplicate values. Unlike lists, sets do NOT keep the order of elements. You cannot access elements by index.

//

Набори це стурктури даних для зберігання багатьох значень в одній зміннй, вони не дозволяються значенням повторюватись. Елементи наборів не впорядковані, елементи набору не можна отримати за індексом.

# Using a list / Використаємо список
l = ["apple", "banana", "apple", "chocolate"]
print(l)

# Using a set / Використаємо набір
s = {"apple", "banana", "apple", "chocolate"}
print(s)
# sets useful for checking membership / набори зручні для перевірки приналежності

print("apple" in s)   # True
print("milk" in s)    # False
# Adding elements to the set / додавання елементу до набору
s.add("cheese")
print(s)
# Union of the sets, duplicates are automatically removed / об'єднання наборів, повтори автоматично видалені
set_2 = {"milk", "bread", "banana"}
print(s.union(set_2))
# Intersection of the sets, finding the common elements / перетин наборів, пошук спільних елементів
set_2 = {"milk", "bread", "banana"}
print(s.intersection(set_2))
# Difference between the sets / різниця між наборів
set_2 = {"milk", "bread", "banana"}
print(s.difference(set_2))

⚠️ Common pitfalls with sets / Типові проблеми з наборами

# TypeError, sets are unordered data type / набори це невпорядкований тип даних
s[0]

Functions and Object-Oriented Programming Concepts / Функції та концепції ООП

  • Concepts of functions / Концепції функцій
  • Syntax of function definition and calling (def) / Синтаксис визначення та виклику функції
  • Parameters and arguments / Параметри та аргументи
  • Return values (return) / Значення, що повертаються
  • Object-oriented programming (OOP) concepts / Концепції об’єктно-орієнтованого програмування
  • Classes and objects / Класи та об’єкти
  • Methods and attributes / Методи та атрибути

Functions / Функції

A function is a block of reusable code that performs a specific task. We use the def keyword.

//

Функція - це блок коду для багаторазового використання, який виконує певну задачу. Ми використовуємо ключове слово def.

# Defining a simple function / Визначення простої функції
def greet_user():
    print("Welcome to Python / Ласкаво просимо до Python")

# Calling the function / Виклик функції
greet_user()
greet_user()  # Can be called multiple times / Можна викликати кілька разів
# Function with parameters and return value
# Функція з параметрами та значенням, що повертається
def add_numbers(x, y):
    result = x + y
    return result  # return gives the value back / return повертає значення

sum_result = add_numbers(5, 7)
print("Sum is / Сума:", sum_result)
# Function that returns a formatted string
# Функція, що повертає форматований рядок
def describe_person(name, age):
    return f"{name} is {age} years old! / {name} має {age} років!"

print(describe_person("Maria", 22))

Default arguments / Аргументи за замовчуванням

Function parameters can have default values that are used when no argument is provided.

//

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

# Default arguments / Аргументи за замовчуванням
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Ivan"))                # Uses default / Значення за замовчуванням
print(greet("Maria", "Привіт"))    # Custom greeting / Власне привітання

⚠️ Common pitfalls with functions / Типові проблеми з функціями

# Common mistake: forgetting return / Поширена помилка: забутий return
def add_without_return(x, y):
    result = x + y
    # forgot return! / забули return!

value = add_without_return(5, 3)
print("Result / Результат:", value)  # None, function returned nothing / Функція нічого не повернула

From Function to Class / Від функції до класу

A class is a way to group related data (attributes) and functions (methods) together. Think of it like this: a class is a recipe, and an object is a dish made from that recipe. Let’s start with a regular function, then wrap it into a class.

//

Клас — це спосіб об’єднати пов’язані дані (атрибути) та функції (методи) разом. Уявіть: клас — це рецепт, а об’єкт — це страва, приготовлена за цим рецептом. Почнемо зі звичайної функції, а потім помістимо її в клас.

# Step 1: A regular function to calculate GC-content of a DNA sequence
# Крок 1: Звичайна функція для обчислення GC-вмісту в послідовності ДНК

def gc_content(sequence):
    """Calculate the percentage of G and C bases / Обчислити відсоток G та C основ
    
    """
    sequence = sequence.upper()  # Convert to uppercase to count both 'g' and 'G' / Преобразовать в верхний регистр, чтобы считать и 'g', и 'G'
    g_count = sequence.count("G")
    c_count = sequence.count("C")
    return (g_count + c_count) / len(sequence) * 100  # Return percentage / Вернуть процент

# Using the function / Використання функції
dna = "ATGCGATCGA"
print(f"GC-content of {dna}: {gc_content(dna):.1f}%")

Now let’s create a DNASequence class that stores the sequence data and has the same function as a method. The advantage: the class keeps the sequence and its name together, and methods can access them via self.

//

Тепер створимо клас DNASequence, який зберігає дані послідовності та має ту саму функцію як метод. Перевага: клас тримає послідовність та її назву разом, а методи мають доступ до них через self.

# Step 2: Wrapping the function into a class
# Крок 2: Обгортання функції у клас

class DNASequence:
    def __init__(self, sequence, name="unknown"):
        self.sequence = sequence.upper()   # attribute - stored data / атрибут - збережені дані
        self.name = name                   # attribute / атрибут

    def gc_content(self):  # method — same logic as the function above!
        """Calculate GC-content / Обчислити GC-вміст
        
        """
        g_count = self.sequence.count("G")  # uses self.sequence instead of parameter
        c_count = self.sequence.count("C")  # використовує self.sequence замість параметра
        return (g_count + c_count) / len(self.sequence) * 100

    def length(self):
        """Return sequence length / Повернути довжину послідовності
        
        """
        return len(self.sequence)
# Step 3: Creating objects and using them
# Крок 3: Створення об'єктів та їх використання

seq1 = DNASequence("ATGCGATCGA", "Gene_A")
seq2 = DNASequence("AAATTTAAATTT", "Gene_B")

# Accessing attributes / Доступ до атрибутів
print(f"Name: {seq1.name}, Sequence: {seq1.sequence}")

# Calling methods / Виклик методів
print(f"{seq1.name}: length={seq1.length()}, GC={seq1.gc_content():.1f}%")
print(f"{seq2.name}: length={seq2.length()}, GC={seq2.gc_content():.1f}%")

Exercises / Вправи

Exercise 1

You are given a list of DNA sequences / Вам надано перелік послідовностей ДНК:

seqs = ["ATGCGT", "TTAGGC", "CCGTAA"]

Tasks:

  1. Print the first sequence / Виведіть першу послідовність
  2. Print the last sequence / Виведіть останню послідовність
  3. Print the first 3 nucleotides of the first sequence / Виведіть перші три нуклеотида першої послідовності
  4. Print the length of the second sequence / Виведіть довжину останньої послідовності
# Write your answer here

Exercise 2

Using the same list / Використовуючи список з попереднього завдання:

seqs = ["ATGCGT", "TTAGGC", "CCGTAA"]

Tasks: 1. Replace the second sequence with “GGGAAA” / Замініть другу послідовність на “GGGAAA” 2. Add a new sequence “TTTCCC” / Додайте нову послідовність “TTTCCC” 3. Print the updated list / Виведіть оновлений список

# Write your answer here

Exercise 3

You are given a list with repeated sequences / Вам надано список із послідовностей, що можуть повторюватись:

seqs = ["ATGCGT", "ATGCGT", "TTAGGC", "CCGTAA"]

Tasks:

  1. Convert the list into a set / Перетворіть список в набір
  2. Print the result / Виведіть результат
  3. How many unique sequences are there? / Скільки унікальних послідовностей лишилось?
# Write your answer here

Exercise 4

You are given a dictionary with sequence names and sequences / Вам надано словник із назв послідовностей та самих послідовностей:

data = {
    "seq1": "ATGCGT",
    "seq2": "TTAGGC",
    "seq3": "CCGTAA"
}

Tasks:

  1. Print the sequence of “seq1” / Виведіть послідовність “seq1”
  2. Print the sequence of “seq3” / Виведіть послідовність “seq3”
  3. Add a new sequence: “seq4”: “GGGAAA” / Додайте новоу послідовність “GGGAAA” із назвою “seq4”
  4. Update “seq2” to “TTTTTT” / Оновіть послідовність “seq2” значенням “TTTTTT”
# Write your answer here

Exercise 5

You are given a nested dictionary / Вам надано вкладений словник:

fasta = { “seq1”: {“sequence”: “ATGCGT”, “length”: 6}, “seq2”: {“sequence”: “TTAGGCA”, “length”: 7} }

Tasks:

  1. Print the sequence of “seq1” / Виведіть послідовність “seq1”
  2. Print the length of “seq2” / Виведіть довжину “seq1”
  3. Add a new key “species”: “human” to “seq1” / Додайте новий ключ "species":"human" до “seq1”
# Write your answer here

Additional Exercises / Додаткові вправи

Use what you have learned to complete the tasks below.

//

Використайте те, що ви вивчили, щоб виконати завдання нижче.

Exercise 1: Variables and Math

Create two variables, length and width of a rectangle (e.g., 5 and 10). Calculate and print its area and perimeter.

//

Вправа 1: Змінні та математика

Створіть дві змінні, length (довжина) та width (ширина) прямокутника (напр. 5 та 10). Обчисліть та виведіть його площу та периметр.

# Write your answer here

Exercise 2: Strings and Lists

Create a list of your 3 favorite cities based on strings. Add a 4th city to the end using python method. Print the list and the second city from the list.

//

Вправа 2: Рядки та Списки

Створіть список ваших 3 улюблених міст у вигляді рядків. Додайте 4-те місто в кінець за допомогою методу. Виведіть список і друге місто зі списку.

# Write your answer here

Exercise 3: Functions and Dicts

Write a function print_student_info(student_dict) that takes a dictionary with keys ‘name’ and ‘age’ and prints “Student [name] is [age] years old”. Create a dictionary and call the function.

//

Вправа 3: Функції та Словники

Напишіть функцію print_student_info(student_dict), яка приймає словник з ключами ‘name’ та ‘age’ і виводить “Студент [name] має [age] років”. Створіть словник і викличте функцію.

# Write your answer here

Exercise 4: Type Conversion and Pitfalls

  1. Given the string number_str = “123”, convert it to int, add 77, and print result with type.
  2. Check: does 0.1 + 0.2 equal 0.3? Print the comparison result and explain why in a comment.

//

Вправа 4: Перетворення типів та підводні камені

  1. Дано рядок number_str = “123”, перетворіть його на int, додайте 77 і виведіть результат з типом.
  2. Перевірте: чи дорівнює 0.1 + 0.2 значенню 0.3? Виведіть результат порівняння та поясніть чому у коментарі.
# Write your answer here