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))
Related
i am new here and i am trying to learn python. i want to create a simple atm program but i also want to try something that i haven't seen yet. i want to take input from user and select one of objects of a class regard to this selection, here is the part of my code
class bankaccount():
def __init__(self,name,money):
self.name=name
self.money=money
def show(self):
print(self.name,self.money)
johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)
selection= input("please write the name: ")
for example i will write john and program should run johnaccount.show is this possible? could you please help about this issue.
Below
class bankaccount():
def __init__(self,name,money):
self.name=name
self.money=money
def show(self):
print(self.name,self.money)
# build the accounts 'DB' (which is just a dict)
# read more here: https://cmdlinetips.com/2018/01/5-examples-using-dict-comprehension/
accounts = {name: bankaccount(name,balance) for name,balance in [("john",500),("mike",1000)]}
user = input("please write the name: ")
account = accounts.get(user)
if account:
account.show()
else:
print(f'no account for {user}')
There is a "hacky" way to do that (see below). Usually you'd rather have a dictionary or list containing all of the accounts and then get the account from there.
For example:
accounts = {
'john': bankaccount("john",500),
'mike': bankaccount("mike",1000)
}
selection = input("please write the name: ")
if selection in accounts:
print(f"Balance: {accounts[selection].show()}")
else:
print("Account not found")
The "hacky" way is to use Python's built-in locals function:
johnaccount=bankaccount("john",500)
mikeaccount=bankaccount("mike",1000)
sarahaccount=bankaccount("sarah",1500)
selection = input("please write the name: ")
account_name = f"{selection}account"
if account_name in locals():
print(f"Balance: {locals()[account_name].show()}")
else:
print("Account not found")
The f"Balance: {accounts[selection].show()}" syntax that I'm using is called f-strings, or formatted string literals.
PS. it's common practice to use CamelCase for class names, e.g. BankAccount, and to use lowercase and underscores for variable names, e.g. john_account.
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.
Take the list Usernames as shown below.
Usernames = ["johnsmith"]
I have the variable NewUsername and I need to check if its value is already contained in the list. If not, an integer will be concatenated to the end of it.
Examples:
NewUsername = "alexsmith"
Usernames = ["johnsmith", "alexsmith"]
NewUsername = "johnsmith"
Usernames = ["johnsmith", "alexsmith", "johnsmith1"]
NewUsername = "johnsmith"
Usernames = ["johnsmith", "alexsmith", "johnsmith1", "johnsmith2"]
Now, I know I can do this with something like this, but it would only check for the first 'level' of duplicate names.
if NewUsername in Usernames:
NewUsername = NewUsername + "1"
Usernames.append(NewUsername)
Question: How can I handle all duplications in a similar manner?
Maybe is a bit elaborate, but you could use a custom child class of a list. To give you an idea:
from collections import Counter
class UsernameList(list):
def __init__(self, *args):
super(UsernameList, self).__init__()
self._ucount = Counter()
for e in args[0]:
self.append(e)
def append(self, el):
if isinstance(el, str):
if self._ucount[el] == 0:
super(UsernameList, self).append(el)
else:
fixel = el + str(self._ucount[el])
super(UsernameList, self).append(fixel)
self._ucount.update([fixel])
self._ucount.update([el])
else:
raise TypeError("Only string can be appended")
Now you could do:
Usernames = UsernameList(["johnsmith"]) #Username is ["johnsmith"]
Usernames.append("johnsmith") #Username becomes ["johnsmith", "johnsmith1"]
Usernames.append("johnsmith") #Username becomes ["johnsmith", "johnsmith1", "johnsmith2"]
Apart the new __init__ and append methods, UsernameList has all the methods of a list, and works exactly as a list. Don't bother about the counter attribute, it's there to keep track of the usernames inputed and add the correct number in case of repetitions.
To have something more consistent you may need to override other methods: i'm just giving you an idea, far from writing a full working code here.
You may have a look at the docs for more details on which methods you may need to override.
I am creating a class structure in python for a city, that stores the name, country, population and language for a city, all of which are input by the user. The information shall then be printed.
I think that I may be successful in storing the information within the class structure (although this may be wrong as well), but I am unsuccessful in printing the information. Currently, I am receiving the error that int object is not subscriptable.
class User():
def _init_(self, username, password, email, numOfLogins):
User.username = username
User.password = password
User.email = email
User.numOfLogins = numOfLogins
#User Record Array Creation
def createUserArray(num , User):
UserArray = []
for x in range(num):
UserArray.append(User)
return UserArray
#User Record Array Population
def populateUserArray(num, UserArray):
for x in range(len(userArray)):
UserArray[x].username = str(input("Enter username."))
UserArray[x].password = str(input("Enter password."))
UserArray[x].email = str(input("Enter email address."))
UserArray[x].numOfLogins = int(input("Enter number of logins."))
return UserArray
#User Record Array Display
def displayUserArray(UserArray, num):
for x in range(len(userArray)):
print(UserArray[x].username, UserArray[x].password, UserArray[x].email, str(UserArray[x].numOfLogins))
#Top Level Program
numOfUsers = 3
userArray = createUserArray(numOfUsers, User)
userArray = populateUserArray(numOfUsers, userArray)
displayUserArray(numOfUsers, userArray)
The contents of the class should all be displayed at the end of the program, but at the minute my program crashes due to the error - int object is not subscriptable.
you can always implement the method : __str__(self) of an object , and then when you just print it with :
your_obj = User(...)
print your_obj
your __str__(self) will be called and you can return from it whatever you want to print.
for example:
def __self__(self):
return `this class has the following attributes: %s %s %s %s` % (self.username,self.password,self.email ,self.numOfLogins )
and this what will get print, i think it is more efficient and well coded to work like that and not creating a function that print each class attribute separately.
The cause of your error is quite simple and obvious: you defined the function as displayUserArray(UserArray, num) but call it with displayUserArray(numOfUsers, userArray) - IOW you pass the arguments in the wrong order.
This being said, almost all your code is wrong, you obviously don't get the difference between a class and instance and how to use a class to create instances. I strongly suggest you read at least the official tutorial, and check a couple other tutorial and/or example code on the topic of classes and instances.
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))]