Python While循环中的UserInput

2024-03-28 09:43:55 发布

您现在位置: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个输入被放置之后再次询问输入,但是如果我输入一个非数字,我希望它在初始部分之后再次询问。在


Tags: ofthetoinputisthismanyhow
3条回答

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

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方法。在

^{pr2}$

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

编写三个几乎完全相同的代码片段来读取三个整数是没有意义的。你需要一个得到一个数的函数。您可以调用此函数三次,事实上,可以根据需要调用任意次数:

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()引发一个异常,使循环继续。在

示例:

^{pr2}$

试试这个:

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)

相关问题 更多 >