Advertisement
Guest User

Untitled

a guest
Apr 6th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. import string
  2.  
  3. def is_valid_integer(numstr):
  4.     i = 0
  5.     is_correct = True
  6.  
  7.     while i < len(numstr) and is_correct:
  8.         if numstr[i] not in string.digits:
  9.             is_correct = False
  10.         i += 1
  11.  
  12.     return is_correct
  13.  
  14. def is_valid_operator(operatorstr):
  15.     return len(operatorstr) == 1 and operatorstr in "+-*/"
  16.  
  17. def input_sth(prompt, fail_msg, validator, chances=1):
  18.     is_correct = False
  19.     while chances > 0 and not is_correct:
  20.         input_value = input(prompt)
  21.         if validator(input_value):
  22.             is_correct = True
  23.         else:
  24.             print (fail_msg)
  25.             chances -= 1
  26.  
  27.     return input_value, is_correct
  28.  
  29. def calculate(operand1, operand2, operator):
  30.     result = ''
  31.     if operator == '+':
  32.         result = operand1 + operand2
  33.     elif operator == '*':
  34.         result = operand1 * operand2
  35.     elif operator == '-':
  36.         result = operand1 - operand2
  37.     elif operator == '/':
  38.         result = operand1 / operand2
  39.     else:
  40.         result = "Error: invalid operator!"
  41.  
  42.     return result
  43.  
  44. everything_is_ok = True
  45. while everything_is_ok:
  46.     first_number, everything_is_ok = input_sth("Enter a number: ", "Critical error: Incorrect number!", is_valid_integer)
  47.  
  48.     if everything_is_ok:
  49.         operator, everything_is_ok = input_sth("Enter a sign: ", "Ivalid sign", is_valid_operator, 3)
  50.  
  51.     if everything_is_ok:
  52.         second_number, everything_is_ok = input_sth("Enter another number: ",
  53.             "Critical error: Incorrect number!", is_valid_integer)
  54.  
  55.     if everything_is_ok:
  56.         result = calculate(int(first_number), int(second_number), operator)
  57.         print("Result:", result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement