python run code that is in a function once - python

I am trying to make a variable in Python go up by one continuously, but inside a function. What I am using is something like this:
def func1():
def set1():
x=5
y=10
##lots of code
x+=1
y+=1
def func2():
while True:
func1()
set1()
func2()
I'm wondering if there is a much better way to do this?

Probably the best way to do this is to put the definition of x and y into function 2, and have them be inputs and outputs of function 1.
def func1(x, y):
##lots of code
x+=1
y+=1
return x, y
def func2():
x = 5
y = 10
while True:
x, y = func1(x, y)
Other alternatives include defining x and y globally and using global x, global y or using mutable default arguments to make the function retain state, but generally better to not resort to these options if you don't have to.

A bit of code review and recommendations:
def func1():
def set1():
x=5
y=10
##lots of code
x+=1
y+=1
def func2():
while True:
func1()
set1() # This won't work because set1 is in the local scope of func1
# and hidden from the global scope
func2()
Looks like you want the function to count each time it is called. May I suggest something like this?:
x=5
y=10
def func1():
global x, y
x+=1
y+=1
print x, y
def func2():
while True:
func1()
func2()
Better than using a global variable, stick them in a mutable object in a nested scope:
Counts = dict(x=5, y=10)
def func1():
Counts['x'] += 1
Counts['y'] += 1
print Counts['x'], Counts['y']
def func2():
while True:
func1()
func2()

x = None
y = None
def set1():
global x, y
x=5
y=10
def func1():
global x, y
x+=1
y+=1
def func2():
while True:
func1()
set1()
func2()

** just saw the edit on going up instead of down - modified code to suit**
It's hard to tell from your question what your actual use case is but I think a Python generator may be the right solution for you.
def generator(x, y):
yield x,y
x += 1
y += 1
Then to use:
if __name__ == "__main__":
my_gen = generator(10,5)
for x,y in my_gen:
print x,y
if x+y > 666:
break
This may be a slightly advanced for someone new to Python. You can read up on generators here: http://anandology.com/python-practice-book/iterators.html

First of all, the set1 function doesn't seem to do much at all, so you could take it away.
If you want to keep count of the number of calls or keep state between calls, the best, more readable way is to keep this inside an object:
class State(object):
def __init__(self):
self._call_count = 0
self.x = 5
def func1(self):
self._call_count += 1
self.x = ... Whatever
def func2():
state = State()
while True:
state.func1()

Related

Is it possible store return value of one function as Global Variable?

I Have function register a patient that will Return Medical record Number , Need store this as Global Variable to so that use the same for Different Functions Eg: Create Vital Sign , Create Lab Order etc.
aqTestCase.Begin(" User able to Register a Unknown patient")
Log.AppendFolder("Unknown Registeration Logs")
ERPage=Aliases.MedBrowser.pageER
ReusableFunctions.ClickonObject(ERPage.RegisterUnknownPatientIcon)
ReusableFunctions.ClickonObject(ERPage.UnknownRegMaleLabel)
ReusableFunctions.setTextValue(ERPage.txtAge, "20")
ReusableFunctions.ClickonObject(ERPage.UnknownRegregistrBtn)
ReusableFunctions.ClickonButton(ERPage.AssignBuutonclose)
AppReusableFunctions.getToastMsgs(ERPage)
labelER = Aliases.VidaPlusBrowser.pageER.FindElement("//span[.='ER']")
ReusableFunctions.ClickonObject(labelER)
mrn = ERPage.FindElement("//div[10]/div[5]/app-er-patient-grid-mrn/span").contentText
aqUtils.Delay(2000)
ReusableFunctions.ClickonObject(ERPage.ERArrvialTime)
Log.Message(" Unknown Patient Registred MRN is : " +mrn)
return mrn
You can set the variable as a global variable and return it.
def foo():
global X
X = 1
return X
In your case, creating a class may work better.
class Foo:
def __init__(self, x):
self.x = x
def bar(self):
return self.x
f = Foo(1)
f.bar()
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Referencing variable from a def block in another def block

Basically I have this section of code that goes like so:
def start():
def blockA():
y = 3
x = 4
print("hello")
blockA()
def blockB():
if x !=y:
print("not the same")
blockB()
start()
However, this gives me an error saying that x and y are not defined. How would I go about referencing the x and y variables in blockB?
You need to return the variables in blockA function and call that function in your second function.
def blockA():
y = 3
x = 4
print("hello")
return x,y
def blockB():
x,y=blockA()
if x !=y:
print("not the same")
This should work for you.

Using variables from another function in a function

I have tried to search this but I don't quite understand. I am coming across this error so I formed a quick easy example.
def test():
global a
a = 0
a+=1
def test2():
a+=1
print (a)
inp = input('a?')
if inp == 'a':
test()
test2()
When I input a. I expected the code to output 2. However, I get this error UnboundLocalError: local variable 'a' referenced before assignment. When I searched around about this, I found that you need to use global, but I already am using it.
So I don't understand. Can someone briefly explain what I'm doing wrong?
Thanks.
A global declaration only applies within that function. So the declaration in test() means that uses of the variable a in that function will refer to the global variable. It doesn't have any effect on other functions, so if test2 also wants to access the global variable, you need the same declaration there as well.
def test2():
global a
a += 1
print(a)
1) You can return the modified value like:
def test():
a = 0
a+=1
return a
def test2(a):
a+=1
print (a)
inp = input('a?')
if inp == 'a':
a = test()
test2(a)
2) Or you can use a class:
class TestClass:
a = 0
def test(self):
self.a = 0
self.a+=1
def test2(self):
self.a+=1
print (self.a)
Usage of option 2:
>>> example = TestClass()
>>> example.test()
>>> example.test2()
2

Abstracting if statement and return by a function

I have a function like this:
def test():
x = "3" # In actual code, this is computed
if x is None:
return None
y = "3"
if y is None:
return None
z = "hello"
if z is None:
return None
Is there a way of making the if statement go away and abstract it with some function. I'm expecting something like this:
def test():
x = "3"
check_None(x)
y = "3"
check_None(y)
z = "hello"
check_None(z)
Ideally, check_None should alter the control flow if the parameter passed to it is None. Is this possible?
Note: Working on Python 2.7.
You can easily code it in some thing like this.
def test():
#compute x, y, z
if None in [x, y, z]:
return None
# proceed with rest of code
An even better way would be to use an generator to generate value x, y, z so that you only does computation for one value at a time.
def compute_values():
yield compute_x()
yield compute_y()
yield compute_z()
def test():
for value in compute_values():
if value is None:
return None
I am not really sure if we should do it like this, but one of the hacks could be like this, Also create your own exception class and only catch that particular exception so that no other exceptions are accidentally caught by the except and return None.
class MyException(Exception):
pass
def check_none(x):
if x is None:
raise MyException
def test():
try:
z=None
check_none(z)
except MyException, e:
return None
return_value = test()

Python function definition global parameter

Can someone explain why the gloabl variable x & y are not recognized in printfunc,
code.py
global x
global y
def test(val_x=None,val_y=None)
x = val_x
y = val_y
printfunc()
def printfunc():
print('x',x)
print('y',y)
if __name__ = '__main__':
test(val_x=1,val_y=2)
place the global inside test().
global is used inside functions so that we can change global variables or create variables that are added to the global namespace. :
def test(val_x=None,val_y=None):
global x
global y
x = val_x
y = val_y
printfunc()
The global keyword is used inside code block to specify, that declared variables are global, not local. So move global inside your functions
def test(val_x=None,val_y=None): #you also forgot ':' here
global x, y
x = val_x
y = val_y
printfunc()
def printfunc():
global x, y
print('x',x)
print('y',y)

Categories

Resources