How can I check if the current string and previous string in Python code? - python

In this code I want to compare the previous message with the current message. So I created a variable to save the previous message. I wanted to create it as a static variable then manipulate it inside the code. but the outside the x function if I declare the variable it shows an error.
flag = 1
previousMessage = "abc"
def x():
do_something
currentMessage = m #got a string from code
if(currentMessage==previousMessage):
#shows error in flag and previousMessgae
#says create parameter of previousMessage and flag
flag=0
return
else:
do_something
previousNews=currentNews
flag=1
return
def call():
while True:
if(flag==1)
x()
time.sleep(60)
elsif(flag==0)
time.sleep(60) **strong text**
call()

Not sure if this is what you need. Try adding global before flag and previousMessage to make that variable a global variable.

Related

Using return value inside another function

I have these two functions:
def check_channel_number(self):
print "***************Channel Checker *********************"
print ''
user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);
channel = ("channelNr= '%d'") % (user_channel_number)
print channel
# channel_search = channel + str(user_channel_number)
datafile = file('output.txt')
found = False
for line in datafile:
if channel in line:
found = True
print 'The channel number you entered is correct and will be deleted'
return user_channel_number
print 'The channel number you entered is not on the planner'
return False
and
def delete_events(self):
if user_channel_number == True:
return 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
When I run my script, it says that user_channel_number is not defined globally. How can I use user_channel_number inside the delete_events function?
When you define a variable inside of a function, it is a local variable, meaning that it can only be accessed within that function.
Within a Class
It looks like you're inside a class, so you can make the variable accessible to all methods in the class by defining it like this:
def check_channel_number(self):
self.user_channel_number = ...
And then in your second function, you can use it like the following:
def delete_events(self):
if self.user_channel_number:
Outside of a class
If you aren't using methods inside of a class, you can instead use the global builtin.
For example,
def check_channel_number():
global user_channel_number
user_channel_number = ...
def delete_events():
if user_channel_number:
...
Using a value returned from a function
Instead in your first function, check_channel_number(), you can have it return user_channel_number. You can then call that function inside of delete_events(), like the following:
def check_channel_number():
user_channel_number = ...
return user_channel_number
def delete_events():
if check_channel_number():
...
Functions can not share their local variables. You can return the value from the first and pass it to the second:
def check_channel_number(self):
...
return user_channel_number
def delete_events(self):
user_channel_number = self.check_channel_number()
...
Or save value on the object:
def check_channel_number(self):
...
self.user_channel_number = user_channel_number
...
def delete_events(self):
if self.user_channel_number:
....
So I think when you call the check_channel_number function, user_channel_number is defined in there, so when you call delete_events, it has gone out of scope, maybe something like this would help?
user_channel_number = check_channel_number()
delete_events()
I'd probably have the user_channel_number as an input to the delete function too, so it would turn into this: (where ucn is the user_channel_number)
def delete_events(self, ucn):
if ucn == True:
print 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
I have also changed `return 'The program number is correct and will be deleted'' to a print statement as I have a feeling the return would end the function before the other lines of code would be run
So the code would probably end up being something like:
user_channel_number = check_channel_number()
delete_events(user_channel_number)
EDIT:
just noticed it looks like your functions are part of a class,
in that case, you could do:
self.ucn = self.check_channel_number()
self.delete_events(self.ucn)
(or if you dont want to pass the user_channel_number into the function you could change if user_channel_number: to if self. user_channel_number:

How do I transfer varibles through functions in Python

I am trying to read from keyboard a number and validate it
This is what I have but it doesn't work.
No error but it doesn't remember the number I introduced
def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
I think this is what you are trying to achieve.
def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
global a
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
You need to use global expression in order to overwrite the global variable without a need to create return inside the function and typing a = read().
But I would highly recommend u to use the return and re-assigned the value of 'a', as someone stated below.
a is a local variable to the two functions and isn't visible to the rest of your code as is. The best way to fix your code is by returning a from your read() function. Also, the spacing is off in your IsInteger() function.
def IsInteger(b):
try:
b=int(b)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while not IsInteger(a):
a=input("Give a number: ")
return a
c = read()
print(c)
It appears as though you are not returning the result of the read() function.
The last line of your read function should be "return a"
And then when you call the read function you would say "a = read()"

How to call an arraylist from a function to another function in python?

Say for example I got the code:
def getRoute(getRouteFile):
getRoutePath = []
routeFile = open(getRouteFile, "r")
for routes in routeFile:
getRoutePath.append(map(ord, routes.split('>')))
return getRoutePath
If I do a function such as which would try and call the items in the getRoutePath array from a function called:
def routeCalculation(getRoute,nodeTable, currentNode):
How do I call it? I tried doing these:
def routeCalculation(getRoute,nodeTable, currentNode):
route = getRoutePath
def routeCalculation(getRoute,nodeTable, currentNode):
route = getRoute[getRouthPath]
And none seem to work. Can anyone help me?
Whenever you declare a variable in a function, when you exit the function, the variable is destroyed. Example:
a = ""
def function():
a = "hello"
b = "hello"
print(a) #prints "hello" because a was declared outside of the function
print(b) #does not print anything
This is called "scope", and if you have a problem understanding it, you should search up a tutorial about it. In order to fix your problem move the code getRoutePath = [] outside of your functions.

How can I use external variables in Python like 'extern int x;' in C?

How can I use external variables in Python, like extern int x; in C?
For example,
main1.py:
from myfunc import print_a
a = 10
print a
print_a()
myfunc.py:
def print_a():
global a
print a
Simply re-assign the variable in the module:
import myfunc
from myfunc import print_a
a = 10
print a
myfunc.a = a
print_a()
Otherwise it is not possible.
Rememeber that python treats modules in a way that is quite different from C.
The import in python does not "copy the contents" of the file in that place,
but it executes the code in the given file and creates a module object.
The global variable of the module are the module object attributes, which can be modified as I've shown. There is no such notion as "global variable" except for built-ins.
I'd suggest to refactor your code in such a way that you don't have to modify this global variable at all, moving the code that uses myfunc.a from main1 to myfunc.
The fact that you need such global variable is already a code smell that there's something wrong with your code and you should try to fix it.
Actually there is a way to affect the "global scope" but it is so hackish that I don't even want to mention it. Trust me: you don't want to use it. If people see your code using such a hack you may be in physical danger.
Unlike C, variables declared at global scope are still limited in scope to the module they are created in, so you need to qualify the name a with the module it lives in.
The global keyword is used when you are going to modify a global variable by reassigning, you do not need it when you are just referencing a global variable.
If you are trying to access a variable of another file, you must import that module, and because of the way your files are structured you have a couple of ways to resolve issues:
Option 1) Move the referencing of myfunc.print_a inside of a function and import main1 inside myfunc to see a
main1.py
import myfunc
a = 10
def main():
print a
myfunc.print_a()
if __name__ == '__main__':
main()
myfunc.py
import main1
def print_a():
print main1.a
Option 2) recommended Move the variable(s) into another module and have both myfunc and main1 import it.
vals.py
a = 20
main1.py
import vals
from myfunc import print_a
vals.a = 10
print vals.a
print_a()
myfunc.py
import vals
def print_a():
print vals.a
This is a workaround to this problem by using a common external file. In this example I am storing an index variable to flag in each application whether a file is being accessed. The variable indxOpen in ext1.py and indxO in ext2.py are being updated and stored in a common external text file "externalVars.txt"
lead application ext1.py
# lead application ext1.py
#this alternately flips the value of indxOpen on prime number intervals
import time
def update(d,v1):
f=open(d+'externalVars.txt','r+')
f.write(str( v1))
f.truncate()
f.close()
# ensure variable is initialised and made available to external apps
indxOpen = False
var_dir = "<your external var directory>/"
try:
f =open(var_dir+'externalVars.txt','r')
except:
f= open(var_dir+'externalVars.txt','w')
f.close()
# this alternately flips the value of indxOpen on prime number intervals
update(var_dir,indxOpen)
i = 0
while True:
while indxOpen:
i += 1
if (i % 13) ==0:
indxOpen = indxOpen ^ True
update(var_dir,indxOpen)
f=open(var_dir+'externalVars.txt','r+')
t=f.readline()
print "app1",t," ",i
if t=='False':
print "app1 updated"
update(var_dir,indxOpen)
indxOpen = False
else:
time.sleep(1.4)
while not indxOpen:
f=open(var_dir+"externalVars.txt","r+")
t=f.readline()
print "app1",t
if t=='True':
indxOpen = True
else:
time.sleep(1)
ext2.py following application
# ext2.py this alternately flips the value of indxO on prime number intervals but it is initialised by the lead application
# in this case ext1.py
# python 2.7.12
import time
def update(d,v1):
f=open(d+'externalVars.txt','r+')
f.write(str( v1))
f.truncate()
f.close()
var_dir = "<your external var directory>/"
# intialise external variable
f=open(var_dir+'externalVars.txt','r+')
t=f.readline()
if t=='True':
indxO= True
if t=='False':
indxO= False
i=0
while True:
while indxO:
f=open(var_dir+"externalVars.txt","r+")
t=f.readline()
print "app2",t
if t=='False':
indxO = False
update(var_dir,indxO)
else:
time.sleep(1.5)
while not indxO:
i += 1
if (i % 17) ==0:
indxO = indxO ^ True
update(var_dir,indxO)
f=open(var_dir+"externalVars.txt","r+")
t=f.readline()
print "app2",t," ",i
if t=='True':
indxO = True
print "apt2 updated"
update(var_dir,indxO)
else:
time.sleep(1.3)

"Son" function cant see "Father" function locals

Hi im doing a udacity course on testing and I dont understand why im getting this problem with globals.
The thing is there is some implementation of queue I want to test. To do so I wrapp the methods with the post conditions [empty, full,enqueue,dequeue] using asserts and then proceed to do a random test on the structure with the wrapped functions to automate the testing.
For the assertions I need to keep track of the max items (size) of the queue and the actual items (elts) so i defined them as locals in function test().
Inside test() i define the wrapers and in the wrappers i use size and elts.
The thing i dont understand is if i make elts global inside the wrapper definition, then i got a NameError global name 'elts' is not defined at the wrapper But if i dont declare it as global in the wrapper then i get the UnboundLocalError of accessing elts before assigning a value to it.
I dont understand why a "Son" function declared in the body of a "Father" function cant see a local variable of the father and use it.
Here is the code
from queue_test import *
import random
import sys
def test():
# Globals
iters=100
max_int=sys.maxint
min_int=1
elts=0
size=0
#Queue wrappers
# Wrapp the queue methods to include the assertions for automated testing
def run_empty():
temp=q.empty()
if elts==0:
assert temp==True
else:
assert temp==False
return temp
def run_full():
temp=q.full()
if elts==size:
assert temp==True
else:
assert temp==False
return temp
def run_enqueue(val):
temp=q.enqueue(val)
if isinstance(val,int) and elts<size:
elts+=1
assert temp==True
else:
assert temp==False
return temp
def run_dequeue():
temp=q.dequeue()
if elts>0:
elts-=1
assert temp!=None and isinstance(temp,int)
else:
assert temp==None
return temp
# Random testing stuff
def get_int(): # Return a random valid integer
return random.randint(min_int,max_int)
def get_command(): #Return a random valid command (string)
return random.choice(["empty","full","enqueue","dequeue"])
def run_random_command(): # Execute a random command
c=get_command()
if c=="empty":
run_empty()
elif c=="full":
run_full()
elif c=="enqueue":
run_enqueue(get_int())
elif c=="dequeue":
run_dequeue()
else:
raise Exception("Error run command invalid command")
def test_this(ncommands=100): # Randomly test a queue with ncommands commands
run_empty()
testi=get_int()
run_enqueue(testi)
testi2=run_dequeue()
assert testi == testi2
for c in range(ncommands):
run_random_command()
#Test Code: Do it random tests each one with a diferent random queue
for it in range(iters):
size=get_int()
elts=0
q=Queue(size)
test_this()
If you assign to a variable within a function, Python automatically makes it local. You'll need to explicitly mark them as global within the child functions. (In Python 3, you can use nonlocal for that.)
However, I can't help thinking that you should really be using a class here.

Categories