+ 1

Tiny calculator on Python 3

Hi, wrote some code, please advice how this idea can be optimized (less code, DRY). I'm just studing the Python, so know very little...) import re while True: while True: i = input('1st number: ') pattern = r"[0-9]" if re.search(pattern, i): break else: print('Only numbers allowed. ') while True: j = input('Choose + - * / as operator: ') if j in ['+', '-', '*', '/']: break else: print('Invalid operator. Try + - * / ') while True: k = input('2nd number: ') pattern = r"[0-9]" if re.search(pattern, k): if k == '0' and j == '/': print('No division by zero. ') else: break else: print('Only numbers allowed. ') d = eval(i + j + k) print('Result:', d, '\n') print('=' * 7)

17th Aug 2018, 8:16 PM
Alex
Alex - avatar
5 odpowiedzi
17th Aug 2018, 8:23 PM
Louis
Louis - avatar
+ 1
For checking if it's only digits you don't need 're'. Just take this string method: string.isdigit()
17th Aug 2018, 8:38 PM
HonFu
HonFu - avatar
+ 1
You are asking for a number two times. I would consider writing a function that returns a number that was given by the user. For example: def number(): while True: number = input() if number in [str(n) for n in range(10)]: return int(number) Then you can just call this function two times: x=number() y=number()
17th Aug 2018, 8:59 PM
HonFu
HonFu - avatar
0
wondering if I could shorten 'while' cycle...
17th Aug 2018, 8:17 PM
Alex
Alex - avatar
0
Mates, thank yor for help! Here's some new iteration: ========= while 1: try: a, b, c = input ('Enter mathematical task with _spaces_\nExample: 2 + 9: '). split () d = eval(a + b + c) except ZeroDivisionError: print('Do not divide by zero.\n') continue except Exception as err: print('Error. Please use spaces and digits.\n') continue else: print('Result:', d, '\n') ========= UPD: have no idea how enforce user's input to add spaces...
20th Aug 2018, 3:07 PM
Alex
Alex - avatar