简体   繁体   English

在python中使用random.randint帮助

[英]Using random.randint help in python

The following code is my attempt at simulating a lottery. 以下代码是我尝试模拟彩票的尝试。

import random

def lottery(numbers):
    lottoNumbers = [randint('0,100') for count in range(3)]

    if numbers == lottoNumbers:
        print('YOU WIN $10,000')
    else:
        print('YOU LOSE,DUN DUN DUNNN!')
    return numbers


def main():
    numbers = int(input('Enter a number: '))
    if numbers == lottoNumbers:
        numbers = lottery(numbers)
    else:
        numbers = lottery(numbers)




main()

Hey guys I've gotten this far with the help you've given me. 嗨,伙计们,我已经得到您的帮助了。 I'm trying to write the code so that 3 lotto numbers at random will be chosen. 我正在尝试编写代码,以便随机选择3个乐透号码。 Then the user must enter 3 of his/her own lotto numbers. 然后,用户必须输入自己的3个乐透号码。 If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. 如果他们所有的3个数字都正确,那么他们将赢得全部奖金;如果他们获得3个数字,但顺序不正确,那么他们将赢得部分奖金。 Obviously if they guess all wrong then a print statement would state that. 显然,如果他们猜错了,那么打印语句将说明这一点。 What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. 我很困惑的是如何编写代码,以便用户可以输入3个数字来尝试匹配随机彩票数字。 I also want to print the 3 lottery numbers after the user inputs his/her choices. 我还想在用户输入选择后打印3个彩票号码。 Any ideas guys? 有想法吗?

Thanks for your help everyone. 谢谢大家的帮助。

You seem a bit confused about what the role of the arguments in a function are. 您似乎对函数中参数的作用感到困惑。 You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. 您已经说过,您的randm函数采用参数“ number”,但是实际上您并没有在任何地方使用它。 The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used. 下次出现该数字时,您已为其分配了一个全新的值,因此传递给randm的任何值实际上都不会使用。

Also, the function is trying to return x, when x hasn't been assigned within the function. 另外,当未在函数中分配x时,该函数尝试返回x。 Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x. 您可能已经定义了一个名为x的全局变量,在这种情况下,该函数将仅返回该变量,否则该函数将因找不到变量x而失败。

Here's a quick example I've done where you pass their three numbers as a list as an argument to the function. 这是我做的一个简单示例,其中您将三个数字作为列表传递给函数。

import random

theirNumbers=[5,24,67]

def checkNumbers(theirNumbers):
    lottoNumbers = []
    for count in range(3)
            lottoNumbers.append(random.randint(0,100))
    winning = True
    for number in theirNumbers:
    if not each in lottoNumbers: winning=False
    if winning == True: print("Winner!")

There are a few things wrong with your implementation, to name a few: 您的实现存在一些错误,仅举几例:

if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so: 如果尝试将randm函数的输出与x进行比较,则需要在函数中包含一个返回值,如下所示:

def randm():
    return return_value

You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so: 您似乎正在打印所有值,但没有存储它们,最后您只会得到最后一个值,您应该尝试将它们存储在这样的列表中:

list_name = [randint(0,100) for x in range(x)]

This will generate randint(0,100) x times in a list, which will allow you to access all the values later. 这将在列表中生成randint(0,100) x次,这将使您以后可以访问所有值。

To fix up your code as close to what you were attempting as possible I would do: 为了使您的代码尽可能地接近您的尝试,我会这样做:

import random

def randm(user_numbers):
    number = []
    for count in range(3):
        number.append(random.randint(0, 100))
    print(number)
    return user_numbers == number

if randm(x):
    print('WINNER')

If you are looking for a very pythonic way of doing this task, you might want to try something like this: 如果您正在寻找一种非常Python化的方法来执行此任务,则可能需要尝试如下操作:

from random import randint

def doLotto(numbers):
    # make the lotto number list
    lottoNumbers = [randint(0,100) for x in range(len(numbers))]

    # check to see if the numbers were equal to the lotto numbers
    if numbers == lottoNumbers:
        print("You are WinRar!")
    else:
        print("You Lose!")

I'm assuming from your code (the print() specifically) that you are using python 3.x+ 我从您的代码(特别是print())假设您正在使用python 3.x +

Try to post your whole code. 尝试发布您的整个代码。 Also mind the indentation when posting, there it looks like the definition of your function would be empty. 在发布时还要注意缩进,那里的函数定义似乎是空的。

I'd do it like this: 我会这样:

import random

def lottery():
  win = True
  for i in range(3):
    guess = random.randint(1,100)
    if int(raw_input("Please enter a number...")) != guess:
      win = False
      break

  return win

Let so do this in few steps. 让我们分几个步骤进行。 First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs. 您在编写代码时应该学习的第一件事是让单独的代码段(函数或对象)完成不同的工作。

First lets create function to make lottery: 首先让我们创建彩票功能:

def makeLottery(slotCount, maxNumber):
    return tuple(random.randint(1,maxNumber) for slot in range(slotCount))

Next lets create function to ask user's guess: 接下来让我们创建函数来询问用户的猜测:

def askGuess(slotCount, maxNumber):
    print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
    while True: #we will ask user until he enter sumething suitable
        userInput = raw_input()
        try:
            numbers = parseGuess(userInput,slotCount,maxNumber)
        except ValueError as err:
            print("please ensure your are entering integer decimal numbers separated by space")
        except GuessError as err:
            if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
            if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))

        return numbers

here we are using another function and custom exception class, lets create them: 在这里,我们使用另一个函数和自定义异常类,让我们创建它们:

def parseGuess(userInput, slotCount,maxNumber):
    numbers = tuple(map(int,userInput.split()))
    if len(numbers) != slotCount : raise GuessError(wrongCount = True)
    for number in numbers:
        if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
    return numbers

class GuessError(Exception):
    def __init__(self,wrongCount = False, notInRange = False):
        super(GuessError,self).__init__()
        self.wrongCount = wrongCount
        self.notInRange = notInRange

and finally function to check solution and conratulate user if he will win: 最终用于检查解决方案并向用户证明他是否会获胜:

def checkGuess(lottery,userGuess):
    if lottery == userGuess : print "BINGO!!!!"
    else : print "Sorry, you lost"

As you can see many functions here uses common data to work. 如您所见,这里的许多功能都使用通用数据来工作。 So it should suggest you to collect whole code in single class, let's do it: 因此,它建议您在单个类中收集整个代码,让我们开始吧:

class Lottery(object):
    def __init__(self, slotCount, maxNumber):
        self.slotCount = slotCount
        self.maxNumber = maxNumber
        self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))

    def askGuess(self):
        print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
        while True: #we will ask user until he enter sumething suitable
            userInput = raw_input()
            try:
                numbers = self.parseGuess(userInput)
            except ValueError as err:
                print("please ensure your are entering integer decimal numbers separated by space")
                continue
            except GuessError as err:
                if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
                if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
                continue

            return numbers

    def parseGuess(self,userInput):
        numbers = tuple(map(int,userInput.split()))
        if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
        for number in numbers:
            if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
        return numbers

    def askAndCheck(self):
        userGuess = self.askGuess()
        if self.lottery == userGuess : print "BINGO!!!!"
        else : print "Sorry, you lost"

finally lets check how it works: 最后让我们检查一下它是如何工作的:

>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123  asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM