[英]simple calculator with class in python
I'm lagging in logic that the following basic script should not ask to enter the input of A and B even after giving the irrelevant numbers that's greater than 5. 我在逻辑上滞后,即使给出不相关的数字大于5,以下基本脚本也不应要求输入A和B的输入。
#!/usr/bin/python
try :
print "Enter 1 for Addition "
print "Enter 2 for Subtraction"
print "Enter 3 for Multiplication"
print "Enter 4 for Divition"
class calc :
def Add ( self, A, B ):
print A + B
def Sub (self, A, B ):
print A - B
def Mul (self, A, B ):
print A * B
def Div (self, A, B ):
print A / B
C = calc()
Input = int (raw_input ("Enter the choice:"))
A = int (raw_input ("Enter A:"))
B = int (raw_input ("Enter B:"))
if Input == 1:
C.Add (A,B)
elif Input == 2:
C.Sub (A,B)
elif Input == 3:
C.Mul (A,B)
elif Input == 4:
C.Div (A,B)
elif Input <= 5:
print "Its not avaliable try again"
exit ()
except ValueError:
"The value is wrong"
Your entire if ... elif
chain is better handled using a dict
structure like this: 整个
if ... elif
链最好使用这样的dict
结构来处理:
try:
{1: C.Add, 2: C.Sub, 3: C.Mul, 4: C.Div}.get(Input)(A,B)
except TypeError:
print "It's not available, try again"
exit()
You can move the condition which checks for wrong user input to the line next to the raw_input
invocation (and fix the issue in the statement itself - the wrong choices are choices which are bigger than 4 and less than 0): 您可以将检查用户输入错误的条件移至
raw_input
调用旁边的行(并在语句本身中解决问题-错误的选择是大于4且小于0的选择):
C = calc()
Input = int (raw_input ("Enter the choice:"))
if Input not in [1,2,3,4]:
print "Its not avaliable try again"
exit ()
BTW: it'll be better to wrap in try/except
block only the lines which can cause the exception, not the whole program: 顺便说一句:最好将
try/except
只包装可能导致异常的行,而不是整个程序:
C = calc()
try:
Input = int (raw_input ("Enter the choice:"))
except ValueError:
print "Wrong input"
exit()
if Input not in [1,2,3,4]:
print "Its not avaliable try again"
exit ()
Also, it'll be better to use naming conventions: names of variables should start with non-capitalized letter, eg input
, names of classes should start with capitalized letters - class Calc
. 另外,最好使用命名约定:变量名称应以非大写字母开头,例如
input
,类名称应以大写字母开头- class Calc
。
Instead of 代替
...
elif Input <= 5: # This doesn't make sense, this check will work just for negative numbers
print "Its not avaliable try again"
exit ()
use 采用
...
else:
print "Its not avaliable try again"
exit ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.