我是python的新手,正在通过我大学的计算课程学习它。我们的作业是创建这个计算器算法,其算法只接受数字1到99,只接受运算符+, - ,*,/,//,%,**。我目前陷入困境,试图弄清楚如何正确使用我目前在方程式中指定为字符串的运算符。我假设它类似于将一个int字符串更改为整数或浮点数,但这就是我已经得到的结果。完整的代码在下面,所有粗线都是代码中的注释,引用了我们赋值中的步骤。感谢您的任何答案,如果您有任何批评,但是对此感到满意,这只是我在该主题上的第二次任务。
#Welcome and Rules
print("Welcome to calculator.py")
print("Valid numbers are 1 through 99")
print("Valid operators are +, -, *, /, //, %, **")
#Take in first integer that is between 0 and 100.
firstInt = int ( input ("Enter the first number: "))
#Take in an operator to operate on the integers.
opStr = input ("Enter a valid operator: ")
#Take in second integer that is between 0 and 100.
secondInt = int ( input ("Enter the second number: "))
#Prints the first error encountered then does not continue execution
#Errors include: values not between 0 and 100, or the operator is not
#of the type: +, -, *, /, //, %, **.
if (firstInt <= 1 or firstInt >= 100):
print ("Your first integer is invalid.")
elif (opStr != "+" or opStr != "-" or opStr != "*" or opStr != "/" or \
opStr != "//" or opStr != "%" or opStr != "**"):
print ("You entered an invalid operator.")
elif (secondInt <= 1 or secondInt >= 100):
print ("Your second integer is invalid.")
#Calculates the answer
answer = (firstInt opStr secondInt)
#Print the answer to screen
else:
print(answer)
&#13;
答案 0 :(得分:0)
您可能希望基于运算符执行if-else语句。例如:
if opStr = "+":
answer = firstInt + secondInt
elif opStr = "-":
answer = firstInt - secondInt
elif opStr = "*":
answer = firstInt * secondInt
等...
如果你更进一步,我会建议使用一些函数来重用/简化代码。