简体   繁体   中英

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. Then the user must enter 3 of his/her own lotto numbers. 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. 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. I also want to print the 3 lottery numbers after the user inputs his/her choices. 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. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.

Also, the function is trying to return x, when x hasn't been assigned within the function. 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.

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:

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.

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:

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+

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!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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