带有输入的Python CLI计算器错误



这是我的代码,

def divide():
# if x is not an int or float, run the input function again...
x = input("Enter a number to divide. ")
while True:
    try:
        if x != int(x) or x != float(x):
            x = input("Error! Please try again, enter a number to divide. ")
        else:
            break
    except ValueError:
        print("value error")
        break
y = input("Enter a number to divide " + x + " by. ")
while True:
    try:
        if y != int(y) or y != float(y):
            y = input("Error! Please try again, enter a number to divide " + x + " by. ")
        else:
            break
    except ValueError:
        print("value Error")
        break
if x == int(x) or y == int(y):
    x = int(x)
    y = int(y)
else:
    x = float(x)
    y = float(y)
divideAns = x / y
divide.result = str(x) + " / " + str(y) + " = " + str(divideAns)
return divide.result

所以我的问题是当我运行分隔函数时,假设一个粗心的用户只是键入胡说八道,我会遇到错误。除非我明确键入整数我会遇到错误,否则我希望用户能够遇到任何不是数字或浮动的东西并获得自定义错误。其次,我希望用户能够将整数和浮子划分。我觉得我的想法正朝着正确的方向发展,但我似乎无法使它正常工作。我找到了另一篇文章,谈到只将所有内容转换为浮子,但是我想保留,ints ints和floats浮动。这可能吗?如果是这样,什么是最佳方法。

写下这样的函数,该函数试图将用户输入转换为int或float,并在不可能的情况下提高例外。

class InvalidUserInput(Exception):
    '''
    Signals that user did not enter a valid value
    '''
    pass
def float_or_int_from_str(inp: str):
    '''
    Reads string and tries to extract int or float
    from it. If this is not possible, raises 
    InvalidUserInput
    '''
    try:
        return int(inp)
    except ValueError:
        pass
    try:
        return float(inp)
    except ValueError:
        pass
    # No matches so far -> raise Exception
    raise InvalidUserInput("'{}' is neither a float nor an int".format(inp))

您可以使用此功能来强制执行有效的用户输入:

user_input = float_or_int_from_str(input("Enter a number to divide. "))

使用这些try: except:构造的一种替代方法是使用正则表达式实际分析用户输入。看起来像这样:

import re
def float_or_int_from_str(inp: str):
    '''
    Reads string and tries to extract int or float
    from it. If this is not possible, raises 
    InvalidUserInput
    '''
    if re.match(r"[+-]?[0-9]+", inp) is not None:
        return int(inp)
    elif re.match(r"[+-]?[0-9]*.[0-9]*(e[+-]?[0-9]+)?", inp) is not None:
        return float(inp)
    else:
        raise InvalidUserInput("...")    

如果要执行用户始终使用浮子或ints,则可以添加

之类的东西
if not type(a) is type(b):
    raise InvalidUserInput("...")

只是几个问题。

您的两个输入在try块之外。这将使功能失败。
您还必须考虑到所有输入都被视为字符串。您需要将它们转换为float(以后可以处理float vs null)以测试它们是数字的。

def divide():
    # if x is not an int or float, run the input function again...
    while True:
        try:
            x = float(input('que numero'))
            break
        except:
            print('that's no numero!')
    while True:
        try:
            y = float(input('que numero'))
            break
        except:
            print('that's no numero!')
    return x/y if x/y != int(x/y) else int(x/y)

这将为您完成工作...

我不知道您为什么要保留ints ints and floats floats,它们都只有一个数字有一个小数点...从来没有少我做!

def divide():
    x = False
    while not x:
        try:
            x = float(input("Enter a number to divide: "))
        except ValueError:
            print("Please enter a float or an integer, not a string..    .")
    # This checks if it's an int or a float.
    x = str(x).split('.')
    if x[1] == '0':
        x = int(x[0])
    else:
        x = float(".".join(x))
    y = False
    while not y:
        try:
            y = float(input("Enter a number to divide %s by: " % x))
        except ValueError:
            print("Please enter a float or an integer, not a string...")
        if y == 0:
            y = False

    y = str(y).split('.')
    if y[1] == '0':
        y = int(y[0])
    else:
        y = float(".".join(y))
    divideAns = x / y
    result = str(x) + " / " + str(y) + " = " + str(divideAns)
    return result

最新更新