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.
Related
I have this below set of code where I perform some manipulation based after pulling some data from a source Dataframe called df.
Customer_data = []
for i in range(0, len(df)):
try:
Customer = (re.search(r'(Customer"=>).*?(,)', df[i]).group(0).split('=>')[1].replace('"','').replace(',',''))
except:
Customer = ''
Customer_data.append(Customer)
Customer = pd.DataFrame(Customer_data.append, columns = ['Customer'])
I am trying to have the above code repeated for set of variables wherein I would replace the variable Customer with another variable. How could I generalise the above code such that it could be reused for other variables as well in a loop.
Example variables : Product, ModelName
You can put it inside the function, where you pass the name string of your variable (as seen in DataFrame).
Just change search part to include correct name r'({}"=>).*?(,)'.format(name).
def my_func(df, name):
Customer_data = []
for i in range(0, len(df)):
try:
Customer = (re.search(r'({}"=>).*?(,)'.format(name), df[i]).group(0).split('=>')[1].replace('"','').replace(',',''))
except:
Customer = ''
Customer_data.append(Customer)
Customer = pd.DataFrame(Customer_data.append, columns = ['Customer'])
return Customer
# run function
Product = my_func(df, 'Product')
ModelName= my_func(df, 'ModelName')
You can define the regex as a string, adding there the column name from a variable. Finally passing that regex expression to re.search:
col_name = "Customer"
my_regex = r"('+re.escape(col_name)+'=>).*?(,)"
Customer_data = []
for i in range(0, len(df)):
try:
Customer = (re.search(my_regex, df[i]).group(0).split('=>')[1].replace('"','').replace(',',''))
except:
Customer = ''
Customer_data.append(Customer)
Customer = pd.DataFrame(Customer_data.append, columns = ['Customer'])
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.
this is my code.
# Lista de usuarios
UserList = []
UserDic = {}
UserListQuery = UserProfile.objects.all()
print "PRINTING QUERY " + UserListQuery
for User in range(0,len(UserListQuery)):
UserDic['username'] = UserListQuery[User].user.get_username()
UserDic['titulo'] = UserListQuery[User].titulo
UserDic['descripcion'] = UserListQuery[User].descripcion[:60]
UserList.append(UserDic)
print "PRINTING LIST " + UserList
print "PRINTING LIST 0 " + UserList[0]
I want UserList to be a dict list. I mean, if I print UserList[0]['username'], it has to return me the username in the position 0. Well, I've many users. I use append and I'm adding the user to the list. It's not working well, it overwrites the user resulting in a one position list, the last user from UserListQuery.
help?
The issue here is, that the same UserDic object gets used in each loop, so each time UserDic['username'] gets overwritten with the new value. To prevent this you must create a new UserDic every time. The following should work:
# Lista de usuarios
UserList = []
UserListQuery = UserProfile.objects.all()
for User in range(0,len(UserListQuery)):
UserDic = {}
UserDic['username'] = UserListQuery[User].user.get_username()
UserDic['titulo'] = UserListQuery[User].titulo
UserDic['descripcion'] = UserListQuery[User].descripcion[:60]
UserList.append(UserDic)
print UserList
(Untested code)
per my comment you should try this
user_list = []
user_list_query = user_profile.objects.all()
for user in range(0,len(user_list_query)):
user_list.append({
'username': user_list_query[user].user.get_username(),
'titulo' : user_list_query[user].titulo,
'descripcion': user_list_query[user].descripcion[:60]
})
print user_list
note i also changed the naming convention of your objects since python is preferred to use underscores between the names instead of capital letters
an even better way (more pythonic) to do it would be to remove all the excess stuff and just go with a single line loop
user_list_query = user_profile.objects.all()
print [{'username': user_list_query[user].user.get_username(), 'titulo' : user_list_query[user].titulo,'descripcion': user_list_query[user].descripcion[:60]} for user in range(0,len(user_list_query))]
I get a syntax error when i do this:
p = []
def proc(n):
for i in range(0,n):
C = i
global p.append(C)
Just change it to the following:
def proc(n):
for i in range(0,n):
C = i
p.append(C)
The global statement can only be used at the very top of a function, and it is only necessary when you are assigning to the global variable. If you are just modifying a mutable object it does not need to be used.
Here is an example of the correct usage:
n = 0
def set_n(i):
global n
n = i
Without the global statement in the above function this would just create a local variable in the function instead of modifying the value of the global variable.
The problem is you are trying to print list directly instead convert into a string before printing,and as array is a member of class Student, you need to reference it using 'self'.
The following code works:
class Student:
array = []
def addstudent(self,studentName):
print("New Student is added "+studentName)
self.array.append(studentName)
print(str(self.array))
def removeStudent(self,studentName):
print("Before Removing the Students from the list are "+ str(self.array))
self.array.remove(studentName)
print("After Removing the students from the list are "+ str(self.array))
if __name__ == '__main__':
studata = Student()
studata.addstudent("Yogeeswar")
studata.addstudent("Linga Amara")
studata.addstudent("Mahanti")
studata.removeStudent("Yogeeswar")
I have a class named Info where Info has a string type instance variable which can be accessed by Info.getName()
Also I have a list of instance Info such as class_list = [Info('Aleck'), Info('John')].
Given a name_list = ['Aleck', 'Bob'], I would like to remove the element in class_list with the same name in name_list, while i also need to know if a name (such as Bob) is not in class_list (for example print out that bob is not in list)
for above example the result should be class_list = [Info('John')] and print out that bob is not on the list.
I know ugly way of doing so such as the following codes (i am not actually running it, just an example), is there elegant or Pythonic way to do this?
def removeElement(name_list, class_list):
list_to_be_removed = []
for name in name_list:
is_name_in_list = false
for obj in class_list
if name == obj.getName():
list_to_be_removed.add(obj)
is_name_in_list = true
break
if is_name_in_list == false:
print name + ' is not in the list'
is_name_in_list = false
for obj in list_to_be_removed:
class_list.remove(obj)
You don't have classes, you have class instances. Info('Alice') is a constructor call, that creates an instance of your Info class.
How about this:
filtered = [info for info in info_list if info.get_name() not in name_list]
Alternatively:
filtered = filter(lambda o: o not in name_list, info_list)
If you have a lot of names convert your name_list into a set and use that.
name_set = set(name_list)
List comprehensions are your friend.
def remove_names(names_to_remove, info_list):
return [info
for info in info_list
if info.getName() not in names_to_remove]
I changed the names of most variables to be closer to what I think you mean.