gpt4 book ai didi

python - 通过一些检查获取一组数字之间的原始输入

转载 作者:行者123 更新时间:2023-11-28 19:55:52 24 4
gpt4 key购买 nike

我试图让用户输入 2 个数字,这些数字被分成 2 个整数的列表,但不幸的是我似乎无法让它们变成整数,但我也不确定我的支票是否正确将正确终止并返回我需要的东西。

def getlohiint():
lohilist = []
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
lohilist = lohi.split()
for x in lohilist:
int(x)
if lohilist[0]<=2 and lohilist[1]<=1000 and lohilist[0]<lohilist[1]:
break
else:
prompt = "%d is not in the range of 2 to 1000; "
prompt1 = "must be at least 2"
prompt2 = "must be no higher than 1000"
if lohilist[0]<2:
print prompt + prompt1
elif lohilist[1]>1000:
print prompt + prompt2
else:
print prompt + prompt1 + prompt2
lohi
high = lohilist[1]
low = lohilist[0]
return(low, high)

最佳答案

您永远不会将 int(x) 的结果分配给任何东西。通过列表理解最容易实现:

lohilist = [int(x) for x in lohi.split()]

请注意,您可以一次分配给多个目标:

low, high = [int(x) for x in lohi.split()]

会将 lohi 中的所有内容转换为整数,并一次性分配给两个变量。

您可能还想在这里测试异常:

def getlohiint():
while True:
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
try:
low, high = [int(x) for x in lohi.split()]
except ValueError:
# either not integers or not exactly 2 numbers entered.
print "You must enter exactly 2 numbers here"
continue

if low <= 2 and high <= 1000 and low < high:
# valid input, return
return low, high

if low > 2:
print 'The minimum must be 2 or lower'
if high > 1000:
print 'The maximum must be 1000 or lower'
if low >= high:
print 'The maximum must be greater than the minimum'

关于python - 通过一些检查获取一组数字之间的原始输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com