how to delete value from a string variable - python

I have designed a function which would take input name from RFID card and prints it. This variable Username is declared global so that I can use it in other functions. Now I want to use this variable in another function which will check if there is value stored in Username or not and performs the corresponding function. At the end of this function this variable should be deleted. so that it takes a new value next time and not use the previous value stored. Therefore I want to delete value stored in my variable so that it can take a new value every time. How can I do this?
def RFID_reading(a,b):
global reader, Username
while True:
Starttime = time.time()
try:
id, Username = reader.read()
print(Username)
def store_unknown(picture_list):
if Username != "":
j=0
while j < len(picture_list):
cv2.imwrite(f'{y}/{picture_list[j][2]}.png', picture_list[j] [0])
j += 1
Username == None
I have tried writing Username == None but it did not work.

Please try using global Username before the last line Username == None. This is to denote that you are aware and going to update the global variable's value.

Related

Python: How to change the value of a function inside a class from an outside function

Hi I am showing a subsection of my code. I created a function(propertyValue) inside an object class(CashOnCashROI). I then created a function (calculator) outside the class. I instantiated the class as "rental" and then tried to use rental.propertyValue() to call the propertyValue function outside the class.
What I am trying to do is change the value for "self.globValue = int(value)" from the calculator() function but I keep getting: TypeError: propertyValue() takes 1 positional argument but 2 were given. I was hoping someone could help me explain what is going on, how to fix it, and if there is a better way to do this? I am just starting to learn about classes so I greatly appreciate it.
Here is the code, it should give the same TypeError.
class CashOnCashROI:
def propertyValue(self):
value = input('How much will you pay for the property? \n')
while value.isdigit() == False:
value = input('Sorry, we need a number? What is the proposed property value? \n')
print(f"Your current purchase value for the property is: {value}")
self.globValue = int(value)
def calculator():
rental = CashOnCashROI()
while True:
rental.propertyValue()
choice = input('<Other parameters asked here>, "Value" to change the property value.\n')
if choice.lower() == "value":
xvalue = input('What would the new property value be? \n')
rental.propertyValue(xvalue) ### How do I change the value here???
Modify the propertyValue function:
Setting a new argument (value) allows to pass a value from outside the function as an argument and skip the input function. If no value is provided, use the old implementation:
class CashOnCashROI:
def propertyValue(self, value=None):
if not value:
value = input('How much will you pay for the property? \n')
while value.isdigit() == False:
value = input('Sorry, we need a number? What is the proposed property value? \n')
print(f"Your current purchase value for the property is: {value}")
self.globValue = int(value)
def calculator():
rental = CashOnCashROI()
while True:
rental.propertyValue()
choice = input('<Other parameters asked here>, "Value" to change the property value.\n')
if choice.lower() == "value":
xvalue = input('What would the new property value be? \n')
rental.propertyValue(xvalue) ### How do I change the value here???

How to use variable defined in for-loop outside of it?

How can I use this u_name and u_pass outside this for loop?
cursr.execute("SELECT rowid ,* FROM usernameandpassword")
user_and_pass = (cursr.fetchall())
for users in user_and_pass:
global u_name
global u_pass
u_name = (users[1])
u_pass = (users[2])
if uni_username.get() == u_name and uni_pass.get() == u_pass:
show_new_user_window()
you could create another two lists like name_list and pass_list, and initialize them before for-loop and inside for loop use name_list.append(user[1]), pass_list.append(user[2]), after for-loop use index to get each name and pass
# intialize name_list and pass_list lists
name_list = []
pass_list = []
for users in user_and_pass:
# save them into our lists
name_list.append(users[1])
pass_list.append(users[2])
outside this for loop, name_list[0] will refer to the first value, name_list[1] will refer to second value and so on.

Python - UnboundLocalError: local variable "ID" referenced before assignment

Id, conf = recognizer.predict(gray[y:y+h,x:x+w]
def hour(cn):
for z in range(9,17):
if now.hour == z:
worksheet(cn, str(z)+":00")
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
for m in range(2,100):
identify(m)
The above code is being used for facial recognition, I copied what I felt was necessary, it is not the entire code.
I'm trying create a function which I want to call back in a for loop
What am I doing wrong? I've been looking t this for 6 hours now, and anything I try doesn't seem to work.
I get a message back saying "UnboundLocalError: local variable 'Id' referenced before assignment"
It's impossible because I'm assigning with:
a = wks3.acell('A'+str(number)).value
So it grabs the ID number from the google spread sheet and checks if it is equaled to that, can someone tell me where I'm going wrong here?
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
#because you did, Id = ?
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
Because you did, variable Id isn't passed as any parameter or global/local variable or as an argument to existing class.
If Id was parameter:
def identify(number,Id):
If Id was global variable:
def identify(number):
global Id
If Id was local variable:
def identify(number):
id = None # or some other data type
And if Id was argument from some class:
some_class.Id
In short you referenced Id before it was initialised. This is rookie mistake and there is some stuff where you can actually init a variable in if elif else statement but you need to trow a none of above logic of the rule.
if True: Id = 2; elif False: Id = 3; else: Id =0 #this is pseudocode, don't paste it in.
Also have in mind that next variable is also Unbound conf
EDIT:
Often to avoid this problem we write code like this:
def somefunction(parm1,parm2... ):
# global variables : description for variable stack is optional
global var1,var2 # if needed
#local variables
var3,var4 = None;
var5 = 'something else'
#in body functions : functions inside functions or just general program functions
def a(... ): return ...
#body : actually what function/program does.
# returning , finishing statement.

Initialize function variable once & change variable value when function is called

Language: Python
I want the value of a variable to be initialized to zero at the start of the execution. This variable is used in a function & its value may also get changed within the function. But I do not want the value of this variable to reset to zero whenever a function call is made. Instead, its value should be equal to the updated value from its previous function call.
Example:
get_current() is constantly returning a different value when it is called.
ctemp is initially zero.
In the first function call get_current_difference() will return cdiff & then update the value of ctemp such that ctemp = current.
In the second function call, the value of ctemp should not be zero. Instead, it should be equal to the updated value from the first function call.
import serial
arduino = serial.Serial('/dev/ttyACM1',9600)
ctemp = 0
def get_current():
line = arduino.readline()
string = line.replace('\r\n','')
return string
def get_current_difference():
global ctemp
current = get_current()
cdiff = float(current) - ctemp
return cdiff
ctemp = current
while 1:
current = get_current_difference()
print(current)
You return before setting value of ctemp
return cdiff
ctemp = current
must become
ctemp = current
return cdiff
You are describing mutable state and a function to modify it, which is what classes are for.
class Temperature:
def __init__(self, arduino):
self.ctemp = 0
self.arduino = arduino
def current(self):
line = self.arduino.readline()
return line.replace('\r\n', '')
def difference(self):
current = self.current()
cdiff = float(current) - self.ctemp
self.ctemp = current
return cdiff
t = Tempurature(serial.Serial('/dev/ttyACM1', 9600)
while True:
print(t.difference())
Using a class scales if, for example, you have multiple temperature monitors to work with.

Setting a dictionarys items to a variable

I was wondering if this would be possible, to save a dictionary item to a variable. So simply this is what I am doing. I am saving this item to a dictionary:
accounts{}
def accountcreator():
newusername = raw_input()
newpassword = raw_input()
UUID = 0
UUID += 1
accounts[newusername] = {newpassword:UUID}
Now basically I will be looping through the newusernames in a separate function:
def accounts():
username = raw_input()
for usernames in accounts:
if usernames == username:
#Not sure what to do from here on out
else:
accounts()
This is where I get confused. So if the username input equals a newusername in the accounts dictionary it will contiune on. I want it to save that newusernames password and UUID (the {newpassword:UUID} part) to a variable. So basically if the newusername equals the username input it will save the rest of thats informations (the {newpassword:UUID}) to a variable. So in the end the variable lets say accountinfo = {newpassword:UUID}. Thank you, I hope that makes sense.
There are a couple of errors in your code. First, probably a typo:
accounts = {}
Next, when you create the code, you are always resetting UUID to 0, making the increment a little pointless. Initialize UUID outside the function, like you do with accounts:
UUID = 0
def accountcreator():
newusername = raw_input()
newpassword = raw_input()
UUID += 1
accounts[newusername] = {newpassword:UUID}
Third, I'm not sure why you are mapping the password to the UUID. Likely, you want two separate fields in the user dictionary to store both:
accounts[newusername] = { 'password': newpassword, 'UUID': UUID }
Finally, the whole point of using a dictionary to map user names to information is that you don't need to iterate over the entire dictionary; you just index the dictionary with the user name. You do have to take care that you don't try to access a nonexistent key, though.
# Use a different name; accounts is already a dictionary
def get_account():
username = raw_input()
if username in accounts:
return accounts[username]
else:
print("No account for {0}".format(username))

Categories