Skip to content

Commit 3f4bae1

Browse files
authored
add while loop
1 parent d8db743 commit 3f4bae1

File tree

1 file changed

+28
-16
lines changed

1 file changed

+28
-16
lines changed

calculator.py

+28-16
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
Written by: Shreyas Daniel - github.com/shreydan
3-
Description: Uses Pythons eval() function
3+
Description: Uses Pythons eval() function
44
as a way to implement calculator
55
66
Functions available:
@@ -22,41 +22,53 @@
2222

2323

2424
def main():
25-
25+
2626
def calc(k):
2727

28-
functions = ['sin', 'cos', 'tan', 'sqrt', 'pi']
29-
28+
functions = ['sin', 'cos', 'tan', 'sqrt', 'pi']
29+
3030
for i in functions:
3131
if i in k.lower():
3232
withmath = 'math.' + i
3333
k = k.replace(i, withmath)
34-
34+
3535
try:
3636
k = eval(k)
3737
except ZeroDivisionError:
38+
3839
print("Can't divide by 0")
3940
exit()
4041
except NameError:
4142
print('Invalid input')
4243
exit()
43-
44+
4445
return k
4546

46-
print("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)")
47+
def result(k):
48+
k = k.replace(' ', '')
49+
k = k.replace('^', '**')
50+
k = k.replace('=', '')
51+
k = k.replace('?', '')
52+
k = k.replace('%', '/100')
53+
54+
print("\n" + str(calc(k)))
55+
56+
print("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)\nEnter quit to exit")
4757

4858
if sys.version_info.major >= 3:
49-
k = input("\nWhat is ")
59+
while True:
60+
k = input("\nWhat is ")
61+
if k == 'quit':
62+
break
63+
result(k)
64+
5065
else:
51-
k = raw_input("\nWhat is ")
66+
while True:
67+
k = raw_input("\nWhat is ")
68+
if k == 'quit':
69+
break
70+
result(k)
5271

53-
k = k.replace(' ', '')
54-
k = k.replace('^', '**')
55-
k = k.replace('=', '')
56-
k = k.replace('?', '')
57-
k = k.replace('%', '/100')
5872

59-
print("\n" + str(calc(k)))
60-
6173
if __name__ == '__main__':
6274
main()

0 commit comments

Comments
 (0)