I have the variable total in a function. Say that I'd like to use that variable in an if statement in another function. I can use the return keyword and return that variable from my first function but how would I use that variable in an if statement that would be outside that function or even in a different function?
You could re-declare the variable with the value from the function. I don't have a lot of information, but I think this is what you mean.
def some_function():
total=10
return total
total=some_function()
print(total)
return the value from your first function, and then a call to that function will evaluate to that value. You can assign the value to a variable, or pass it directly to another function. In either case, the value doesn't need to be assigned to the same variable name in different scopes.
def func_a():
total = 42
return total
def func_b(the_answer):
if the_answer == 42:
print("That's the answer to the ultimate question!")
func_b(func_a())
Related
Let's assume I have two functions
def seq():
#here I wrote a code that evaluates the mean of a value from a csv file
print(x)#assuming the condition in the above code is true it prints x
seq()
and
def lenn():
p=4
d=#I want this variable to be the value that the 1st function produces
x=d/p
lenn()
One produces an integer and the other uses the output of the 1st function and then divides it with an integer to produce its own output. How do I call the function?
I tried calling the function name but when I tried to divide the function name with an integer it keeps saying that I have a None type. I also tried to put the 1st first function inside the 2nd function but I had the same problem.
How can i solve this?
Don't use print but return (print has no return value, so this defaults to None):
def seq():
return int(input())
def lenn():
p=4
d=seq()
x=d/p
return x
print(lenn())
The problem is that seq does not return the inputted value (x). Anyway, I wouldn't place int(input(x)) in its own function. You can try something like
def lenn():
p=4
d=int(input())
x=d/p
return x
I don’t know how to retrieve, store and print the values of parameters passed into a function. I do know that many posts are related to this question, but I couldn't find anything that matches the simple thing I would like to do.
Let’s take a very simple example:
def times(value, power):
return value**power
If I run this function and then write:
x = times(2.72, 3.1)
print(f'Result of calculation is: {x: .6f}')
then the output will be:
Result of calculation is: 22.241476
OK, but this is not what I would like to have; I would like to be able to print the result, the value and the power, and have the following lines as output, preferably using a print as above; something like print(f’some text here: {something}’)…
Desired output:
Result of calculation is: 22.241476
Value passed to function was: 2
Power passed to function was: 3
What is the most effective way to do that?
The question appears to be asking about accessing the function's namespace, not just printing the value of the variables. If the namespace concept is new to you, I recommend reading the Python documentation and Real Python's blog post on Namespace's in Python. Let's look at a few ways to do what you are asking.
Printing the values is straightforward:
def times(value, power):
print(f"Value passed to function was: {value}")
print(f"Power passed to function was: {power}")
print(f'Result of calculation is: {x: .6f}')
If you need to print it out the way you describe in your question, the values should be returned. This can be accomplished by updating your function to:
def times(value, power):
return value, power, value**power
v, p, result = times(2,3)
print(f'Result of calculation is: {result: .6f}')
print(f"Value passed to function was: {v}")
print(f"Power passed to function was: {p}")
However, returning parameters seems a little odd since one would assume you as the developer can capture those values elsewhere in your code. If you want to view the variables and their values for a given namespace, use the corresponding function. For viewing the value and power variables, which live in the function times() local namespace, use locals() which returns a dictionary object that is a copy of the current local namespace.
def times(value, power):
print(locals())
return value**power
>>> times(5, 4)
{'value': 5, 'power': 4}
625
If the variables are defined in the global namespace, (keep in mind global variables should be used with care) you can use globals() to look up the value in the global namespace:
VALUE = 2
POWER = 3
def times(value=VALUE, power=POWER):
return value**power
>>> globals()['VALUE']
2
>>> globals()['POWER']
3
I hope this helps you figure out how to accomplish what you are working on. I recommend taking some time to read about how Python views and manages namespaces. If you want to watch a video, check out this PyCon talk by Raymond Hettinger on object oriented programming 4 different ways.
You will need to first store the parameters in variables in the code that calls the function.
Assuming the function 'times' is defined.
a = 2.72
b = 3.1
x = times(a, b)
print(f'Result of calculation is: {x: .6f}')
print(f'Value passed to function was: {a}')
print(f'Power passed to function was: {b}')
You can always just add more "print" lines.
So the code would look something like this:
def times(value, power):
print(f'Result of calculation is: {x: .6f}')
print(f'Value passed to function was: {value}')
print(f'Power passed to function was: {power}')
and then you can just pass the values into the function like so:
times(2.72, 3.1)
Please try the following code. It uses the concept of closure (google it). Hope it is helpful.
def times():
value = float(input('Enter a value:'))
power = float(input('Enter a power: '))
def raise_to_power():
return value ** power
print(
f'Result of calculation is: {raise_to_power(): .6f}\nValue passed to function was: {value}\nPower passed to function was: {power}')
times()
I need to design a game of snakes and ladders in python and for part of it, I need to be able to roll a dice and get a random value. For this, I have imported random and then written the function below. However, obviously, I then need to be able to use the dice value in other functions of the game. How do I get it so that the value python returns is retained and able to be used in another function.
Below is the function I have written for rolling the dice. However, when I then run this function and then afterwards try print(dice_value), the program tells me that dice_value has not be defined.
Anybody able to help??
import random
def roll_dice():
dice_value = random.randint(1,6)
print("Its a..." + str(dice_value))
return dice_value
The variable dice_value exists only inside your function roll_dice(). It is a local variable.
You need to call your function with:
my_variable = roll_dice()
Now the result of your function is stored in the variable my_variable, and you can print it.
You have to save the return value somewhere and then use it or pass it to another function.
For example:
>>> import random
>>> def roll_dice():
... dice_value = random.randint(1,6)
... print("[in roll_dice] Its a..." + str(dice_value))
... return dice_value
...
>>> obtained_dice = roll_dice()
[in roll_dice] Its a...1
>>> print("[outside roll_dice] Its a..." + str(obtained_dice))
[outside roll_dice] Its a...1
variable dice_value is a local variable inside the function space so you have to return and save it in another variable to continue using it
You can store the return value of your function roll_dice() in a variable that will in return store the value of the return variable (dice_value).
random_dice_value = roll_dice()
Note: You need to call the function after you have implemented it since Python is an interpreter language. It will execute the file line by line.
The problem is that you're trying to call the variable dice_value outside of its scope. If you still go on with your one liner print statement, you can do so by calling the function (that's returning the dice_value variable) as in:
print(roll_dice())
I came across this problem of not being able reference golbal variables from inside of a function. It always throws an error saying "local variable 'variable_name ' referenced before assignment".
I wrote a simple code which will throw the same error in trying to return a array of product of two numbers.
table=[]
counter = 0
def multiplier(num):
if counter >9:
print (table)
else:
table.append(num*counter)
counter +=1
multiplier(num)
multiplier (5)
What am I doing wrong here? My original code requires the function to be called again and again for that I want to use a counter to keep track of how many times it is being called. This means I cannot initialize the counter inside of the function because once the function is called and because the counter is initialized inside the function, it will be reset.
Use global keyword at the first line in your function block.
Like:
def multiplier(num):
global counter
...
You have to declare
global counter
in your function to access the global variable instead of creating a local variable of the same name. The nicer solution would be to define a class, though.
Make counter a parameter of the function with a default value of zero. When you recurse, add one to the count.
table=[]
def multiplier(num, counter = 0):
if counter >9:
print (table)
else:
table.append(num*counter)
multiplier(num, counter+1)
multiplier(5)
Here is your function refactored to return a value instead of printing it.
table=[]
def multiplier(num, counter = 0):
if counter >9:
return table
else:
table.append(num*counter)
return multiplier(num, counter+1)
print(multiplier(5))
You can use global keyword to use the global variable. Following points to keep in mind:
Use global keyword only when you are changing the global variable value.
You can use global variable if only reading just by using the variable name (global variable definition not required here).
Example:
var = 10
def change_var():
global var
var = 2
return var
def read_var():
print "Variable is:",var
Hope this helps.
I have a function:
def create_discs(noDiscs):
which when called creates a specified number of discs, so for example:
create_discs(5)
will create 5 discs.
I then want to use the integer inputted into the create_discs function in a separate function:
def hanoi(disc_int):
In other words I would like disc_int to equal 5 (or whatever number is inputted)
Can anyone help me?
If you want two functions to share state like this, they should be defined as methods of a class.
class Hanoi(object):
def __init__(self, num_discs):
self.num_discs = num_discs
def create_discs(self):
# use value of self.num_discs
def hanoi(self):
# use value of self.num_discs
h = Hanoi(5)
h.create_discs()
h.hanoi()
If you're passing 5 to create_discs, can you do:
num = 5
create_discs(num)
hanoi(num)
You could make a closure:
def create_discs(num):
# create some discs
def hanoi_closure():
# now num is available within this function
# do hanoi stuff
return
return hanoi_closure
hanoi = create_discs(5)
hanoi()
In this case, create_discs defined your hanoi function within itself so that num was within its scope (automatically, no need to store anything in a global or a class!) and it returned the inner function so you could call it later.
If create_discs was already supposed to return something, then you could just return a tuple with what it was returning plus the inner function:
def create_discs(num):
# ...
return what_it_normally_returns, hanoi_closure
create_discs_result, hanoi = create_discs(5)
hanoi()