請不要太意味着我只開始使用Python,並且想要嘗試並完成一個可以使用括號和BIDMAS的計算器。我目前正處於開始部分括號的階段,但是當我運行我的程序時,它不會正確運行我的def函數。def函數沒有正確運行
import time
import os
import random
import sys
print("=======================")
print("Use^for the power of")
print("Use + for adding")
print("Use - for subtracting")
print("Use * for multiplying")
print("Use/for dividing")
print("Use % for a percentage")
print("DON'T USE SPACES!")
print("=======================\n\n")
uilist = ""
uilength = ""
user_input = ""
def to_the_power_of(a):
postion_n1 = a.index("^")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1**n2
sign = "^"
def subtracting(a):
postion_n1 = a.index("-")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1-n2
sign = "-"
def adding(a):
postion_n1 = a.index("+")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1+n2
sign = "+"
def multiplying(a):
postion_n1 = a.index("*")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1*n2
sign = "x"
def dividing(a):
postion_n1 = a.index("/")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = n1/n2
sign = "/"
def percentage(a):
postion_n1 = a.index("%")
postion_n2 = postion_n1 + 1
n1 = int(a[:postion_n1])
n2 = int(a[postion_n2:])
total = (n1*n2)/100
sign = "%"
def calculate(ab):
uilength = len(ab)
uilist = list(ab)
if "^" in uilist:
to_the_power_of(answer_1)
elif "+" in uilist:
adding(answer_1)
elif "-" in uilist:
subtracting(answer_1)
elif "*" in uilist:
multiplying(answer_1)
elif "/" in uilist:
dividing(answer_1)
elif "%" in uilist:
percentage(answer_1)
else:
print("Please eneter a valid calculation!")
while True:
user_input = input("Write your calculation: ")
answer_1 = user_input
calculate(user_input)
print(user_input,"=",total)
exit_cal = input("Would you like to exit or make a now calculation?").lower()
exit_list = ["exit","quit","leave","404"]
if exit_cal in exit_list:
sys.exit()
這是錯誤我得到
=======================
Use^for the power of
Use + for adding
Use - for subtracting
Use * for multiplying
Use/for dividing
Use % for a percentage
DON'T USE SPACES!
=======================
Write your calculation: 12*4
Traceback (most recent call last):
File "C:\Users\Max\Desktop\Python Scripts\Calculator.py", line 99, in <module>
print(user_input,"=",total)
NameError: name 'total' is not defined
任何幫助將不勝感激!
您的代碼段過於寬泛,包含了很多你的問題不相關的代碼。爲了提高您獲得答案的機會,您可能希望限制您的示例代碼,使其對被問到的問題至少是不可或缺的。爲了幫助你,你可能想要熟悉[我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask)和[如何創建一個最小,完整,和可驗證示例](http://stackoverflow.com/help/mcve)。 –
你是不是指'total = calculate(user_input)'? –
你沒有定義總的def函數工作得很好 –