-
2021-01-13 15:35:07
【摘要】python的实用性不用多说了,现在已经有很多人使用python完成很多事情,那么python计算器功能如何实现?这篇文章给你最实用的代码,计算器功能的实现是python的基础,所以掌握python计算器功能如何实现很重要,这篇文章给你最实用的代码。
这篇文章主要介绍了python如何通过闭包实现计算器的功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
python计算器功能如何实现?满足闭包的条件:
1、函数中嵌套一个函数
2、外层函数的返回值是内层函数的函数名
3、内层嵌套函数对外部作用域有一个非全局变量的引用
python计算器功能如何实现?闭包的作用:
实现数据锁定
装饰器的作用:
就是为已经存在的对象添加额外的功能。
常用场景:
插入日志、性能测试、事务处理、缓存、权限校验等
代码示例:
def scope(func):
def calc(a, b):
try:
_a = float(a) _b = float(b) except:
_a = 0 _b = 0 return func(_a, _b) return calc @scope def add(a, b):
return a + b @scope def sub(a, b):
return a - b @scope def mul(a, b):
return a * b @scope def div(a, b):
try: return a / b except ZeroDivisionError as error:
print(error) return 0 # 调用闭包函数 res = scope(add)("1", 3) print(res) res = add("1", "2") print(res) res = sub("1", "2") print(res) res = mul("1", "2") print(res) res = div("1", "2") print(res)
通过这篇文章,大家应该已经学会了python计算器功能如何实现?这篇文章给你最实用的代码,当然,如果你想真正的实现python的功能,环球网校的小编希望你可以亲自实践一下python的代码编写工作,如果你想了解更多的pythonh知识,可以点击下方资料下载链接。
更多相关内容 -
python计算器
2019-01-14 16:18:38python计算器课程作业,可实现键盘响应。完美的计算器作业,python小程序 -
calculator.rar_python 计算器_python计算器_计算器 python
2022-07-14 04:09:38用python实现简易计算器,包括+,-,*,/及一些扩展运算,是联系python的GUI编程的很好的练手题目。 -
Python计算器
2021-02-13 15:17:06Python计算器 这是带有登录页面的计算器。 用户名是:admin密码是:admin我们已经使用了flask和python。 当我们运行程序时,我们将获得一个http链接。 当我们单击它时,我们将在成功登录后显示登录页面,并显示... -
python计算器源码
2017-08-01 09:28:19python开发的简易计算器,主要是学习tkinter -
python计算器源代码
2018-10-08 19:05:46用户输入一个类似这样 3*( 4+ 50 )-(( 100 + 40 )*5/2- 3*2* 2/4+9)*((( 3 + 4)-4)-4) 这样的表达式,假设表达式里面除了包含空格、'+'、'-'、'*'、'/'和括号再无其他特殊符号,然后自己动手写代码解析其中的表达式... -
python计算器(tinker模块)源代码
2020-06-03 22:43:51非原创,一个运用tinker模块编写的计算器,很好的实例,对于tinker模块的初学者可能会有些帮助。 -
python 计算器功能实现
2021-12-08 18:26:45python 计算器功能实现今天学习到python中界面设计部分,常用的几种图形化界面库有:Jython、wxPython和tkinter。
主要介绍tkinter模块,tkinter模块(tk接口)是Python的标准tk GUI工具包的接口。tk和tkinter可以在大多数的UNIX平台下使用,同样可以应用在Windows和Macintosh系统里。Tk8.0的后续版本可以实现本地窗口风格,并良好地运行在绝大多数平台中。
下面使用tkinter设计完成计算器功能。
(1)首先呈现一下计算器初始界面:
(2)简单说明:已经实现计算器的基本功能
(3)主要代码说明:
①导入包
import tkinter from tkinter import * import re import tkinter.messagebox
②界面布局设置
# 创建主窗口 root = Tk() # 设置窗口大小和位置 root.title("---计算器---") root.geometry("320x210+500+200") # 自动刷新字符串变量,可用 set 和 get 方法进行传值和取值 contentVar = tkinter.StringVar(root,'') # 创建单行文本框 contentEntry = tkinter.Entry(root, textvariable=contentVar) # 设置文本框坐标及宽高 contentEntry.place(x=20, y=10, width=260, height=30) # 按钮显示内容 bvalue = ['CLC', '+', '-', '//', '0', '1', '2', '√', '3', '4', '5', '*', '6', '7', '8', '.', '9', '/', '**', '='] index = 0 # 将按钮进行 5x4 放置 for row in range(5): for col in range(4): d = bvalue[index] index += 1 btnDigit = tkinter.Button(root, text=d, command=lambda x=d:onclick(x)) btnDigit.place(x=20 + col * 70, y=50 + row * 30, width=50, height=20) root.mainloop()
③按钮事件的响应函数(可在评论区进行交流)
# 点击事件 def onclick(btn): # 运算符 operation = ('+', '-', '*', '/', '**', '//') # 获取文本框中的内容 content = contentVar.get() # 如果已有内容是以小数点开头的,在前面加 0 if content.startswith('.'): content = '0' + content # 字符串可以直接用+来增加字符 # 根据不同的按钮作出不同的反应 if btn in '0123456789': # 按下 0-9 在 content 中追加 content += btn elif btn == '.': # 将 content 从 +-*/ 这些字符的地方分割开来 lastPart = re.split(r'\+|-|\*|/', content)[-1] if '.' in lastPart: # 信息提示对话框 tkinter.messagebox.showerror('错误', '重复出现的小数点') return else: content += btn elif btn == 'CLC': # 清除文本框 content = '' elif btn == '=': try: # 对输入的表达式求值 content = str(eval(content)) except: tkinter.messagebox.showerror('错误', '表达式有误') return elif btn in operation: if content.endswith(operation): tkinter.messagebox.showerror('错误', '不允许存在连续运算符') return content += btn elif btn == '√': # 从 . 处分割存入 n,n 是一个列表 n = content.split('.') # 如果列表中所有的都是数字,就是为了检查表达式是不是正确的 if all(map(lambda x: x.isdigit(), n)): content = eval(content) ** 0.5 else: tkinter.messagebox.showerror('错误', '表达式错误') return
以上就是本文的全部内容,希望对大家的学习有所帮助。
-
python计算器.py
2020-12-10 01:11:44我是程序员幼儿阶段,第一次做这个,有不好的地方我会慢慢改进,也希望大家督促我,我会努力进步的。这是我做的简易python计算器可以实现简单的加减乘除,GUI界面可视化,用到了第三方插件。 -
Python简易计算器制作方法代码详解
2021-01-02 20:31:29主要用到的工具是Python中的Tkinter库 比较简单 直接上图形界面和代码 引用Tkinter库 from tkinter import * 建立主窗口对象 window=Tk() #设置窗口对象 window.title('counting machine') window.geometry(350x... -
Python计算器简单程序
2020-07-13 02:54:52Python计算器 (Python Calculator) In this quick post, we will see how we can create a very simple python calculator program. We will take input from the user about the operation he wants to perform and...Python计算器 (Python Calculator)
In this quick post, we will see how we can create a very simple python calculator program. We will take input from the user about the operation he wants to perform and show the result on its basis. Let’s get started with our python calculator code right away.
在这篇快速文章中,我们将看到如何创建一个非常简单的python计算器程序。 我们将从用户输入有关他要执行的操作的信息,并根据其显示结果。 让我们立即开始使用我们的python计算器代码。
模块化代码 (Modular Code)
To keep things modular, we will define functions to perform various operations. Here are the operations our calculator will support for numbers:
为了使事物保持模块化,我们将定义函数来执行各种操作。 这是我们的计算器支持的数字运算 :
- Addition 加成
- Subtraction 减法
- Multiplication 乘法
- Division 师
- Raising a power to number 提高数字能力
加成 (Addition)
Let’s do our first operation of Addition here:
让我们在这里进行加法的第一个操作:
def addition(x, y): return x + y;
We used a simple function so that our code remains modular.
我们使用了一个简单的函数,以便我们的代码保持模块化。
减法 (Subtraction)
Second operation involves subtracting two numbers:
第二个操作涉及两个数字相减:
def subtraction(x, y): return x - y;
乘法 (Multiplication)
Third operation involves multiplying two numbers:
第三个运算涉及两个数字相乘:
def multiplication(x, y): return x * y;
师 (Division)
Fourth operation involves dividing two numbers:
第四个运算涉及两个数的除法:
def division(x, y): return x / y;
提高数字能力 (Raising a power to number)
Our final operation involves raising a number by a power. Note that to do this, we can use mathematical operator
**
:我们的最终操作涉及通过幂提高数字。 注意,要做到这一点,我们可以使用数学运算符
**
:def raisePower(x, y): return x ** y;
接受用户输入 (Taking user input)
Time to present the user with available choices and taking an input from him:
是时候向用户展示可用的选项并从他那里获取输入了:
print("Operation to perform:"); print("1. Addition"); print("2. Subtraction"); print("3. Multiplication"); print("4. Division"); print("5. Raising a power to number"); choice = input("Enter choice: "); num1 = int(input("Enter first number: ")); num2 = int(input("Enter second number: "));
决定经营 (Deciding operation)
Finally, we can decide which function to call when user has provided an input:
最后,我们可以决定在用户提供输入后要调用哪个函数:
if choice == '1': print(num1, "+" ,num2, "=", addition(num1, num2)); elif choice == '2': print(num1, "-", num2, "=", subtraction(num1, num2)); elif choice == '3': print(num1, "*", num2, "=", multiplication(num1, num2)); elif choice == '4': print(num1, "/", num2, "=", division(num1, num2)); elif choice == '5': print(num1, "**", num2, "=", raisePower(num1, num2)); else: print("Please select a valid input.");
When we run this program, we will be able to perform mathematical operations:
运行此程序时,我们将能够执行数学运算:
结论 (Conclusion)
In this quick post, we defined a very simple Python calculator and kept the code modular as well so that we can reuse the functions accordingly.
在这篇快速文章中,我们定义了一个非常简单的Python计算器,并保持了代码模块化,以便我们可以相应地重用这些函数。
翻译自: https://www.journaldev.com/18798/python-calculator-simple-program
-
Python计算器菜鸟入门
2021-12-02 17:44:59Python计算器,适合初学者学习代码,了解编程格式和使用方式 -
python 简易计算器程序,代码就几行
2020-12-25 08:15:04代码: 复制代码 代码如下: import os while True: dynamic = input(‘输入计算表达式:’) if dynamic !... 您可能感兴趣的文章:Python使用wxPython实现计算器基于wxpython开发的简单gui计算器实例Python实现简单的四 -
calculator:简单的python计算器
2021-03-12 19:50:11calculator:简单的python计算器 -
Python 计算器界面设计
2020-12-02 22:57:26# coding=utf-8"""计算器软件界面设计"""from tkinter import *from tkinter import messageboxclass Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack...# coding=utf-8
"""计算器软件界面设计"""
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.creatWidget()
def creatWidget(self):
"""实现计算器"""
btnText =(("mc","m+","m-","mr"),
("c","±","÷","*"),
(7,8,9,"-"),
(4,5,6,"+"),
(1,2,3,"="),
(0,".")
)
Entry(self).grid(row=0,column=0,columnspan=4,pady=10)
for rindex,r in enumerate(btnText):
for cindex,c in enumerate(r):
if c=="=":
# rowspan 跨行
# columnspan 跨列
Button(self,text=c,width=2).\
grid(row=rindex+1,column=cindex,rowspan=2,sticky=NSEW)
elif c==0:
Button(self, text=c, width=2). \
grid(row=rindex + 1, column=cindex, columnspan=2, sticky=NSEW)
elif c==".":
Button(self, text=c, width=2). \
grid(row=rindex + 1, column=cindex+1,sticky=NSEW)
else:
Button(self,text=c,width=2).\
grid(row=rindex+1,column=cindex,sticky=EW)
if __name__=="__main__":
root = Tk()
root.geometry("160x240+100+200")
app = Application(master=root)
root.mainloop()
# 学习grid布局 做了个小的计算器界面
# 体会 grid布局主要是根据坐标的位置来确定具体在哪里填充控件
# 尤其是对于cowspan 和 columnspan的操作使用
# 初学Python 如有不足 请多多指教
原文:https://www.cnblogs.com/walxt/p/11522755.html
-
python简易计算器
2018-06-13 19:59:43一个已经打包成exe可执行文件的简易的python计算器,内附源码 -
python实现计算器
2018-06-09 19:28:18python实现界面设计,实现两个整数的加减乘数 简易的计算器,适合初学者 -
calculator_python计算器_eyecxc_计算器_
2021-10-04 09:23:02本代码使用python语言实现了简单的计算器 -
python计算器的实现
2022-01-10 19:09:59python计算器的实现 -
python界面计算器
2018-05-17 15:51:55用Python tkinter实现的初级计算器,功能基本完备。代码很精简 -
Python开发的实用计算器完整实例
2020-12-23 13:42:18本文实例讲述了Python开发的实用计算器。分享给大家供大家参考,具体如下: 实现功能:图形界面PyQt,输入框,+,—,*,/ ;乘方 ,开方 ,取余,清零。 1. Python代码: #!/usr/bin/env python # -*- coding: utf... -
python实现计算器功能
2020-09-18 12:51:47主要为大家详细介绍了python实现计算器功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下