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
97 changes: 97 additions & 0 deletions HW2_Laskina/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# 🧮 HW2 Team Calculator

> A simple Python calculator that evaluates mathematical expressions in the format: `number operator number`.

---

## 📌 Description

This repository contains a team-developed implementation of a basic calculator as part of a homework assignment.
The program accepts an expression via `input()`, for example:

`5 + 3`

and prints the result of the calculation.

Supported operations: `+`, `-`, `*`, `/`.

Each mathematical operation is implemented in a separate function:
- `add(x, y)` — addition
- `sub(x, y)` — subtraction
- `mul(x, y)` — multiplication
- `div(x, y)` — division (with error handling for division by zero)

The main logic for parsing and routing the expression is handled in the `main()` function.

## ⚠️ Input Errors

The calculator validates your input and will show error messages in the following cases:

- Missing spaces:
`5+3` → Error: the expression must be in the format `<number> <operator> <number>`

- Comma as decimal separator:
`3,5 + 2` → Error: use a dot for the decimal part, not a comma.

- Unsupported operator:
`5 ^ 2` → Error: operator '^' is not supported. Available: +, -, *, /

- Division by zero:
`7 / 0` → Error: Division by zero is not allowed

---

## 👥 Development Team

| Contributor | Contribution |
|---------------------|-------------------------------------------|
| Natalia Laskina | `main()` — main logic |
| Daria Bobrova | `add()` — addition |
| Vadim Bolshakov | `sub()` — subtraction |
| Nikita Maksimov | `mul()` — multiplication |
| Artem Stetoi | `div()` — division, `main()`, `parse_number()` |

---

## 🚀 How to Use

### Requirements:
- Python 3.6 or higher

### Running the Program:

1. Clone the repository (if not already done):
```bash
git clone -b HW2_Laskina https://github.com/NataliaLaskina/HW2_NBLaskina.git

2. Navigate to the project folder:
```bash
cd HW2_NBLaskina
3. Run the calculator:
```bash
python HW2_Laskina/calculator.py
4. Enter an expression in the format:
```bash
<number> <operator> <number>

#Example: 10 - 4
5. The program will output the result:
6

📂 Project Structure

- `HW2_NBLaskina/` — root folder
- `HW2_Laskina/` — main project folder
- `calculator.py` — main script with 6 functions:
- `add(x, y)`
- `sub(x, y)`
- `mul(x, y)`
- `div(x, y)`
- `parse_number(token)`
- `main()`
- `imgs/` — folder for project screenshots
- `README.md` — this file

✨ Completed as part of a course assignment. All team members contributed equally to the development.

![Разработчики за работой](imgs/my-image.jpg)
63 changes: 63 additions & 0 deletions HW2_Laskina/calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
correct_oper = ["+", "-", "*", "/"]
def div(x: float, y: float) -> float:
if y == 0:
raise ZeroDivisionError("Division by zero is not allowed")
Comment on lines +3 to +4

Choose a reason for hiding this comment

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

Огонь, что сделана ошибка - но тогда пусть бы уже само кидало деление на ноль?

return x / y

def add(x: float, y: float) -> float:

Choose a reason for hiding this comment

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

x, y мне нравятся больше, чем a, b, но в целом однобуквенные переменные стоит держать только в счетчиках. num1, num2 было бы неплохим решением.

return x + y

def mul(x: float, y: float) -> float:
return x * y

def sub(x: float, y: float) -> float:
return x - y

def parse_number(token: str):
if "." in token or "e" in token.lower():
return float(token)
return int(token)
def main():
Comment on lines +19 to +20

Choose a reason for hiding this comment

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

Suggested change
return int(token)
def main():
return int(token)
def main():

Не хватает отступов в паре мест. Это очень помогает читаемости, честное слово.

while True:
calc = input("Enter an expression like: <number> <operator> <number>\n"
"Example: 2.5 * 4 \n> ").strip()

if "," in calc:
print("Error: use a dot for the decimal part, not a comma.")
continue

parts = calc.split()
if len(parts) != 3:
print("Error: the expression must be in the format: <number> <operator> <number>")
continue

left, op, right = parts

if op not in correct_oper:
print(f"Error: operator '{op}' is not supported. Available: {', '.join(correct_oper)}")
continue

try:
x = parse_number(left)
y = parse_number(right)
except ValueError:
print("Error: invalid number. Use integers or real values.")
continue

try:
if op == "+":
res = add(x, y)
elif op == "-":
res = sub(x, y)
elif op == "*":
res = mul(x, y)
elif op == "/":
res = div(x, y)
except ZeroDivisionError as e:
print(f"Error: {e}")
continue

print("Result:", res)

if __name__ == "__main__":
main()
Binary file added HW2_Laskina/imgs/my-image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added HW2_Laskina/imgs/photo_2025-09-21_16-51-44.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.