This section of a program I am writing is supposed to take the random choice and then print it outside the function (I can't print from within as I need the variable later).
I am sure there is a simple solution to this, but I am unsure what it is.
#python2
def CompTurn():
RandTurn = [Column1,Column2,Column3,Column4]
Choice = random.choice(RandTurn)
return(Choice)
print Choice
Thank you.
Add the line
Choice = CompTurn()
before your print statement. Because the variables you declare within the function are not known outside of it, you have to store (or print directly, but then you cannot store it) the returned variable in a new variable.
You have defined your function correctly, but you never executed it! (You'll see that if you make it print something as a diagnostic.) You must run it to get the result:
chosen = CompTurn()
print chosen
Note that I used a different variable name. You could use the same variable name as a variable in your function, but it's still a different variable than the one in your function.
It is also important to realize that your function returns a value, not a variable. You can assign the value to a variable (as above) or print it immediately.
print CompTurn()
About your program, you don't need the brackets for return. It's s statement, not a function.
def CompTurn():
RandTurn = [Column1,Column2,Column3,Column4]
Choice = random.choice(RandTurn)
return Choice
Shorter:
def CompTurn():
RandTurn = [Column1,Column2,Column3,Column4]
return random.choice(RandTurn)
To print the return value, You can save it in a variable and print it
ret = CompTurn()
print ret
Or print directly:
print CompTurn()
Related
I am pretty new to python, and I was wondering about return and the stuff inside () when defining a new function. I do not want to run any code inside if __name__ == '__main__':. I want a function to do it. Why won't this work?
def money():
coins = 100
return coins
def doubleMoney(coins):
doubleCoins = int(coins * 2)
return doubleCoins
def printMoney(doubleCoins):
print("Your coins doubled are:", doubleCoins)
if __name__ == '__main__':
money()
doubleMoney(coins)
printMoney(doubleCoins)
No, that will not work. Think of a function as a machine. You put things in one end (arguments, aka "the stuff in () when defining a new function), and you get something out at the other end. What you get out is a value. It doesn't create a variable with a certain name or anything like that.
So if you want to use the value of doubleMoney(coins), you have to do something with it. In your example, you just call doubleMoney(coins). This will result in a value, but you don't do anything with it. If you want one function to use a value that another function returns, you have to link them up somehow. What you probably are looking for is something like:
coins = money()
doubleCoins = doubleMoney(coins)
printMoney(doubleCoins)
You could also do it all in one line with printMoney(doubleMoney(money())).
They key thing is that just because you did return coins doesn't mean a variable with that name is created when money() returns. Only the value is returned; if you want to make a variable, you have to do that yourself outside the function, like in the example I showed.
I want to return the variable aRoll, and use it as the argument for the next function. In this case, aRoll holds the answer to the question "Let's roll your ability scores. ready? (y/n)" Once the question is answered, it raw input is stored in the variable aRoll and returned.
import random
pAbility = ['Str', 'Dex', 'Con', 'Int', 'Wis', 'Cha']
pScore = []
i = 0
def pQuestion():
aRoll = raw_input("Let's roll your ability scores. ready? (y/n)")
if aRoll not in ('y', 'n'):
print "Please type 'y' or 'n'"
return pQuestion()
else:
return aRoll
def pStats(aRoll):
while aRoll == "y":
while i < 6:
pScore.append(random.randint(7, 18))
i = i + 1
for score, ability in zip(pAbility, pScore):
print str(score) + ":\t\t " + str(ability)
def pReroll():
aRoll = raw_input("Do you wish to reroll? (y/n)")
aRoll = aRoll.lower()
if aRoll not in ('y', 'n'):
print "Please type 'y' or 'n'"
return pReroll()
pQuestion()
pStats()
pReroll()
When putting print aRoll after pQuestion(), at the bottom of the script, it tells me aRoll isn't defined. Am I not returning aRoll correctly?
aRoll as defined is a separate local variable in each function. You either need to declare it as a global (not a good idea), or explicitly pass the return value of one function as an argument to the next. For example,
rv = pQuestion()
rv2 = pStats(rv)
rv3 = pReroll(rv2)
(Note the change in the definition of pReroll this requires.)
A couple of the other answers have it partly right, but you have to put their answers together to get what you want. At the bottom, it should look like this:
aRoll = pQuestion()
pStats(aRoll)
First, you're assigning what pQuestion() returns to aRoll. Next, you're passing that in as a parameter to pStats(). There are a couple things that will happen if you don't do this:
Since you defined a parameter for pstats(), the interpreter will tell you that you're missing a parameter when you try to run this.
Due to the local scope of aRoll, that variable is not defined outside of the function pQuestion().
For more information about variable scope, look here. This page may also prove useful:
http://gettingstartedwithpython.blogspot.com/2012/05/variable-scope.html
pQuestion() returns aRoll but you never assign the return value. pStats() expects you to pass in aRoll but you never do.
You don't return "the variable" but the value of the variable at the point of the return statement. The name of the variable in the function is completely irrelevant. This is a Good Thing: functions are a way to encapsulate pieces of code. Imagine a simple function that adds two numbers:
def add(a, b):
result = a+b
return result
and then the author changes his mind and renames the variable inside the function:
def add(a, b):
sum = a+b
return sum
and finally, he's clever and just does
def add(a, b):
return a+b
As a user of this function, you should not bother about the names inside the function. You use the add function because you expect it to return the sum of the arguments, no matter how the function works internally.
If you want to use the result of a function, you must store it in a variable yourself:
sum_of_2_and_3 = add(2,3)
print(sum_of_2_and_3)
Not to be discouraging, but your code is a long way from working even once we correct the issue with aRoll. You'll probably have to follow up with some other questions.
As for your immediate problem:
aRoll is defined in pQuestion() and only exists for the duration of that function call (it is in scope only within that function).
When you return aRoll in the function the name aRoll is lost and the value of aRoll "pops out" of the function into the calling code. Unfortunately, you're not catching that value so it basically dissolves into the ether, never to be seen again.
In order to catch the value you need to assign it, like this:
answer = pQuestion()
Now, you have a new variable called answer containing the value "popped out" of the function pQuestion() (y or n in this case). Note that you could also write aRoll = pQuestion() and you'd have a variable named aRoll containing the value from pQuestion() but, importantly, it would not be the same variable as the one INSIDE pQuestion() because that one was already lost. While you're learning, it's probably a better idea to use different variable names everywhere so you don't get confused and believe that the same-named variables are actually the same (rather than variables in different scopes that coincidentally share a name)
That's thing one. Next, you have somehow get the value of answer or aRoll or foobar or whatever name you gave to that value into pStats(). You've already told pStats() to expect to receive one value and to name that value aRoll -- but this aRoll, like the first one, is in scope only inside the pStats() function. The problem is, you're not actually supplying the value to pStats(), which you would do like this:
pStats(answer)
or
pStats(aRoll)
or
pStats(foobar)
or whatever name you chose for the variable.
There is another solution to this problem which is to declare the variables as global and not pass them around. I urge you not to pursue this solution as it leads to very bad programming habits and should only be used in rare circumstances after you fully understand the idea of local scope.
For fun/to practice python, I am trying to create a program that displays the contents of a module. Looks like this:
import sys
print "Here are all the functions in the sys module: "
print dir(sys)
function = raw_input("Pick a function to see: ")
cnt = True
while cnt:
if function in dir(sys):
print "You chose:", function
cnt = False
else:
print "Invalid choice, please select again."
cnt = True
print dir("sys." + function)
But every time, no matter what string the variable function is set to, the dir("sys." + function) call always defaults to the same output as dir(string) (or so I think!)
What is happening and is there a way for me to do this properly and get the output I really want (for example, the variable function is set to stdin and I get the output for dir(sys.stdin))?
You want to retrieve the actual object from the module; use the getattr() function for that:
print dir(getattr(sys, function))
dir() does not interpret the contents of the objects you pass to it; a string that happens to contain a value that corresponds to the name of a function in a module is not dereferenced for you.
f = getattr(sys, function) # get function object
help(f) # display help for the function
Note: dir(f) would return the same info for all functions with the same type.
As dir works on objects, you need to get the object somehow from the name.
First option is to use getattr:
print dir(getattr(sys, function))
If you want to be more flexible (and are ready to take security risk), you can use eval:
print dir(eval('sys.' + function))
I'm a casual gamer and hobbyist programmer who knows a bit of Python. I'm trying to make a simple text adventure game engine, so I need to get raw input from the player.
This is Python 3.2.2, so my line is this:
var = input("What do you want to do? ").lower()
And that line works, but rather than typing that whole line I'd like to make it into a function (something like "getinput()"). From what I've read about input() and functions I'm looking for a function that doesn't return anything, but changes another variable's state (here "var") as a "side effect."
I do have a working function "halt()" that takes no arguments:
def halt():
input("(Press Enter to continue...) ")
print("")
Calling "halt()" gives the prompt, waits for Enter, then prints a blank line and moves on, which I intended.
The function I'm trying to get to work looks like this:
def getinput(x):
x = input("What do you want to do? ").lower()
print("")
After defining getinput(x):
var = ""
getinput(var)
print(var)
That snippet does not print the user's input, and I'm confused as to why. What do I need to do to make this work in the intended fashion?
Is what I'm trying to do impossible with a function, or is there just something I don't know about scope? Should I be at codereview?
You are right that the issue is about scope. The x in this line:
x = input("What do you want to do? ").lower()
Does not change the value that is passed to it- it creates a new variable (also called x) in the local scope of the function.
The right way to do this would be:
def getinput():
return input("What do you want to do? ").lower()
x = getinput()
print(x)
NOTE: If you are going to use any version of Python before 3.x, definitely consider using the raw_input() function as the plain input() function only takes input that is SYNTACTICALLY VALID from the user, otherwise a SyntaxError will be raised.
I'm not sure what you're trying to do exactly, but I've moved around what you've written above so that it will work. Here's what I suggest trying:
First the function getinput()...
def getinput():
x = raw_input("What do you want to do? ").lower() #prompts for the value of x
print "" #prints a blank line
return x
Then the second part...
var = getinput()
print(var)
When you pass something to a Python function, it's generally impossible to modify it unless it's mutable. That restricts you to a small subset of Python types such as a list or dictionary.
def getinput(x):
x[0] = input("What do you want to do? ").lower()
print("")
var = [""]
getinput(var)
print(var[0])
You're far better off letting the function return a value. That's the way Python was meant to work.
var is a python string variable which is being passed by value to your getinput function, which means that your getinput function only modifies a local copy of the name "x", not the value pointed to by "x" from your calling scope.
Also in Python strings are immutable and so it is impossible to modify a string's underlying value in-place due to string interning/hash consing - you merely create a new string. You should really be returning your value:
x = getinput()
But if you still want to stick to your existing design, you can pass this string variable by reference by wrapping it in a list or other reference type:
def getinput(li):
li.append(input("What do you want to do? ").lower())
print("")
usage:
x = []
getinput(x)
print x[0]
I have a function defined which includes a return statement but no value is handed back. My code is as follows:
def seed(addy):
# urllib2 stuff is here
seed_result = re.search('<td>Results 1 - \d+ of (\d+)',seed_query) # searches for '<td>Results 1 - x of y', captures 'y'
seed_result = seed_result.group(1) # this is 'y' from above
# there's a call to a different function here which works properly
# other stuff going on here pertaining to addy but seed_result still has my string
# now I want to return the seed_result string...
return seed_result
# ... some code outside of the seed function, then I call seed...
seed(addy)
print "Result is %s" % seed_result
I have tried this with and without defining seed_result outside of the function to "initialize" it but this has no impact on the outcome which is that my print statement at the end yields "Result is " - there's no seed_result. I have also wrapped seed_result in parenthesis in the return statement though I believe how I have it is correct. The parens didn't make a difference.
A set up a very basic, yet similar, function in the Python shell and called it as I do here but that works. Not sure what I'm missing.
Thanks for the feedback and guidance.
You're not using the return value (e.g. assigning it to a variable). Try this:
result = seed(addy)
print "Result is %s" % result
Two ways of solving this:
First, the proper, obvious, and easy way is actually using the returned value:
seedresult = seed(addy)
Or you use a global variable (bad style - avoid at any cost):
seedresult = None
def seed(addy):
global seedresult
...
This is caused by None being assigned to seed_result during the execution of your function.
As Jon Skeet identified, you are doing nothing with the return value of your function. You should also address the issues below, though.
In particular, you are doing nothing with the parameter addy, and searching a global variable seed_query. I imagine the behaviour you are seeing is a result of that.