【问题标题】:python input check function not being called properlypython输入检查功能没有被正确调用
【发布时间】:2015-06-05 21:21:08
【问题描述】:

我正在使用 Python 开发一个非常简单的温度转换器(仅供练习),并且正在努力处理一些 UX 组件。我希望进行检查以在进行无效输入时继续提示输入变量。我的完整代码如下:

o_temp = ''

def temp_input(o_temp):
    o_temp = raw_input('Enter a temperature (round to nearest integer): ')
    return o_temp

def temp_input_check(o_temp):   
    o_temp = list(o_temp)
    for i in o_temp:
        if i not in '1234567890':
            print 'Invalid entry. Please enter only the numerical temperature measurement in integer format.'
            temp_input(o_temp)
        else:
            break

def converter(o_temp):
    unit = raw_input('Convert to (F)ahrenheit or (C)elsius? ')
    unit  = unit.upper()
    if unit == 'F' or unit == 'f':
        n_temp = (9.0/5.0) * int(o_temp) + 32
        print '%d C = %d F' % (o_temp, n_temp)
        quit()
    elif unit == 'C' or unit == 'c':
        n_temp = (5.0/9.0) * (int(o_temp) - 32)
        print '%d F = %d C' % (o_temp, n_temp)
        quit()
    else: #check for valid entry
        print 'Invalid entry. Please enter F for Fahrenheit or C for Celsius'
        unit_input()

def temp_converter():
#title, call sub-functions
    print ''
    print 'Temperature Converter'
    print ''
    temp_input(o_temp)
    temp_input_check(o_temp)
    converter(o_temp)

temp_converter()

但是,当我在 o_temp 提示中输入无效条目(例如,字母或字母和数字的组合)时,代码似乎无法识别这是无效的并继续单元提示。我没有正确返回变量吗?这里有什么问题?我尝试删除最初的 o_temp 声明,但随后出现“NameError:未定义全局名称 'o_temp'”

编辑

我想出了这个解决方案,还有什么进一步的建议来完善代码吗?

def converter():
    print 'Temperature Converter'
    while 1:
        temp = raw_input('Starting temperature? ')
        try:
            temp = float(temp)
        except ValueError:
            print 'Invalid entry. Please enter only the numerical temperature measurement.'
        else:
            break
    while 1:
        unit = raw_input('Convert to Fahrenheit or Celsius? ')    
        if unit.upper().startswith('F') == True:
            print "%f C = %f F" % (temp, temp*9./5+32)
            return False
        elif unit.upper().startswith('C') == True:
            print "%f F = %f C" % (temp, (temp-32)*5./9)
            return False
        else:
            print 'Invalid entry. Please enter F for Fahrenheit or C for Celsius'

converter()

【问题讨论】:

  • 您的实际问题是什么?当您运行此代码时会发生什么,这与您的预期有何不同?
  • 对不起,问题没有写完,不小心提前提交了。完整的代码和问题现已提出!
  • 另外,您收到“名称错误”的原因是因为您的 o_temp 从未在 temp_converter 中的任何位置分配。你传入的变量对你的函数没有价值!

标签: python return global-variables try-catch raw-input


【解决方案1】:

你定义了一些函数,然后调用temp_coverter()。这个函数调用temp_input(otemp),给它发送一个空字符串,我看不到任何原因,除了你可能不知道你可以定义一个没有参数的函数。然后,此函数返回一个值,您不保存该值。

之后,temp_input_check(otemp) 被调用,它尝试验证相同的空字符串。这个函数的返回值没有保存,损失不大,因为None不是一个特别有用的保存值。

然后converter(otemp) 将相同的旧空字符串发送到实际转换器。混乱结果。

我建议与tutorial 共度美好时光。

完成后,代码应该看起来更像这样:

def converter():
    print 'Temperature Converter'
    unit = raw_input('Convert to Fahrenheit or Celsius? ')
    while 1:
        temp = raw_input('Starting temperature? ')
        try:
            temp = float(temp)
        except ValueError:
            print 'Not a valid temperature.'
        else:
            break
    if unit.lower().startswith('f'):
        print "%f C = %f F" % (temp, temp*9./5+32)
    else:
        print "%f F = %f C" % (temp, (temp-32)*5./9)

converter()

【讨论】:

    【解决方案2】:

    你的 for 循环没有正确实现。

    def temp_input_check(o_temp):   
        o_temp = list(o_temp)
        for i in o_temp:
            if i not in '1234567890':
                print 'Invalid entry. Please enter only the numerical temperature measurement in integer format.'
                temp_input(o_temp)
            else:
                break
    

    您检查 每个字符 是否存在无效条目。如果你输入了多个无效字符,它会在你已经确定字符串无效后继续触发!

    另外,如果你的第一个字符是有效的,你告诉它从 for 循环中中断(在你的代码中 1fdsdfdsf 将是一个有效的温度,因为它会在点击 else 语句并从循环中中断后跳过每个字符)。

    此外,您的 temp_input 不需要在函数中接受参数(您只需返回用户的输入)。您实际上想在调用函数后对其进行分配,而不是将其作为参数

    此外,您再次调用 temp_input 以获取用户输入,但没有在任何地方通过返回捕获该输入 - 所以它最终什么也没做。如果您想让用户尝试输入更好的温度,您应该让您的函数返回 True 或 False,然后在检查器的外部捕获它:

    def temp_input_check(o_temp):   
        o_temp = list(o_temp)
        for i in o_temp:
            if i not in '1234567890':
                print 'Invalid entry. Please enter only the numerical temperature measurement in integer format.'
                return False
            else:
                pass # nothing is wrong with this character, keep checking
        return True # if we hit this line, there were no problem characters
    

    然后,当你调用这些东西时:

    while(1):
        o_temp = temp_input()
        if temp_input_check(o_temp):
            break # this means our o_temp is allllright. 
                  # otherwise, go back to the start of the loop and ask for another temp
    converter(o_temp)
    

    【讨论】:

      【解决方案3】:

      因为您最后提到了“o_temp”作为函数参数,但在开始时将其作为空字符串提到。不要为全局和函数变量提供相同的名称(只是为了避免混淆)。该函数将您上面提到的 o_temp 作为参数,而忽略了其中的参数。

      raw_input 也不会将输入视为字符串。改用input 来避免不使用str 来纠正循环的敏感性。

      这样就可以了:

      def converter():
          o_temp = float(raw_input('Enter a temperature (round to nearest integer): '))
          for i in str(o_temp):
              if i not in ['1','2','3','4','5','6','7','8','9','0','.']:
                  print 'Invalid entry. Please enter only the numerical temperature measurement in integer format.'
          unit = raw_input('Convert to (F)ahrenheit or (C)elsius? ')
          if unit in ['f','F']:
              n_temp = (9.0/5.0) * float(o_temp) + 32
              print '%f C = %f F' % (o_temp, n_temp)
          elif unit in ['c','C']:
              n_temp = (5.0/9.0) * (float(o_temp) - 32)
              print '%f F = %f C' % (o_temp, n_temp)
          else: #check for valid entry
              print 'Invalid entry. Please enter F for Fahrenheit or C for    Celsius'
              unit_input()
      
      def temp_converter():
      #title, call sub-functions
          print ''
          print 'Temperature Converter'
          print ''
          converter()
      
      print temp_converter()
      

      【讨论】:

        猜你喜欢
        • 2014-11-22
        • 2022-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        相关资源
        最近更新 更多