开始Python抽奖函数

2024-09-30 18:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,根据随机生成的“获胜者”序列评估用户输入。在输入用户的输入之前,代码将一直正常运行,然后停止。我使用的编辑器也有点奇怪,所以这里的缩进会被去掉,不过,我保证这不是问题所在。很抱歉。谢谢

from __future__ import print_function
import random
import sys

minimum, maximum = 1,69

def playPowerBall():
  instruction = "Please pick your {} number, between 1 and 69:"
  tickets = []
  for s in ('1st', '2nd', '3rd', '4th', '5th', '6th'):
    ticket = int(input(instruction.format(s)))
    tickets.append(ticket)

  range = (1,69)

  if any(ticket < minimum or ticket > maximum for ticket in tickets):
    print('One or more of the inputted numbers is not between 1-69. Please restart the function and try again.')
    sys.exit()

  winners = []

  for s in ('1st', '2nd', '3rd', '4th', '5th', '6th'):
    winner = random.sample(range(0,69), 6)
    winners.append(winner)

def matches(tickets, winners):
  score = 0

  for number in tickets:
    if number in winners:
      score += 1
    else:
      score += 0

    return score

  if 3 <= score:
    print('You picked at least three winning numbers, please claim your cash prize.')
  else:
    print('You do not have a winning combination. Would you like to play Powerball again? (Y/N)')
    response = str(input('Y/N:'))

    if response == 'Y':
      sys.restart()
    else:
      sys.exit()

Tags: 用户inimportnumberforifsysfunction
1条回答
网友
1楼 · 发布于 2024-09-30 18:21:47

您正在用语句range = (1, 69)覆盖内置函数range,然后执行winner = random.sample(range(0,69), 6),因此,您正在尝试调用元组(1, 69)。如果删除这样的语句range = (0, 69),错误就会消失。代码中还有其他问题,必须在playPowerBall末尾调用matches,必须从方法matches中删除return语句,sys没有restart函数,但可以递归调用playPowerBall

from __future__ import print_function
import random
import sys

minimum, maximum = 1,69

def playPowerBall():
  instruction = "Please pick your {} number, between 1 and 69:"
  tickets = []
  for s in ('1st', '2nd', '3rd', '4th', '5th', '6th'):
    ticket = int(input(instruction.format(s)))
    tickets.append(ticket)

  if any(ticket < minimum or ticket > maximum for ticket in tickets):
    print('One or more of the inputted numbers is not between 1-69. Please restart the function and try again.')
    sys.exit()

  winners = []

  for s in ('1st', '2nd', '3rd', '4th', '5th', '6th'):
    winner = random.sample(range(0,69), 6)
    winners.append(winner)

  matches(tickets, winners)

def matches(tickets, winners):
  score = 0

  for number in tickets:
    if number in winners:
      score += 1
    else:
      score += 0

  if 3 <= score:
    print('You picked at least three winning numbers, please claim your cash prize.')
  else:
    print('You do not have a winning combination. Would you like to play Powerball again? (Y/N)')
    response = str(input('Y/N:'))

    if response == 'Y':
      playPowerBall()
    else:
      sys.exit()

playPowerBall()

相关问题 更多 >