Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions HW2_Senkovenko/README.md
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Привет! (´• ω •`)ノ
Блестящая работа, молодцы! Комментарии к работе вы найдете ниже.

  • О README.md: Очень подробное и понятное ридми! Отличным решением было добавить примеры, пояснения к ошибкам и интерактивный выход из программы. (+1 доп. балл)
  • О коммитах и структуре репозитория: Очень здорово, что и коммиты, и PR имеют осмысленные названия. Очень большая и красивая работа!

О коде будет комментарий чуть ниже в виде построчного ревью.
Баллы: 10/10 (README) + 10/10 (Forks) + 80/80 (код и коммиты) + 12 доп. =
= 100/100 + 12 доп. = 112 баллов

Вы проделали большую работу. Молодцы! (´。• ω •。`)
(тимлид, не забудь показать ревью всей команде)

Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Калькулятор / Calculator

#### _**HomeWork №2.**_


## Description

The calculator is written in Python and performs basic arithmetic operations.

Function | Description | Contributor
----------------|------------|----------
main()| program loop, input/output, error handling | Alexey Senkovenko (lead)
addition(val1, val2) | val1 + val2 | Alisa Senko
subtraction(val1, val2)| val1 - val2 | Aglaya Tsidulko
division(val1, val2) | val1 / val2 | Anastasiia Kolos
multiplication(val1, val2)| val1 * val2 | Elizaveta Menshikova

README.md - main text by Alisa Senko, en-translation by Alexey Senkovenko.

## How to run the script
The script is launched from the console.

1. Clone the repository:
```
git clone <URL>
```
2. Go to the project folder and run the script:
```
python3 calculator.py
```
or
```
python calculator.py
```
depending on your OS.

### _Example_
```
> python calculator.py
Hello!
Type exit to finish calculations
Enter your expression:
> 3 * 15
Result: 45.0
Enter your expression:
> 3 / 0
Math Error: Cannot divide by zero
Enter your expression:
> 3 + 15.4
Result: 18.4
Enter your expression:
> 3.0 + 3.9
Result: 6.9
```
### _Error handling:_
* Input-check that exactly 3 elements are given, separated by a space - two numbers and an operator:
```
Enter your expression:
> 2 +
Value Error: Incorrect number of values, check your input: value1 operator value2
Enter your expression:
> 2+3
Value Error: Incorrect number of values, check your input: value1 operator value2
```
* Division by zero:
```
Enter your expression:
> 3 / 0
Math Error: Cannot divide by zero
```
* Check for the correct input format:
```
Enter your expression:
> 3,5 + 3,5
Value Error: could not convert string to float: '3,5'
Enter your expression:
> 4.0 ++ 5
Key Error: "Used unknown operator, supported operators are: ('+', '-', '*', '/')"
Enter your expression:
> - - 3
Value Error: could not convert string to float: '-'
```
* Unexpected Error

### _How to end the calculations_
To finish your work, type `exit` in the input field :
```
Enter your expression:
> exit
Program closed
```

## ✨✨Our team!✨✨

![alt text](imgs_Senkovenko/photo_2025-09-18_20-48-29.jpg)
60 changes: 60 additions & 0 deletions HW2_Senkovenko/calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
def subtraction(val1, val2):
return val1 - val2

def addition(val1, val2):
return val1 + val2

def multiplication(val1, val2):
return val1 * val2

def division(val1, val2):
if val2 == 0:
raise ZeroDivisionError("Cannot divide by zero")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь нет необходимости в вызове ошибки ZeroDivision, поскольку питон сам её поднимает. Также это дублирует функционал из except блока функции main, что немного избыточно.

return val1 / val2


operators = {
'+': addition,
'-': subtraction,
'*': multiplication,
'/': division
}
Comment on lines +16 to +21
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень крутое решение сделать вызов функций из словаря! (+1 доп балл)


def main():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У вас итак замечательная работа, но ещё круче её может сделать дополнение в виде docstrings и аннотаций функций)

print("Hello! \nType exit to finish calculations")

while True:
check = input("Enter your expression: \n")

if "exit" in check:
print("Program closed")
break

try:
line = check.split()

if len(line) != 3:
raise ValueError("Incorrect number of values, check your input: value1 operator value2")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здорово, что написали вызов ошибки, очень продвинутое решение)


val1 = float(line[0])
oper = line[1]
val2 = float(line[2])

if oper not in operators:
raise KeyError (f"Used unknown operator, supported operators are: {tuple(operators.keys())}")

result = operators[oper](val1, val2)

print(f"Result: {result}")

except ValueError as valerr:
print(f"Value Error: {valerr}")
except KeyError as keyerr:
print(f"Key Error: {keyerr}")
except ZeroDivisionError as zeroerr:
print(f"Math Error: {zeroerr}")
except Exception as exc:
print(f"Unexpected Error: {exc}")
Comment on lines +50 to +57
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отличное решение по try-execpt блоку!


if __name__ == "__main__":
main()
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.