how to declare variables in python in functions - python

I am newbie to python
i wrote a small function which is resulting in error
can you please let me know what is the mistake i am doing
def cost(input):
output=input*2
next=output*3
return output,next
print output
print next
Namerror name 'output' is not defined

Output is not defined since it is local to the function and the function hasn't even run. To get it globally, above print output you would put:
output, next = cost(1.12)

You need to call the function first. Both output and next are defined within the function and can not be accessed directly from outside.

print output
There is no variable called output for python to display. The output variable you have is inside the function, which is not accessible outside.

the problem is that the scope of the output and next variable is within the function, they cannot be referenced outside the function. If you want to print the result, just call the cost function in the print statement:
print cost(100)

Related

understanding python inner function .how does this works?

def prefix_factory(prefix):
def prefix_printer(text):
print(f"{prefix}: {text}")
return prefix_printer
Now lets execute the below line.
# First time we are executing this
debug = prefix_factory('DEBUG')
# Second time we are executing as
debug('Hello world')
First time we are executing this
1st execution or assignment of function to the variable debug is assigned the value "DEBUG". My understanding is this is how it has to be executed.
ideally inner function prefix_printer(text) - gets defined inside prefix_factory()
'return prefix_printer' should get an error, stating that text is not available or text is missing.
Second time we are executing as
debug('hello world ') - 2nd execution of the function reference.
The question for the second execution is, I am assuming 'hello world' should be considered as a value for the prefix. and text should be blank as we don't call prefix_printer in the return statement with any value. Hence it has to be '' empty string. I am coming from c, C++ background.
My question is, it's the same piece of code 1st-time prefix is assigned,
but during the 2nd execution debug('Hello world') it behaves differently. How is it possible, please clarify in detail how this works?
When debug = prefix_factory('DEBUG') is executed, variable debug is assigned the return value from calling function prefix_factory('DEBUG'). It is not assigned the value "DEBUG" as you said. And what is this return value?
Function prefix_factory returns prefix_printer, which is a function nested within prefix_factory. Moreover, prefix_printer references a variable, prefix, which is defined in the outer, enclosing function. When prefix_factory returns a nested function, prefix_printer, that references a variable defined in the nesting function, that returned function is known as a closure. Even though we have now returned from the call to printing_factory, the closure function prefix_printer, which has now been assigned to variable debug, still has a reference to the value of variable prefix as it existed at the time prefix_factory was called.
Subsequently, when you execute debug('Hello World'), because debug evaluates to our prefix_printer closure , this is equivalent to calling function prefix_printer('Hello World') with variable prefix initialized to 'DEBUG'.

Passing a variable into a parameter defined by another function python

I am unsure of why the variable totalspeed variable is not being passed correctly to the function startgame as the startgame function is called after the gettotalspeed function.
Exerpt from call function:
gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)
Functions
def gettotalspeed(party_ids):
#Get selected party members IDS
print(party_ids)
#Obtain Speeds
ids_string = ','.join(str(id) for id in party_ids)
mycursor.execute("SELECT startspeed FROM characters WHERE CharID IN ({0})".format(ids_string))
myspeeds=mycursor.fetchall()
totalspeed=0
for speedval in myspeeds:
totalspeed=totalspeed + speedval[0]
print("totalspeed is: ",totalspeed)
return totalspeed
def startgame(party_ids,totalspeed,distance,NoOfEvents):
#Check if game end
print(totalspeed)
while distance!=0:
#Travel...
distance=distance-totalspeed
NoOfEvents=NoOfEvents+1
#Generate Random Encounter
genevent(NoOfEvents)
return NoOfEvents
Error Produced:
NameError: name 'totalspeed' is not defined
Outputs (ignoring party_ids)
totalspeed is: 15
I suspect that your problem is self-evident from the main program:
gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)
Of the variables you pass to your functions, only NoOfEvents is defined. party_ids, totalspeed, and distance have no definitions.
Work through a tutorial on Python scoping rules. Most of all, note that a function defines a scoping block. Variables inside the function are reclaimed when you leave the function; their names do not apply outside of that block. Your posted program has three independent totalspeed variables.
You forgot to make totalspeed a global variable like global totalspeed in your gettotalspeed() function. You might also be confused about what return does. If you wanted to do it the "proper" way, you could do totalspeed = gettotalspeed(party_ids). Hope this helps!

Why does a function execute when put inside a variable (and how to stop it)

While writing a program in python i noticed that if one puts a function like print("hello world") inside a variable it will not be stored like expected, instead it will run. Also when i go and call the variable later in the program it will do nothing. can anyone tell me why this is and how to fix it?
If mean something like:
variable = print("hello world")`
then calling the function is the expected result. This syntax means to call the print function and assign the returned value to the variable. It's analogous to:
variable = input("Enter a name")
You're surely not surprised that this calls the input() function and assigns the string that the user entered to the variable.
If you want to store a function, you can use a lambda:
variable = lambda: print("hello world")
Then you can later do:
variable()
and it will print the message

Python use input to select local variable inside another function

All, I have this request but first I will explain what I'm trying to achieve. I coded a python script with many global variables but also many methods defined inside different modules (.py files).
The script sometimes moves to a method and inside this method I call another method defined in another module. The script is quite complex.
Most of my code is inside Try/Except so that every time an exception is triggered my code runs a method called "check_issue()" in which I print to console the traceback and then I ask myself if there's any variable's value I want to double check. Now, I read many stackoverflow useful pages in which users show how to use/select globals(), locals() and eval() to see current global variables and local variables.
What I would specifically need though is the ability to input inside method "check_issue()" the name of a variable that may be defined not as global and not inside the method check_issue() either.
Using classes is not a solution since I would need to change hundreds of lines of code.
These are the links I already read:
Viewing all defined variables
Calling variable defined inside one function from another function
How to get value of variable entered from user input?
This is a sample code that doesn't work:
a = 4
b = "apple"
def func_a():
c = "orange"
...
check_issue()
def check_issue():
print("Something went wrong")
var_to_review = input("Input name of var you want to review")
# I need to be able to enter "c" and print the its value "orange"
print(func_a.locals()[var_to_review ]) # this doesn't work
Could somebody suggest how to fix it?
Many thanks
When you call locals() inside check_issue(), you can only access to the locals of this function, which would be : ['var_to_review'].
You can add a parameter to the check_issue function and pass locals whenever you call it.
a = 4
b = "apple"
def func_a():
c = "orange"
check_issue(locals())
def check_issue(local_vars):
print("Something went wrong")
var_to_review = input("Input name of var you want to review")
print(local_vars[var_to_review])

Changing the definition of an existing function

I want to print to a file using print I import from __future___. I have the following as an import:
from __future__ import print_function
From now on, I can print using:
print("stuff", file=my_handle)
However, I have many calls to print in a function, so I would want to be able to use a function where the keyword argument is bound to my_handle. So, I use partial application:
printfile = partial(print, file=my_handle)
printfile("stuff")
printfile("more stuff")
which is what I intended. However, is there any way I can change to definition of print itself by partially applying the keyword argument? What I have tried was:
print = partial(print, file=my_handle)
however I got an error saying:
UnboundLocalError: local variable 'print' referenced before assignment
Is there any way to use print without mentioning my file every time?
print = partial(print, file=my_handle)
This line causes the UnboundLocalError on the second print, the one used as argument to partial(). This is because the name print is found to be a local variable in this particular function --- because you assign to it, in this case in the same line, more generally in the same function. You can't use the same variable name in one function to refer sometimes to a global and sometimes to a local.
To fix it you need to use a different name:
fprint = partial(print, file=my_handle).

Categories

Resources