Skip to content

Commit 0754e74

Browse files
author
Karan Goel
committed
Safer way of user input
1 parent 423927f commit 0754e74

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed

Numbers/calc.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
1-
# -*- coding: cp1252 -*-
2-
"""
3-
Calculator - A simple calculator to do basic operators.
4-
"""
5-
6-
if __name__ == '__main__':
7-
num1 = input("Number 1: ")
8-
num2 = input("Number 2: ")
9-
op = raw_input("Operation (+, -, /, *): ")
10-
11-
if op not in '+-/*':
12-
print "Invalid operator"
13-
else:
14-
if op == '+':
15-
res = num1 + num2
16-
elif op == '-':
17-
res = num1 - num2
18-
elif op == '/':
19-
res = num1 / num2
20-
elif op == '*':
21-
res = num1 * num2
22-
print "%d %s %d = %d" % (num1, op, num2, res)
1+
"""
2+
Calculator - A simple calculator to do basic operators.
3+
"""
4+
5+
if __name__ == '__main__':
6+
try:
7+
num1 = int(raw_input("Number 1: "))
8+
num2 = int(raw_input("Number 2: "))
9+
except:
10+
print 'Invalid input'
11+
else:
12+
op = raw_input("Operation (+, -, /, *): ")
13+
if op not in '+-/*':
14+
print "Invalid operator"
15+
else:
16+
if op == '+':
17+
res = num1 + num2
18+
elif op == '-':
19+
res = num1 - num2
20+
elif op == '/':
21+
res = num1 / num2
22+
elif op == '*':
23+
res = num1 * num2
24+
print "%d %s %d = %d" % (num1, op, num2, res)

0 commit comments

Comments
 (0)