Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import string
- def is_valid_integer(numstr):
- i = 0
- is_correct = True
- while i < len(numstr) and is_correct:
- if numstr[i] not in string.digits:
- is_correct = False
- i += 1
- return is_correct
- def is_valid_operator(operatorstr):
- return len(operatorstr) == 1 and operatorstr in "+-*/"
- def input_sth(prompt, fail_msg, validator, chances=1):
- is_correct = False
- while chances > 0 and not is_correct:
- input_value = input(prompt)
- if validator(input_value):
- is_correct = True
- else:
- print (fail_msg)
- chances -= 1
- return input_value, is_correct
- def calculate(operand1, operand2, operator):
- result = ''
- if operator == '+':
- result = operand1 + operand2
- elif operator == '*':
- result = operand1 * operand2
- elif operator == '-':
- result = operand1 - operand2
- elif operator == '/':
- result = operand1 / operand2
- else:
- result = "Error: invalid operator!"
- return result
- everything_is_ok = True
- while everything_is_ok:
- first_number, everything_is_ok = input_sth("Enter a number: ", "Critical error: Incorrect number!", is_valid_integer)
- if everything_is_ok:
- operator, everything_is_ok = input_sth("Enter a sign: ", "Ivalid sign", is_valid_operator, 3)
- if everything_is_ok:
- second_number, everything_is_ok = input_sth("Enter another number: ",
- "Critical error: Incorrect number!", is_valid_integer)
- if everything_is_ok:
- result = calculate(int(first_number), int(second_number), operator)
- print("Result:", result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement