python簡易計算器程序(Python 計算器)

本文目錄一覽:

如何使用python編程寫一個加法計算器

1、打開idle。點擊file,然後點擊new file.這是創建一個新的文件。

新建一個文件之後,我們輸入第一行代碼,使用print函數,在屏幕上列印一句話,其中字元串要使用雙引號,輸入法要使用英文輸入法,如果符號使用中文輸入法輸入,就會出現錯誤。print(“我們做一個兩個整數相加的計算題!”)

同理,在屏幕上列印第二句話,與用戶交互,提醒用戶輸入第一個數。

第三行調用input函數,將用戶輸入的內容賦值給a,這時候a收到的是字元串信息,所以需要下一步把字元串轉換為整型。這輸入計算機處理數據指令。

然後依照以上的步驟寫第二個加數,和最後輸出的和,注意最後一句列印結果時,引號內部是字元串形式,x+y是數值形式,所以需要在中間加上一個逗號。如果不加逗號就會提示錯誤信息,以上就是所有的程序編寫完成,下一步就開始保存,命名,運行。如圖所示

運行結果如下:

更多Python相關技術文章,請訪問Python教程欄目進行學習!以上就是小編分享的關於如何使用python編程寫一個加法計算器的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!

用PYTHON2做個計算器,只要加減乘除

”’

命令行簡易計算器

”’

import sys

class culate():

#加法

def add(self,a,b):

return a+b

#減法

def mut(self,a,b):

return a-b

#乘法

def sub(self,a,b):

return a*b

#除法

def mod(self,a,b):

return a/b

c=culate()

while True:

n=input(“請選擇你的操作:\n1.加法\n2.減法\n3.乘法\n4.除法\n0.退出\n”)

if n==”0″:

break

elif n==”1″:

a=input(“請輸入第一個數:”)

b=input(“請輸入第二個數:”)

print(c.add(int(a),int(b)))

continue

elif n==”2″:

a=input(“請輸入第一個數:”)

b=input(“請輸入第二個數:”)

print(c.mut(int(a),int(b)))

continue

elif n==”3″:

a=input(“請輸入第一個數:”)

b=input(“請輸入第二個數:”)

print(c.sub(int(a),int(b)))

continue

elif n==”4″:

a=input(“請輸入第一個數:”)

b=input(“請輸入第二個數:”)

print(c.mod(int(a),int(b)))

continue

”’

結果:

請選擇你的操作:

1.加法

2.減法

3.乘法

4.除法

0.退出

3

請輸入第一個數:9

請輸入第二個數:3

27

請選擇你的操作:

1.加法

2.減法

3.乘法

4.除法

0.退出

4

請輸入第一個數:9

請輸入第二個數:3

3.0

請選擇你的操作:

1.加法

2.減法

3.乘法

4.除法

0.退出

”’

用python操作Windows的計算器。

安裝pywin32模塊。

注意:乘法的優先順序高,在計算器輸入時要加括弧!

代碼:

import win32api,win32gui, win32con

import win32com.client

shell = win32com.client.Dispatch(“WScript.Shell”)

shell.Run(“calc”)

win32api.Sleep(1000)

shell.SendKeys(“200{+}”)

win32api.Sleep(1000)

shell.SendKeys(“{(}100\x2a2{)}”)

win32api.Sleep(1000)

shell.SendKeys(“-22”)

win32api.Sleep(1000)

shell.SendKeys(“=”)

h = win32gui.FindWindow(“SciCalc”, None)

edit = win32gui.FindWindowEx(h, None, ‘Edit’, None)

bufLen = 1024

buf = win32gui.PyMakeBuffer(bufLen)

n = win32gui.SendMessage(edit, win32con.WM_GETTEXT, bufLen, buf)

print buf[0:n]

win32api.Sleep(1000)

win32gui.SendMessage(h, win32con.WM_SYSCOMMAND, win32con.SC_CLOSE, 0);

運行結果:

378.

如何用 Python 寫一個帶 GUI 的科學計算程序

使用Tkinter圖形庫,如果你是用的linux系統 記得將第一行改為from tkinter import *

這個代碼實現的挺簡單,並不是很複雜的科學計算器界面,你可以以此為基礎,添加自己想要的東西:給你個截圖:

代碼是如下, 我就不給你添注釋了啊:

#!/usr/bin/env python3.4

from Tkinter import *

import parser

root = Tk()

root.title(‘Calculator’)

i = 0

def factorial():

“””Calculates the factorial of the number entered.”””

whole_string = display.get()

number = int(whole_string)

fact = 1

counter = number

try:

while counter 0:

fact = fact*counter

counter -= 1

clear_all()

display.insert(0, fact)

except Exception:

clear_all()

display.insert(0, “Error”)

def clear_all():

“””clears all the content in the Entry widget”””

display.delete(0, END)

def get_variables(num):

“””Gets the user input for operands and puts it inside the entry widget”””

global i

display.insert(i, num)

i += 1

def get_operation(operator):

“””Gets the operand the user wants to apply on the functions”””

global i

length = len(operator)

display.insert(i, operator)

i += length

def undo():

“””removes the last entered operator/variable from entry widget”””

whole_string = display.get()

if len(whole_string): ## repeats until

## now just decrement the string by one index

new_string = whole_string[:-1]

print(new_string)

clear_all()

display.insert(0, new_string)

else:

clear_all()

display.insert(0, “Error, press AC”)

def calculate():

“””

Evaluates the expression

ref :

“””

whole_string = display.get()

try:

formulae = parser.expr(whole_string).compile()

result = eval(formulae)

clear_all()

display.insert(0, result)

except Exception:

clear_all()

display.insert(0, “Error!”)

root.columnconfigure(0,pad=3)

root.columnconfigure(1,pad=3)

root.columnconfigure(2,pad=3)

root.columnconfigure(3,pad=3)

root.columnconfigure(4,pad=3)

root.rowconfigure(0,pad=3)

root.rowconfigure(1,pad=3)

root.rowconfigure(2,pad=3)

root.rowconfigure(3,pad=3)

display = Entry(root, font = (“Calibri”, 13))

display.grid(row = 1, columnspan = 6 , sticky = W+E)

one = Button(root, text = “1”, command = lambda : get_variables(1), font=(“Calibri”, 12))

one.grid(row = 2, column = 0)

two = Button(root, text = “2”, command = lambda : get_variables(2), font=(“Calibri”, 12))

two.grid(row = 2, column = 1)

three = Button(root, text = “3”, command = lambda : get_variables(3), font=(“Calibri”, 12))

three.grid(row = 2, column = 2)

four = Button(root, text = “4”, command = lambda : get_variables(4), font=(“Calibri”, 12))

four.grid(row = 3 , column = 0)

five = Button(root, text = “5”, command = lambda : get_variables(5), font=(“Calibri”, 12))

five.grid(row = 3, column = 1)

six = Button(root, text = “6”, command = lambda : get_variables(6), font=(“Calibri”, 12))

six.grid(row = 3, column = 2)

seven = Button(root, text = “7”, command = lambda : get_variables(7), font=(“Calibri”, 12))

seven.grid(row = 4, column = 0)

eight = Button(root, text = “8”, command = lambda : get_variables(8), font=(“Calibri”, 12))

eight.grid(row = 4, column = 1)

nine = Button(root , text = “9”, command = lambda : get_variables(9), font=(“Calibri”, 12))

nine.grid(row = 4, column = 2)

cls = Button(root, text = “AC”, command = clear_all, font=(“Calibri”, 12), foreground = “red”)

cls.grid(row = 5, column = 0)

zero = Button(root, text = “0”, command = lambda : get_variables(0), font=(“Calibri”, 12))

zero.grid(row = 5, column = 1)

result = Button(root, text = “=”, command = calculate, font=(“Calibri”, 12), foreground = “red”)

result.grid(row = 5, column = 2)

plus = Button(root, text = “+”, command = lambda : get_operation(“+”), font=(“Calibri”, 12))

plus.grid(row = 2, column = 3)

minus = Button(root, text = “-“, command = lambda : get_operation(“-“), font=(“Calibri”, 12))

minus.grid(row = 3, column = 3)

multiply = Button(root,text = “*”, command = lambda : get_operation(“*”), font=(“Calibri”, 12))

multiply.grid(row = 4, column = 3)

divide = Button(root, text = “/”, command = lambda : get_operation(“/”), font=(“Calibri”, 12))

divide.grid(row = 5, column = 3)

# adding new operations

pi = Button(root, text = “pi”, command = lambda: get_operation(“*3.14”), font =(“Calibri”, 12))

pi.grid(row = 2, column = 4)

modulo = Button(root, text = “%”, command = lambda : get_operation(“%”), font=(“Calibri”, 12))

modulo.grid(row = 3, column = 4)

left_bracket = Button(root, text = “(“, command = lambda: get_operation(“(“), font =(“Calibri”, 12))

left_bracket.grid(row = 4, column = 4)

exp = Button(root, text = “exp”, command = lambda: get_operation(“**”), font = (“Calibri”, 10))

exp.grid(row = 5, column = 4)

## To be added :

# sin, cos, log, ln

undo_button = Button(root, text = “-“, command = undo, font =(“Calibri”, 12), foreground = “red”)

undo_button.grid(row = 2, column = 5)

fact = Button(root, text = “x!”, command = factorial, font=(“Calibri”, 12))

fact.grid(row = 3, column = 5)

right_bracket = Button(root, text = “)”, command = lambda: get_operation(“)”), font =(“Calibri”, 12))

right_bracket.grid(row = 4, column = 5)

square = Button(root, text = “^2”, command = lambda: get_operation(“**2”), font = (“Calibri”, 10))

square.grid(row = 5, column = 5)

root.mainloop()

如何運用Python編寫簡易計算器

import time

print(“計算器”)

print(“+等於加法模式 -等於減法模式 *等於乘法模式 /等於除法模式”)

while 2 1:

try:

print(“請輸入+,-,*或/”)

a = input()

if a == “+”:

print(“請輸入第1個加數”)

b = input()

print(“請輸入第2個加數”)

c = input()

print(“計算中”)

time.sleep(0.3)

j = float(b) + float(c)

print(“等於”+str(j))

elif a == “-“:

print(“請輸入被減數”)

b = input()

print(“請輸入減數”)

c = input()

print(“計算中”)

time.sleep(0.3)

j = float(b) – float(c)

print(“等於”+str(j))

elif a == “*”:

print(“請輸入第1個因數”)

b = input()

print(“請輸入第2個因數”)

c = input()

print(“計算中”)

time.sleep(0.3)

j = float(b) * float(c)

print(“等於”+str(j))

elif a == “/”:

print(“……等於餘數模式 .等於小數模式”)

print(“請輸入……或.”)

a = input()

if a == “.”:

print(“請輸入被除數”)

b = input()

print(“請輸入除數”)

c = input()

print(“計算中”)

time.sleep(0.3)

j = float(b) / float(c)

print(“等於”+str(j))

if c == “0”:

print(“除數不能為0!”)

elif a == “……”:

print(“請輸入被除數”)

b = input()

print(“請輸入除數”)

c = input()

j = float(b) // float(c)

e = float(b) % float(c)

print(“等於”+str(j)+”……”+str(e))

if c == “0”:

print(“除數不能為0!”)

except Exception as e:

print(“您輸入的內容有錯誤”)

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/204546.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-07 12:17
下一篇 2024-12-07 12:18

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論