2
import random

b = random.choice([2309,1897,2307])

def function(user):
    user.getApple().eatTheApple(b, 2000, 50, 1, 8663, 4444)

I am fairly new to python but I'm picking it up quickly. B is the variable and it equals a 4 digit number. This 4 digit number will be picked at random.

Then I would like this value to be placed alongside other fixed values such as 2000, 50, 1, 8663 and 4444.

How could I do this? I've been looking around for ages.

5
  • 3
    what's wrong with the code you have now? Commented Jul 30, 2013 at 1:49
  • 4
    You have some code, but what is relevant about the code? Does it represent something that doesn't work? Commented Jul 30, 2013 at 1:49
  • What's a user? Does the input to function actually have a getApple method that returns a thing with an eatTheApple method? Commented Jul 30, 2013 at 1:53
  • It's not entirely clear what you're asking. Are you trying to figure out how to use a global variable in a function? Please help us out by giving us a little more context behind what you want to happen, and what's going wrong. Commented Jul 30, 2013 at 1:55
  • You've also specify that b is a four-digit number; do you want a check in the function to see if that's true, or do we assume that it's been appropriately calculated? Commented Jul 30, 2013 at 1:59

1 Answer 1

2

Just add b as a parameter of the function, if I understand you correctly.

Consider:

def function(user,b):
    user.getApple().eatTheApple(b, 2000, 50, 1, 8663, 4444)

Then we could test with (assuming the class User is defined somewhere else):

import random
myUser = User()

b = random.choice([2309,1897,2307])
function( myUser , b )

We've made a function of two parameters, and passed them both in! An alternative would be:

def function(user):
    user.getApple().eatTheApple( random.choice([2309,1897,2307], 2000, 50, 1, 8663, 4444)

I've assumed that User is a class somewhere, so there might be a prettier way to do this yet, if this is appropriate for your circumstances (it might not be). We have our class declaration:

class User:
    def __init__( self ):
        #this code is executed when the class is created
        self.b = random.choice([2309,1897,2307])

    def function( self ):
        #this code is owned by each User object
        user.getApple().eatTheApple(self.b, 2000, 50, 1, 8663, 4444)

That would be executed by:

myUser = User()
myUser.function()

Python likes object-oriented design, so this would be nice! However, it assumes that the "b" value is personal to the user, and doesn't change. I'll give you alternatives, if it does

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.