以下是我收到的关于作业的说明:
4)将以下函数添加到Mylib中
scalc(p1)
p1 will be a string like this "N1, N2, operator"
examples
scalc("20,30,*")
the result will be 600
scalc("50,20,+")
the result will be 70
scalc("50,20,-")
the result will be 30
scalc("60,20,/")
the result will be 30
使用字符串函数从输入字符串中解析第一个数字,第二个数字和运算符。使用先前的功能(加,减,除和乘)进行计算。
而这是我的尝试无效。我有add()sub()mult()div()函数,这里只是不显示它们。
我知道这很简单,可能与调用函数scalc(p1)的位置有关。什么是正确的方法?
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[3] == "+":
add()
elif astring[3] == "-":
sub()
elif astring[3] == "*":
mult()
elif astring[3] == "/":
div()
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
这里是整个main()函数,可以提供更好的图像:
#Define the main program function
def main():
#Define input function
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
print("You must enter a number!")
else:
break
#Declare variables
rangeLower = float_input("Enter your Lower range: ")
rangeHigher = float_input("Enter your Higher range: ")
num1 = float_input("Enter your First number: ")
num2 = float_input("Enter your Second number: ")
#Define formula functions
def add():
sum = num1 + num2
print("The Result of",num1,"+",num2,"=", sum)
def sub():
diff = num1 - num2
print("The Result of",num1,"-",num2,"=", diff)
def mult():
product = num1 * num2
print("The Result of",num1,"*",num2,"=", product)
def div():
if num2 == 0:
print("The Result of",num1,"/",num2,"= You cannot divide by Zero")
else:
quotient = num1 / num2
print("The Result of",num1,"/",num2,"=", quotient)
#If-else
if num1 < rangeLower or num1 > rangeHigher or num2 < rangeLower or num2 > rangeHigher:
print("The input values are outside the input ranges.")
print("Please check the number and try again.")
print("Thanks for using our calculator")
else:
#Call functions
add()
sub()
mult()
div()
print("Thanks for using this calculator!")
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
value = num1+num2
elif astring[2] == "-":
value = num1-num2
elif astring[2] == "*":
value = num1*num2
elif astring[2] == "/":
value = num1/num2
return value
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
完成。有几个错误。首先,在Python中,您从0开始计数,因此您想使用astring[2]
而不是astring[3]
。另外,您需要返回一个值:
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
value = num1+num2
elif astring[2] == "-":
value = num1-num2
elif astring[2] == "*":
value = num1*num2
elif astring[2] == "/":
value = num1/num2
return value
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
示例:
input: "20,30,+"
Out[2]: 50.0