如何限制输入的数量并将int转换为列表Python



我试图将彩票的用户输入限制为七个字符,并且它只能接受整数,当我使用int(输入(时,它会给我一个ValueError。当我在输入之前删除int时,它工作得很好。然后,我使用split方法将输入更改为列表。如何限制输入?

import random
number_choice = int(input("Input 7 lottery numbers between 1 and 100"))    
lottery_ticket = number_choice.split()          
print(type(lottery_ticket))        
random_nums = random.sample(range(1, 100), 7)  # generate a list of random numbers
print(lottery_ticket)
print(random_nums)
matches = set(lottery_ticket).intersection(random_nums)  # set.intersection matches the elements that are similar
print("The matching numbers are", matches)     

def matchingNumber():
countMatches = sum(i in random_nums for i in lottery_ticket)
print(countMatches)
if countMatches == 2:
print("You have won £5")
elif countMatches == 3:
print("you have won £20")
elif countMatches == 4:
print("you have won £40")
elif countMatches == 5:
print("you have won £100")
elif countMatches == 6:
print("you have won £10,000")
elif countMatches == 7:
print("you have won £1000000")
else:
print("You have won nothing!")

matchingNumber()

正如Pranav所指出的,您正试图在不兼容的类型(integer(上应用方法(split(。试着这样做吧,它首先将数字作为字符串读取,然后将它们转换为整数。接下来,它将检查是否给出了7个数字——如果没有,它将退出程序。它假设您将在控制台中键入格式为3, 45, 33, 7, 3, 90, 49的输入。

import random
number_choice = input("Input 7 lottery numbers between 1 and 100n")    
lottery_ticket_strings = number_choice.split(', ')
if len(lottery_ticket_strings) != 7:
print("You did not input 7 lottery numbers!")
exit(0)
lottery_ticket = [int(s) for s in lottery_ticket_strings]          
print(type(lottery_ticket))        
random_nums = random.sample(range(1, 100), 7)  # generate a list of random numbers
print(lottery_ticket)
print(random_nums)
matches = set(lottery_ticket).intersection(random_nums)  # set.intersection matches the elements that are similar
print("The matching numbers are", matches)     

def matchingNumber():
countMatches = sum(i in random_nums for i in lottery_ticket)
print(countMatches)
if countMatches == 2:
print("You have won £5")
elif countMatches == 3:
print("you have won £20")
elif countMatches == 4:
print("you have won £40")
elif countMatches == 5:
print("you have won £100")
elif countMatches == 6:
print("you have won £10,000")
elif countMatches == 7:
print("you have won £1000000")
else:
print("You have won nothing!")

matchingNumber()

最新更新