负输入值无法打印消息的问题

时间:2017-09-27 04:35:15

标签: python input

我编写了以下程序来计算并打印出一个给定上限的完美正方形。但是,当输入除正整数(例如,负整数或字母)之外的任何内容时,我无法使程序打印You must enter a positive integer。我该如何调整我的程序才能这样做?

"""Print all the perfect squares from zero up to a given maximum."""
def read_bound():
   """Reads the upper bound from the standard input (keyboard).
      If the user enters something that is not a positive integer
      the function issues an error message and retries
      repeatedly"""

   line = input("Enter the upper bound: ")
   try:
       upper_bound = int(line)
   except:
       raise ValueError("You must enter a positive integer.")
   else:
       return upper_bound  


def is_perfect_square(num):
   """Return true if and only if num is a perfect square"""
   for candidate in range(1, num):
       if candidate * candidate == num:
           return True
   return False



def print_squares(upper_bound, squares):
   """Print a given list of all the squares up to a given upper bound"""
   print("The perfect squares up to {} are: ". format(upper_bound))
   for square in squares:
       print (square, end=' ')


def main():
   """Calling the functions"""
   upper_bound = read_bound()
   squares = []
   for num in range(2, upper_bound + 1):
       if is_perfect_square(num):
           squares.append(num)

   print_squares(upper_bound, squares)    


main()

2 个答案:

答案 0 :(得分:0)

int转换任何看起来像整数的字符串。正面还是负面。

因此,在解析负值时,您永远不会有异常。您必须添加一个明确的raise到:

   upper_bound = int(line)
   if upper_bound < 0:
      raise ValueError("You must enter a positive integer, got {}".format(upper_bound))
   return upper_bound # don't forget to return the value

在这种情况下,您不需要try/except保护您的陈述(除了这是不好的做法,因为它会捕获任何异常,包括CTRL + C /用户中断)你只是这样做会抛出一个不太准确的错误信息。让你的程序使用stacktrace和整数解析中的clean异常正常崩溃。

答案 1 :(得分:0)

整数是整数,意味着它们可以是负数。你需要一个有条件的。我建议在花时间发布之前研究你正在使用的函数和它们返回的数据类型。