Python中的UserInput while循环

时间:2018-04-05 05:03:21

标签: python

遵循我的代码,该代码应该从用户输入3个正整数。但是,它没有按照预期工作。

def getPositiveNumber(prompt):
    timeUnits = (input("This is the numnber of time units to simulate > "))
    numAtoms = (input("How many atoms should we simulate ? "))
    radBeaker = (input("The radius of the beaker is ? "))
    while True:
         if timeUnits.isnumeric() and numAtoms.isnumeric() and radBeaker.isnumeric():
         print("All your values are integers")
         break

     else:
         timeUnits = input("This is the number of units to simulate. >")
         numAtoms = input("How many atoms should we simulate ? ")
         radBeaker = input("The radius of the beaker is ? ")
return timeUnits, numAtoms, radBeaker

这导致在放置初始3个输入后再次询问输入但我希望它在初始部分之后再次询问,如果我输入非数字。

3 个答案:

答案 0 :(得分:0)

试试这个:

def getPositiveNumber(prompt):
  timeUnits = None
  numAtoms = None
  radBeaker = None
  while True:
    timeUnits = input('This is the numnber of time units to simulate > ')
    numAtoms = input('How many atoms should we simulate ? ')
    radBeaker = input('The radius of the beaker is ? ')
    if timeUnits.isnumeric() and numAtoms.isnumeric() and radBeaker.isnumeric():
      print 'All your values are integers'
      break
  return (timeUnits, numAtoms, radBeaker)

答案 1 :(得分:0)

编写三个几乎相同的代码片段来读取三个整数是没有意义的。你需要一个获得一个数字的函数。你可以调用这个函数三次,或者实际上,你可以多次调用它:

def get_positive_int(prompt):
    while True:        
        possibly_number = input(prompt + "> ")
        try:
            number = int(possibly_number)
        except ValueError: # Not an integer number at all
            continue
        if number > 0: # Comment this line if it's ok to have negatives
            return number

该函数依赖于int()识别的任何字符串都是有效整数的事实。如果是,则将号码返回给呼叫者。如果不是,int()会引发异常,使循环继续进行。

示例:

>>> get_positive_int("This is the number of units to simulate")
This is the number of units to simulate> ff
This is the number of units to simulate> -10
This is the number of units to simulate> 25
25

答案 2 :(得分:0)

您可以分开测试以检查输入是否为函数的正整数

def is_positive(n):
    """(str) -> bool
    returns True if and only if n is a positive int
    """
    return n.isdigit() 

接下来,您可以创建一个函数来请求正整数。为此避免使用str.isnumeric方法,因为它也会为浮点数返回True。相反,请使用str.isdigit方法。

def request_input(msg):
    """(str) -> str
     Return the user input as a string if and only if the user input is a positive integer
    """
    while True:
        retval = input(msg)
        if is_positive(retval):
            return retval
        else:
            print("Please enter a positive integer")

request_input将永远循环,直到收到正整数。这些简单的块可以组合起来实现您的需求。在您的特定情况下:

def get_user_inputs(prompt):
    time_units = request_input("This is the number of time units to simulate > ")
    num_atoms = request_input("How many atoms should we simulate ? ")
    rad_breaker = request_input("The radius of the beaker is ? ")
    return time_units, num_atoms, rad_breaker