如何用python编写计算器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用python编写计算器相关的知识,希望对你有一定的参考价值。

我想你的需求应该是一个图形界面的程序,而不是简单的在命令行上输入。
那么,要做的第一件事就是选择一个图形界面套件。可以使用原生的TK,也可以用跨平台性能很好的wxPython,或者是整体结构很像MFC的PyWin32。至于pyGTK,pyQT,都是可选的,但是相对来说文档比较少,学习不便。
选定图形库之后,就可以看文档范例了。计算器总体是比较简单的。我记得WxPython的demo里直接就有一个简单计算器,您可以直接取来用。
参考技术A # true needed a captial T
while True:

# Brackets were mismatched
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))

if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
# Calling a function shouldn't have trailing :
add(c)

elif CHOICE == "2":
print 'SUBTRACTING TWO NUMBERS'
# Calling a function shouldn't have trailing :
sub(c)

elif CHOICE == "3":
print 'MULTIPLYING TWO NUMBERS'
# Calling a function shouldn't have trailing :
Mul(c)

elif CHOICE == "4":
print "DIVIDEING TWO NUMBERS"
# Calling a function shouldn't have trailing :
Div(c)

elif CHOICE == "0":
# can only return from a function use exit here instead
exit()

# else needs a trailing :
else:
# No capital P for print
print "The value Enter value from 1-4"

The code now has no syntax errors but still has many problems.
You pass c to your function, c is never initialized, what is c?
Your function doesn't take arguments def add(): (even though pass the mysterious cvalue).
Your function doesn't print or return the result it just computes.
You store CHOICE as an int are do comparisons with strings so the else case is always executed and there is no way to exit the loop (infinite looping).
Fixed code:
#!/usr/bin/python

def add():
print "Enter the two numbers to Add"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A + B

def sub():
print "Enter the two numbers to Subtract"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A - B

def mul():
print "Enter the two numbers to Multiply"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A * B

def div():
print "Enter the two number to Divide"
A=float(raw_input("Enter A: "))
B=float(raw_input("Enter B: "))
return A / B

print "1: ADDITION"
print "2: SUBTRACTION"
print "3: MULTIPLICATION"
print "4: DIVITION"
print "0: QUIT"

while True:

CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION "))

if CHOICE == 1:
print 'ADDING TWO NUMBERS:'
print add()

elif CHOICE == 2:
print 'SUBTRACTING TWO NUMBERS'
print sub()

elif CHOICE == 3:
print 'MULTIPLYING TWO NUMBERS'
print mul()

elif CHOICE == 4:
print "DIVIDEING TWO NUMBERS"
print div()

elif CHOICE == 0:
exit()
else:
print "The value Enter value from 1-4"
参考技术B

代码

print('计算器')

problem = input('输入1个算式,按q退出')

while (problem != 'q'):

       print('答案是',eval(problem))

       problem = input('输入1个算式,按q退出')


注释      eval(   ) 用于将括号里的算式返回到答案

以上是关于如何用python编写计算器的主要内容,如果未能解决你的问题,请参考以下文章

如何用python编写一个求分段函数的值的程序

如何用Python编写代码在Word中实现带公式计算过程的计算书?

用JavaScript编写计算日期

如何用JAVA编写计算器?

如何用Python生成计算题?

如何用 Python 计算 CRC32 以匹配在线结果?