本文目錄一覽:
用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 當做計算器使用方法?
我們來嘗試一些簡單的 Python 命令。啟動解釋器然後等待主提示符 出現(不需要很久)。
3.1.1. 數字
解釋器表現得就像一個簡單的計算器:可以向其錄入一些表達式,它會給出返回值。表達式語法很直白:運算符 +,-,* 和 / 與其它語言一樣(例如:Pascal 或 C);括號 (()) 用於分組。
整數(例如,2, 4, 20 )的類型是 int,帶有小數部分的數字(例如,5.0, 1.6)的類型是 float。在本教程的後面我們會看到更多關於數字類型的內容。
除法(/)永遠返回一個浮點數。如要使用 floor 除法 並且得到整數結果(丟掉任何小數部分),你可以使用 // 運算符;要計算餘數你可以使用 %
此變量對於用戶是只讀的。不要嘗試給它賦值 —— 你只會創建一個獨立的同名局部變量,它屏蔽了系統內置變量的魔術效果。
除了 int 和 float,Python 還支持其它數字類型,例如 Decimal 和 Fraction。Python 還內建支持 複數 ,使用後綴 j 或 J 表示虛數部分
如何運用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-hant/n/282930.html