[环境]:Python3.5 + Win8.1
在开始编写一个程序之前,一定要先想好想要的功能,这个项目的描述大概是这样的:
当用户输入一个含有数字和加、减、乘、除、乘方和括号的算式时,输出他的结果。
如:用户输入2*(5+8**(5-3))/2时,返回69。
>>>3+6+8
17
>>>3*5-2
13
>>>
Python本身可以作为计算器
>>>eval("3+6+8")
17
>>>eval("3*5-2")
13
>>>
用eval来运行一段Python代码
# -*- coding: UTF-8 -*-
while True:
Equation = input('>')
print(eval(Equation))
至少可以用了:
>2*(5+8**(5-3))/2
69.0
>2*5
10
>66-9
57
>I'm a Error!
Traceback (most recent call last):
File "E:\python_work\calc.py", line 4, in
print(eval(Equation))
File "", line 1
I'm a Error!
^
SyntaxError: EOL while scanning string literal
这是一个不友好的消息。
# -*- coding: UTF-8 -*-
while True:
Equation = input('>')
try:
print(eval(Equation))
except:
print("Unknow equation %s" % Equation)
再试一下:
>2*(5+8**(5-3))/2
69.0
>2*5
10
>66-9
57
>I'm a Error!
Unknow equation I'm a Error!
>__import__('os').system("shutdown -s -t 120")
0
>
不会报错了,但是用户还可以干一些别的事,比如关机。
# -*- coding: UTF-8 -*-
symbol = ('+', '-', '*', '/', '(', ')', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0')
calc = True
while True:
Equation = input('>')
tester = list(Equation)
for i in tester:
if i not in symbol:
print("Unknow symbol %s" % i)
calc = False
if calc:
try:
print(eval(Equation))
except:
print("Unknow equation %s" % Equation)
终于可以用了:
>2*(5+8**(5-3))/2
69.0
>2*5
10
>66-9
57
>I'm a Error!
Unknow symbol I
Unknow symbol '
Unknow symbol m
Unknow symbol
Unknow symbol a
Unknow symbol
Unknow symbol E
Unknow symbol r
Unknow symbol r
Unknow symbol o
Unknow symbol r
Unknow symbol !
>__import__('os').system("shutdown -s -t 120"
Unknow symbol _
Unknow symbol _
Unknow symbol i
Unknow symbol m
Unknow symbol p
Unknow symbol o
Unknow symbol r
Unknow symbol t
Unknow symbol _
Unknow symbol _
Unknow symbol '
Unknow symbol o
Unknow symbol s
Unknow symbol '
Unknow symbol .
Unknow symbol s
Unknow symbol y
Unknow symbol s
Unknow symbol t
Unknow symbol e
Unknow symbol m
Unknow symbol "
Unknow symbol s
Unknow symbol h
Unknow symbol u
Unknow symbol t
Unknow symbol d
Unknow symbol o
Unknow symbol w
Unknow symbol n
Unknow symbol
Unknow symbol s
Unknow symbol
Unknow symbol t
Unknow symbol
Unknow symbol "
>
只要报一个错就够了
# -*- coding: UTF-8 -*-
symbol = ('+', '-', '*', '/', '(', ')', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0')
calc = True
while True:
Equation = input('>')
tester = list(Equation)
for i in tester:
if i not in symbol and calc:
print("Unknow symbol %s" % i)
calc = False
if calc:
try:
print(eval(Equation))
except:
print("Unknow equation %s" % Equation)