Python While循环中的用户输入
下面是我的代码,它应该接受3个正整数作为用户的输入。然而,它并没有按照预期工作Python While循环中的用户输入,python,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
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个输入之后再次询问输入,但是如果我放置了非数字,我希望它在初始部分之后再次询问 试试这个:
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)
写三个几乎相同的代码片段来读取三个整数是没有意义的。您需要一个获得一个数字的函数。您可以调用此函数三次,或者,实际上,根据需要调用任意次数:
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
您可以分离测试以检查输入是否是函数的正整数
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\u 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
如果需要整数,可以使用int函数。这将强制用户输入一个整数。发布的代码无效。第二,一次只选一个号码,在正确选择前一个号码之前不要选下一个号码。你试过了吗?(提示:否)@Joey试试这个解决方案,告诉我它是否对你有效??