我有一个基本的计算器脚本,正在尝试让用户按下一个运算符(+,-,*,/或0),然后忽略是否按回车键,而是等到他们按下等号-然后打印结果。我已经安装了键盘模块,并认为我可以只使用“和keyboard.is_pressed”来提示,但这是行不通的。
# You must install keyboard to run this program in order to capture the equal sign key press as a trigger for Enter.
import sys, keyboard
# Create calculate function with cal class.
def calculate():
class cal():
def __init__(self,a,b):
self.a=a
self.b=b
# Define operations.
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
# Prompt for first number.
a=int(input("Enter first number: "))
# If first number is zero prompt for rentry.
while a == 0:
a=int(input("Enter a first number that is not zero: "))
# If first number isn't 0 then prompt for second number.
if a != 0:
b=int(input("Enter second number: "))
# If second number is zero prompt for rentry.
while b == 0:
b=int(input("Enter a second number that is not zero: "))
# If both numbers are != 0 ask for operation.
obj=cal(a,b)
operatorChoice = '+'
if operatorChoice!=0:
print("Choose operation then press Enter \n + | Add \n - | Subtract \n * | Multiply \n / | Divide \n 0 | Exit")
operatorChoice = input("Enter operation: ")
# Perform operation based on user selection.
if operatorChoice == '+' and keyboard.is_pressed('='):
print("----------\n",a," + ",b," = ",obj.add(),"\n----------")
elif operatorChoice == '-' and keyboard.is_pressed('='):
print("----------\n",a," - ",b," = ",obj.sub(),"\n----------")
elif operatorChoice == '*' and keyboard.is_pressed('='):
print("----------\n",a," * ",b," = ",obj.mul(),"\n----------")
elif operatorChoice == '/' and keyboard.is_pressed('='):
print("----------\n",a," / ",b," = ",round(obj.div(),2),"\n----------")
elif operatorChoice == '0':
print("----------\nExit program.\n----------")
# If not one of the provided operations, display error.
else:
print("Invalid operation selection.")
# Add again() function to calculate() function
def again():
calc_again = input("Do you want to calculate again? Please type Y for YES or N for NO.\n")
if calc_again.upper() == 'Y':
calculate()
again()
elif calc_again.upper() == 'N':
print('Okay, bye Felicia!')
else:
again()
calculate()
again()