【问题标题】:Python Programming ExersizePython 编程练习
【发布时间】:2016-01-27 15:54:54
【问题描述】:

我被这个问题困住了,它在 Python 中:

编写一个程序,反复提示用户输入整数,直到用户输入“完成”。输入“完成”后,打印出最大和最小的数字。如果用户输入的不是有效数字,请使用 try/except 捕获它并发出适当的消息并忽略该数字。

这是我现在拥有的代码:

largest = None
smallest = None
while True:
     num = raw_input("Enter a number: ")
     if num == "done" : break

     try:
          num = float(num)
     except:
          print "Invalid input"
          continue 

     if num > largest:
         largest = num
     elif num < smallest:
         smallest = num

     largest = str(largest)
     smallest = str(smallest)    


print "Maximum " + "is " + largest
print "Minimum " + "is " + smallest

【问题讨论】:

  • 这里没有问题。
  • 对我来说看起来不错。我不明白,这是一个问题吗?
  • 您没有提出问题或说明您的代码有问题。阅读帮助页面。

标签: python python-2.7


【解决方案1】:

您遇到了一些缩进问题,并且逻辑不起作用。如果您以不同的顺序输入数字,则会输出错误的结果。我在代码中包含了 cmets 供您查看。

largest = None
smallest = None

while True:
    # Move try here, as it would previously crash if you left a blank line
    try:
        num = raw_input("Enter a number: \n")
    except:
        # Field was left blank
        print "Invalid input"
        continue

    if num == "done":
        break
    else:
        if num.lstrip('-').replace('.', '').isdigit(): # No need for a try here, check if it's a valid number (replace and lstrip to include floats and negatives)
            num = float(num)
            # Auto-set if it's None
            if largest is None or num > largest:
                largest = num
            if smallest is None or num < smallest:
                smallest = num
        else:
            # Field was not a number
            print "Invalid input"

# Print results
print "Maximum is {0}".format(largest)
print "Minimum is {0}".format(smallest)

【讨论】:

    【解决方案2】:

    这两行需要去齿

     largest = str(largest)
     smallest = str(smallest)    
    

    所以在循环退出之前它们不会被执行。

    或者干脆把它们排除在外,让print 进行转换

    print "Maximum is ", largest
    print "Minimum is ", smallest
    

    如果它们是None,您还应该在循环中初始化这些值

        if num is None or num > largest:
             largest = num
        if smallest is None or num < smallest:
             smallest = num
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多