【问题标题】:def python error repeatdef python错误重复
【发布时间】:2013-03-23 22:51:03
【问题描述】:

虽然我输入了一个数值,但它仍然给我一个错误。我不知道为什么会这样.. 帮助别人?

def is_string(s):
    rate = input(s)
    try:
        str.isalpha(rate)
        print('There was an error. Please try again. Make sure you use numerical values and alpabetical. ')
        return is_string(s)  #ask for input again
   except:
        return rate
ExRate = is_string('Please enter the exchange rate in the order of, 1 '+Currency1+' = '+Currency2)

def is_string2(msg):
    amount = input(msg)
    try:
        str.isalpha(amount)
        print('There was an error. Please try again. Make sure you use numerical values. ')
        return is_string2(msg)  #ask for input again
    except:
        return amount
Amount = is_string2('Please enter the amount you would like to convert:')

【问题讨论】:

  • 你想在这里做什么?
  • 阅读isalpha() 的文档,您可能会发现错误。
  • 您希望try 子句的哪一部分引发错误?打印“有一个错误”不足以打破try 语句。
  • @Ben OP 甚至没有这样做,因为他丢弃了结果并期望它无缘无故地抛出异常,因为这不是方法的作用,也没有理智的理由期待它会。
  • @Jemini 然后要做的事情是try: amount = int(raw_input(...)) 如果有的话。我也会特别关注ValueError

标签: python python-3.x function


【解决方案1】:

你在寻找这样的东西吗?

def get_int(prompt, error_msg):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print(error_msg)


rate = get_int(
    'Please enter the exchange rate in the order of, 1 {} = {}'
        .format(Currency1, Currency2),
    error_msg="Rate must be an integer")
amount = get_int(
    'Please enter the amount you would like to convert:',
    error_msg="Amount must be an integer")

【讨论】:

    【解决方案2】:

    我不确定你为什么要使用异常,什么时候应该使用 if 语句:

    def is_string(s):
        rate = input(s)
        if str.isalpha(rate):
            print('There was an error. Please try again. Make sure you use numerical values and alpabetical. ')
            return is_string(s)  #ask for input again
        else:
            return rate
    ExRate = is_string('Please enter the exchange rate in the order of, 1 '+Currency1+' = '+Currency2)
    
    def is_string2(msg):
        amount = input(msg)
        if str.isalpha(amount):
            print('There was an error. Please try again. Make sure you use numerical values. ')
            return is_string2(msg)  #ask for input again
        else:
            return amount
    Amount = is_string2('Please enter the amount you would like to convert:')
    

    【讨论】:

    • 我尝试了 if 语句,但它不适用于我的整个代码,因为我正在尝试创建货币转换器。谢谢。
    【解决方案3】:

    你不应该使用 try 语句,而且我认为你不应该使用 isalpha()。 isnumeric() 测试数字有效性。 isalpha() 会为像 "%#-@" 这样的字符串返回 false。

    while True:
        s = input("Enter amount: ")
        if s.isnumeric():
            break
        print("There was a problem. Enter a number.")
    

    【讨论】:

    • -1 用于非 Python 括号
    • 已修复。代码现在更加 Pythonic。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多