我正在为我的班级写一个彩票计划。我已经查看了stackoverflow的答案,但我发现的所有内容都已提升。我想知道是否有办法缩短if语句并减少它们。
import random
def lottery():
lottoNumber1 = random.randint(1,50)
print(lottoNumber1)
lottoNumber2 = random.randint(1,50)
print(lottoNumber2)
lottoNumber3 = random.randint(1,50)
print(lottoNumber3)
return lottoNumber1,lottoNumber2,lottoNumber3
userChoice1 = int(input('Choose a number between 1 and 50: '))
userChoice2 = int(input('Choose a number between 1 and 50: '))
userChoice3 = int(input('Choose a number between 1 and 50: '))
lottoNumber1, lottoNumber2, lottoNumber3 = lottery()
if userChoice1 == lottoNumber1:
if userChoice1 == lottoNumber2:
if userChoice1 == lottoNumber3:
if userChoice2 == lottoNumber1:
if userChoice2 == lottoNumber2:
if userChoice2 == lottoNumber3:
if userChoice3 == lottoNumber1:
if userChoice3 == lottoNumber2:
if userChoice3 == lottoNumber3:
print('You win $1,000')
else:
print('Try it again!')
main()
答案 0 :(得分:1)
如果你创建了两个集合,一个持有彩票号码,另一个持有用户选择,那么一个if
语句可以比较它们:
import random
# Use sets to ensure lottery numbers and user choices are unique
lottoNumbers = set()
userChoices = set()
while len(lottoNumbers) < 3:
lottoNumbers.add(random.randint(1,50))
while len(userChoices) < 3:
userChoices.add(input('Choose a number between 1 and 50: '))
print(lottoNumbers)
print(userChoices)
if lottoNumbers == userChoices:
print('You win $1,000')
答案 1 :(得分:0)
这对你有用。
from random import randint
def lottery():
return [randint(1, 50) for x in range(3)]
user_choices = list(map(int, [input('Choose a number between 1 and 50: ') for x in range(3)]))
lotto_numbers = lottery()
print(user_choices)
print(lotto_numbers)
if any(user_choice == lotto_number for user_choice, lotto_number in zip(sorted(user_choices), sorted(lotto_numbers)))