python3 魔术方法
We will build a calculator program in this article using python3. If you search for a python calculator program on the internet, you will definitely find many of them and most of the basic calculator programs, like one below:
我们将在本文中使用python3构建一个计算器程序 。 如果您在互联网上搜索python计算器程序 ,则肯定会找到其中的许多程序以及大多数基本的计算器程序 ,例如以下程序:
1)传统计算器程序 (1) Traditional Calculator Program)
# Program make a simple calculator that can
# add, subtract, multiply and divide using functions
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Output
输出量
Explanation:
说明:
This calculator program is made using simple if...else condition, we created 4 functions (addition, subtraction, multiplication, and division) for our 4 different operations. We had a print command for out basic outputs and operation variable stores the value of users choice which a number and perform an operation associated with that number and will produce the result.
这个计算器程序是使用if ... else的简单条件制作的 ,我们为4个不同的运算创建了4个函数(加,减,乘和除)。 我们有一个用于输出基本输出的打印命令,并且操作变量存储用户选择的值,该值是一个数字,并执行与该数字关联的操作,并将产生结果。
Pretty interesting??? BOOO!!!!! I know this calculator is capable of doing only 4 operations and only can do one operation in its life cycle. This is what you can find on the internet, here in next section we used a better approach to build a calculator program.
非常有趣??? OO !!!!! 我知道此计算器只能执行4次操作,并且在其生命周期内只能执行一次操作。 这是您可以在Internet上找到的内容,在下一节中,我们使用了一种更好的方法来构建计算器程序。
2)魔术计算器| 更好的方法 (2) Magic Calculator | A Better Approach)
The thing to remember: Before we start, just know we make use Regex (regular Expression) here, so if you are not familiar with it don’t worry we got you covered, we will get through this as required of the moment.
要记住的事情:在开始之前,只知道我们在这里使用Regex(正则表达式),所以如果您不熟悉Regex(正则表达式),请放心,我们会按要求立即解决此问题。
In the modern calculator, that you have probably seen in windows and Linux these won’t ask you for choosing an operation they perform tasks you type.
在现代计算器中,您可能已经在Windows和Linux中看到过这些,它们不会要求您选择它们执行键入的任务的操作。
Image courtesy: My windows inbuilt calculator
图片提供:我的Windows内置计算器
And on hitting enter key it will produce the result, and in this section, we shall make a calculator program.
并按Enter键将产生结果,在本节中,我们将创建一个计算器程序。
Program:
程序:
import re
print("Our Magical Calculator")
print("Type x to close")
previous = 0
run = True
def performMath():
global run
global previous
equation = ""
if previous == 0:
equation = input("Enter Equation: ")
else :
equation = input(str(previous))
if equation == 'x':
print("GoodBye!!!")
exit(0)
else:
equation = re.sub('[a-zA-Z,:()" "]',"",equation)
if previous == 0:
previous = eval(equation)
else:
previous = eval(str(previous) + equation)
while run:
performMath()
Output
输出量
Explanation:
说明:
Ok... I agree it’s a lot to grasp so we will understand the above program in steps.
好吧...我同意要掌握很多东西,因此我们将逐步了解上述程序。
First, we imported the Regex library, and some output for a user and define a variable like run = True and previous = 0. In while we called our performMath() function we created before. Since while is checking run so it’s an infinite loop.
首先,我们导入了Regex库 ,并为用户提供了一些输出,并定义了一个变量,例如run = True和previous = 0 。 在我们调用之前创建的performMath()函数的同时 。 由于while正在检查运行,因此这是一个无限循环。
Now, performMath() is our important component of the program as it the one performing all the operations.
现在, performMath()是程序的重要组成部分,因为它是执行所有操作的程序。
In the first two lines of performMath() we used global keywords so that the run and previous variable we will use in the function we referred as a global variable instead of function local variable.
在performMath()的前两行中,我们使用了全局关键字,因此我们将在称为全局变量而不是函数局部变量的函数中使用run和previous变量。
If previous will be zero that is we just started our program we so our calculator will ask for input otherwise it will append in previous equation itself.
如果previous为零,那就是我们刚刚启动程序,因此我们的计算器将要求输入,否则它将附加在先前的方程本身中。
In the second if...else case, it checks if the user pressed 'x' to quit if not then we called re.sub() that the regex function which takes 3 parameters 1.pattern 2.substitute 3.string. re.sub() is substitution which replaces ‘pattern’ with ‘substitute’ in the ‘string’.
在第二种if ... else情况下,它检查用户是否按了'x'退出,然后我们调用re.sub() ,该regex函数带有 3个参数1.pattern 2.substitute 3.string 。 re.sub()是替换,它将'string'中的'pattern'替换为'substitute' 。
Now we will look into some basic regex expression we used above, we used [] (square brackets) because it defines the set of characters that need to include in the pattern, and we can use hyphen (-) to set the characters to range in which case we choose between a to z and A to Z including other symbols and replaced them with blank spaces just to remove them from the equation string and stored it in equation itself.
现在,我们将研究上面使用的一些基本正则表达式,我们使用[] (方括号),因为它定义了需要包含在模式中的字符集,并且我们可以使用连字符( - )将字符设置为range在这种情况下,我们在a到z和A到Z之间进行选择(包括其他符号),并用空格替换它们,只是将其从等式字符串中删除并将其存储在等式本身中。
In the third if...else case, we checked if previous hold any prior calculation if not to evaluate the equation with eval() function otherwise evaluate it after appending previously calculated value with the current equation.
在第三个if ... else情况下,我们检查了是否先前保存了任何先前的计算,如果不使用eval()函数来评估方程,否则在将先前计算的值附加到当前方程之后评估它。
Note: eval() function is something we shouldn't be using (in general) in our python code, because it can evaluate anything that is passed as its parameter, meaning it can actually calculate all multiplication, division, addition and subtraction as well as exponential and the calculating remainder as well. But it has a dark side too that we need to avoid, that is eval() function can actually run any python command that passed as its parameter even if its as simple as print() it will execute the command so as the security point of view we shouldn't be using it so we used Regex here to eliminate all the letters and keep only numerical characters.
注意: eval()函数是我们一般不应该在python代码中使用的函数,因为它可以评估作为参数传递的任何内容,这意味着它实际上还可以计算所有的乘法,除法,加法和减法作为指数和计算余数。 但是它也有一个黑暗的方面,我们需要避免,那就是eval()函数实际上可以运行作为参数传递的任何python命令,即使它与print()一样简单,它将执行该命令,以确保安全性。鉴于我们不应该使用它,因此我们在这里使用了Regex来消除所有字母并仅保留数字字符。
If you are curious about Regex you can read here: Google python Regex
如果您对Regex感到好奇,可以在这里阅读: Google python Regex
翻译自: https://www.includehelp.com/python/design-traditional-and-magic-calculator-in-python3.aspx
python3 魔术方法