gpt4 book ai didi

Python 断言不工作 : limit user enter only stated numbers but assert not working

转载 作者:行者123 更新时间:2023-12-05 06:57:08 25 4
gpt4 key购买 nike

这里是初学者。我尝试通过输入 6 个数字来创建彩票游戏。下面的代码尝试检查用户输入的数字:首先,它是否是整数;第二,是否在规定的范围内。但是,ValueError 对 int 的检查有效,但 assert 检查的数字范围无效。

def buy_lottery_ticket():
global credit
credit -= 5
while True:
try:
entered_numbers = input('Enter your 6 favorites numbers!(1 ~ 20): ')
entered_numbers_list = entered_numbers.split(',')
ticket_numbers = {int(n) for n in entered_numbers_list}
print(ticket_numbers)
return ticket_numbers
assert 0 < entered_numbers_list < 21
except ValueError:
print("Not an integer! Please enter an integer.")
except AssertionError:
print("Please enter an integer between 1 and 20")
else:
break

感谢您的投入和帮助。提前致谢。

最佳答案

您正在尝试检查 return 语句后的 6 个数字和范围值。这是执行相同操作的方法。

此外,在您的代码中,您有 credit -= 5。不确定您首先在哪里设置值。你可能想调查一下。我已经注释掉了那行代码。

def buy_lottery_ticket():
global credit
#credit -= 5
while True:
entered_numbers = input('Enter your 6 favorites numbers!(1 ~ 20): ')
try:
entered_numbers_list = entered_numbers.split(',')
ticket_numbers = {int(n) for n in entered_numbers_list}
if len(ticket_numbers) > 6:
print ('You must enter only 6 unique numbers')
continue
elif len(ticket_numbers) < 6:
print ('You must enter at least 6 unique numbers')
continue
if min(ticket_numbers) < 1 or max(ticket_numbers) > 20:
print ("Please enter an integer between 1 and 20")
continue
print(ticket_numbers)
return ticket_numbers
except ValueError:
print("Not an integer! Please enter an integer.")

print (buy_lottery_ticket())

这个的输出将是:

Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3,8,9
You must enter only 6 unique numbers
Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3
You must enter at least 6 unique numbers
Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3,15
You must enter at least 6 unique numbers
Enter your 6 favorites numbers!(1 ~ 20): 5,7,15,17,3,8
{3, 5, 7, 8, 15, 17}
{3, 5, 7, 8, 15, 17}

关于Python 断言不工作 : limit user enter only stated numbers but assert not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64962245/

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