Skip to content

Hw2 Yury Popov #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
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
42 changes: 42 additions & 0 deletions README_POPOV.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Calculator

Choose a reason for hiding this comment

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

В следующий раз сразу меняй содержимое README.md :)


This readme describes mini-program Calculator you can find here.

Calculator can calculate easy arythmetical functions:
* Addition
* Subtraction
* Multiplication
* Division

## How it works

1. Clone this repo using SSH or HTTPS:

```bash
git clone [email protected]:YuryPopov/HW2_Git_and_python.git
```
**or**
```bash
git clone https://github.com/YuryPopov/HW2_Git_and_python.git
```
2. Launch application (I hope, that you are inside app folder):
```bash
python3 ./calculator.py
```
3. After prompt (*Enter expression:*) enter your expression (numbers and arythmetical operator divided with spaces) and press *"Enter"* button.
***Pay attention***, programm works with integrer and float numbers and only with +, -, *, / operators.
**Enter expression like
```
1 + 3
```
4. Enjoy the results.


## Your developers:
* Yury Popov
* Kristina Zhur
* Maria Uzun
* Anastasia Shtompel
* Alina Potyseva

![Our team](/images/picture.jpg "Our team")
64 changes: 64 additions & 0 deletions calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
def substract(a, b):

Choose a reason for hiding this comment

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

Тут и дальше. Названия a и b абсолютно не информативны :)
Лучше хотя бы num1 и num2.

return a - b


def divide(a, b):
if b == 0:
return "Error: division by zero"

Choose a reason for hiding this comment

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

Идея неплохая, но 2 момента:

  1. Если нам придет 0, то функция вернет строку. Это явно не то поведение, которое мы ожидаем :)
    В этом случае уж лучше использовать raise, но об этом поговорим в следующем семестре :)
  2. В целом-то можно даже и не обрабатывать :)
    Ну то есть вот пользователь ввел 0 --> программа упала с ZeroDivisionError. Ожидаемое поведение :)
    У нас тут нет какого-то варианта, чтоб при 0 мы бы все-равно хотели что-то да рассчитать.

return a / b


def multiplication(a, b):
answer = a * b

Choose a reason for hiding this comment

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

nit: можно сразу return a * b

return answer


def summing(a, b):
return a + b


list_of_operators = ['/', '*', '-', '+']

Choose a reason for hiding this comment

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

Если вы пишете это за пределами функции, тогда тут это константа :)
Такое нужно прописными буквами называть: list_of_operators --> LIST_OF_OPERATORS



def main(keyboard_input: str) -> float:
'''
Function checks operators, transform numbers to float,
call math function described above (substract, divide,
multiplication, summing) and return result. If operators
are not in list or numbers cannot transform into floats,
func returns error message.
'''
math_sign, operator_position = False, False

Choose a reason for hiding this comment

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

Почему False?
У вас же в math_sign будет сидеть строка, а в operator_position -- число ))


for char in range(len(keyboard_input)):

Choose a reason for hiding this comment

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

тут явно не char :)
вот если for char in keyboard_input, тогда да... Здесь же скорее индекс ))
То есть либо char_idx, либо в целом-то можно даже i :)

А вообще можно было бы вот так:

for i, char in enumerate(keyboard_input):
    if char in list_of_operators:
        math_sign = char
        operator_position = i
        break

if keyboard_input[char] in list_of_operators:
math_sign = keyboard_input[char]
operator_position = char

if math_sign == False:

Choose a reason for hiding this comment

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

Зачем? )))

if not math_sign:

return 'Enter valid expression'

Choose a reason for hiding this comment

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

Опять же по идее должны делать raise. Вы ж даже в типах указали float, а получается, что может вернуться еще и строка :)
Но пока что ладно ))


num1 = keyboard_input[:operator_position].strip()
num2 = keyboard_input[operator_position + 1:].strip()

try:
num1 = float(num1)
num2 = float(num2)
if math_sign == '/':
return divide(num1, num2)

elif math_sign == '-':
return substract(num1, num2)

elif math_sign == '+':
return summing(num1, num2)

elif math_sign == '*':
return multiplication(num1, num2)

except ValueError:
return 'Enter valid expression'

Choose a reason for hiding this comment

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

Та же история с raise



if __name__ == '__main__':
print(main(input('Enter expression:')))
Binary file added images/picture.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions images/picture.jpg:Zone.Identifier
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[ZoneTransfer]
ZoneId=3
HostUrl=https://web.telegram.org/
Comment on lines +1 to +3

Choose a reason for hiding this comment

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

Это зачем тут? :)
Если это не нужно, то, на будущее, такое лучше добавлять в .gitignore и смотреть, что добавляете через git add ))