提问人:Ant753 提问时间:11/13/2023 更新时间:11/13/2023 访问量:48
如何检查用户输入的操作数是否有效?(蟒蛇)
How can I check if the user has entered a valid operand? (Python)
问:
我正在编写代码以在 python 中实现一个简单的计算器。我正在尝试检查用户是否输入了有效的操作数。我输入的代码如下。
calc = False
while calc == False:
firstNum = 0
operand = ''
secondNum = 0
firstNum = input('Please enter a number: ')
if firstNum.isdigit() == False:
print('Please enter a number.')
continue
else:
firstNum = int(firstNum)
operand = input('Please enter an operand (+, -, *, or /): ')
if operand != '/' or operand != '*' or operand != '+' or operand != '-':
print('Please enter a valid operand.')
continue
secondNum = input('Please enter another number: ')
if secondNum.isdigit() == False:
print('Please enter a number.')
continue
secondNum = int(secondNum)
if secondNum == 0 and operand == '/':
print('You cannot divide by 0. Please try again.')
continue
if operand == '+':
calc = True
print(f'{firstNum} + {secondNum} = {firstNum + secondNum}')
elif operand == '*':
calc = True
print(f'{firstNum} * {secondNum} = {firstNum * secondNum}')
elif operand == '-':
calc = True
print(f'{firstNum} - {secondNum} = {firstNum - secondNum}')
else:
calc = True
print(f'{firstNum} / {secondNum} = {firstNum / secondNum}')
calc = False
while calc == False:
firstNum = 0
operand = ''
secondNum = 0
listOfOperands = ['+', '-', '/', '*']
firstNum = input('Please enter a number: ')
if firstNum.isdigit() == False:
print('Please enter a number.')
continue
else:
firstNum = int(firstNum)
operand = input('Please enter an operand (+, -, *, or /): ')
if operand != listOfOperands:
print('Please enter a valid operand.')
continue
secondNum = input('Please enter another number: ')
if secondNum.isdigit() == False:
print('Please enter a number.')
continue
secondNum = int(secondNum)
if secondNum == 0 and operand == '/':
print('You cannot divide by 0. Please try again.')
continue
if operand == '+':
calc = True
print(f'{firstNum} + {secondNum} = {firstNum + secondNum}')
elif operand == '*':
calc = True
print(f'{firstNum} * {secondNum} = {firstNum * secondNum}')
elif operand == '-':
calc = True
print(f'{firstNum} - {secondNum} = {firstNum - secondNum}')
else:
calc = True
print(f'{firstNum} / {secondNum} = {firstNum / secondNum}')
代码的当前版本始终拒绝操作数并返回到 while 循环的顶部。如果用户没有输入 +、-、* 或 /,我想返回到循环的顶部,如果他们输入了四个字符之一,我想继续完成循环。
答:
评论
or
and
operand != '/' or operand != '*' or operand != '+' or operand != '-'
operand != listOfOperands
operand not in listOfOperands