如何检查我在基于文本的计算器中输入的内容是否是数字



当我提示控制台要求用户为计算器输入数字时,我想检查用户输入的是否是数字。在first_input((中,我使用if-else条件来检查用户输入的内容是否是数字。尽管如果为false,则会再次调用该函数以提示用户键入数字,但一旦我尝试在计算器中计算,它就不会返回,为什么会出现这种情况,以及在用户未能输入数字后,如何正确返回数字?

# Operations variable
oper = "+-*/"
# Calculates basic operations
def calc(x, op, y):
for i in oper:
if i == str(op):
return eval(str(x) + op + str(y))
# Main function that controls the text-based calculator
def console_calculator():
def first_input():
x = input('Type your first number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
first_input()
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat 
def next_input():
y = input('Type your next number: ')
return y
answer = calc(first_input(), operation_input(), next_input())
print(answer)
console_calculator()

我建议使用try/except块。通过这种方式,它将返回整数本身,特别是因为您已经在eval块中将它们转换为字符串。

x = input('Type your first number: ')
try:
return int(x)
except ValueError:
print('Please type in a number')
...

此外,为了不断向用户询问一个整数,直到他们输入正确的值,我会使用while循环。

您可以使用一个函数调用两次,而不是使用两个函数进行用户输入。并且您还需要在用户输入中的函数调用之前添加CCD_ 1。

def console_calculator():
def user_input():
x = input('Type your number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
return user_input()
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat 

answer = calc(user_input(), operation_input(), user_input())
print(answer)

你实际上把答案藏在了自己的问题中:

如何正确返回数字

您忘记在其他分支中使用return

# Calculates basic operations
def calc(x, op, y):
for i in op:
if i == str(op):
return eval(str(x) + op + str(y))
# Main function that controls the text-based calculator
def console_calculator():
def first_input():
x = input('Type your first number: ')
if x.isnumeric():
return x
else:
print('Please type in a number')
return first_input() # missing return
def operation_input():
operat = input('Type one of the following, "+ - * /": ')
return operat 
def next_input():
y = input('Type your next number: ')
return y
answer = calc(first_input(), operation_input(), next_input())
print(answer)
console_calculator()

但是您也有编译错误,因为您引用了oper,但该参数被称为op

这只是回答了您的问题,但并没有解决架构问题(其他人会这样做,因为他们涵盖了更好的实现(。

相关内容

最新更新