I have a function getloantype(account_no) which I would like to call. The account numbers are in a list ['10101-2','10101-2', '10101-3'] and I would like the function to run one by one through all the account numbers and put all the results into another list. However, I cannot seem to get my code to run.
What I do: first, I get the user to input his userID and use it to fetch all the bank accounts that he owns from SQL database:
userid = input("Please enter user id")
conn=create_connection()
def getacct(userid):
query = """\
select Account_Number
from User_Account
where UserID = '{}'
""" .format(userid)
return (execute_read_query (conn, query))
account_no = getacct(userid)
As such, the account numbers would end up being in a list [account_no]. Next, I will need to use the account number to fetch his Loan ID. From this part comes the first question. Am I supposed to code it as getloanid(account_no) or getloanid(x) whereby x is for x in account_no ?
def getloanid(x):
query = """\
select SUBSTRING(LoanID, 1, 2)
from Account_Delinquency
where Account_Number = '{}'
""" .format(account_no)
return (execute_read_query (conn, query))
From here, I assume that I should do a nested for loop but the way I coded it, the list remains empty.
loanlist = []
for i in account_no:
for x in i:
getloanid(x)
loanlist.append(i[0])
I have also tried this which would return error :
'NoneType' object is not iterable
mylist = []
loanlist = []
for i in account_no:
mylist.append(i[0])
for x in mylist:
a = getloanid(x)
for i in a:
loanlist.append(i[0])
How can I code it such that I can call the function getloantype(account_no) with all the account numbers in the list account_no = getacct(userid) and have all the results be appended into a new list [loanlist]?
It is not so clear the structure of your program, and data returned from functions, but if I can undestand, a possible simple solution could be somthing like this:
result_list = [getloantype(account_no) for account_no in account_list]
Related
I've got a list name users, and I want a second list named account_no to take only the first part of the contents of users.
users = [
'GB1520*Adam Johnson*07293105657',
'ZA5584*Dean Davids*07945671883'
]
account_no = []
def find_accountno():
for index in range(len(users)):
# I want to take the first 6 characters of users[index]
acc = users[index: 6]
account_no.append(acc)
print(users)
find_accountno()
print(account_no)
And this is the desired output:
['GB1520', 'ZA5584']
But, instead, I'm getting this:
[['GB1520*Adam Johnson*07293105657', 'ZA5584*Dean Davids*07945671883'], ['ZA5584*Dean Davids*07945671883']]
You should read a bit more about slicing; you'll see that it doesn't work the way you think it does.
You wrote:
acc = users[index: 6]
This is saying "take every element in users from index index to index 6 (including index, not including 6), form a new list from them, and put them in acc".
For example:
l = [0,1,2]
b = l[0:2]
Would have the list [0,1] inside b.
If what you want is to grab the first six characters of users[index], then you simply want users[index][0:6] (so users[index] is the string you wish to slice; then [0:6] employs slicing as described above to only grab the first 6 elements: 0 to 5). You can also drop the 0 (so [:6]).
Some extras:
Another two solutions, just to show you some fun alternatives (these use what's known as list comprehension):
def find_accountno_alt1():
numbers = [user[:6] for user in users]
account_no.extend(numbers)
def find_accountno_alt2():
numbers = [user.split('*')[0] for user in users]
account_no.extend(numbers)
Another point: I'd personally recommend simply passing the list (account_no) as a parameter to make the method neater and more self-contained.
In your code, you need to use acc=users[index][:6].
users = ['GB1520*Adam Johnson*07293105657', 'ZA5584*Dean Davids*07945671883']
account_no = []
def find_accountno():
for index in range(len(users)):
acc = users[index][:6] #I want to take the first 6 characters of users[index]
account_no.append(acc)
#print(users)
find_accountno()
print(account_no)
As for the multiple output, you are getting that because you are also printing the users list.
I suggest you to split the strings by "*" char and take only the first part (your account id)
account_no = [user.split("*")[0] for user in users]
EDIT:
full code for your task
users = ['GB1520*Adam Johnson*07293105657', 'ZA5584*Dean Davids*07945671883']
account_no = [user.split("*")[0] for user in users]
print(users)
print(account_no)
Here is an alternative and more Pythonic way to write your code and get the results you want:
def find_account_numbers(users):
return [user[:6] for user in users]
users = [
'GB1520*Adam Johnson*07293105657',
'ZA5584*Dean Davids*07945671883'
]
account_numbers = find_account_numbers(users)
print(account_numbers)
The code snippet above will result in the following output:
['GB1520', 'ZA5584']
Working on this for learning experience. The 3 ideas below I came up with
A) User creates a profile so I have a dictionary for fname and lname.
B)Then I randomly generate userid add that to a list. This list only contains random user id that I will user later eg: userid012,userid89
C) I assign A and B in a new dictionary. Output looks like this:
used_id user3
profile {'lastname': 'jon', 'firstname': 'jme'}
problem: I only see the last values user id and names. If I have more than 2 entries, I do not see the 1st ones. Helpful hint would be really helpful.
Thank You.
import random
print('Enter choice 1-3:'),'\n'
print('', '1-Create new profile','\n',
'2-Update existing profile','\n',
'3-Delete a profile')
#global variables
choice=int(input())
user_directory={}
#Dictionary function that takes fst and lst name and puts in a dict:
def new_profile():
new_profile={}
fn=input('First name:')
new_profile['firstname']=fn
ln = input('Last name:')
new_profile['lastname'] = ln
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
#Generates a random user id which we will assign to a user created above
def user_id():
uid_list=[]
user_id='user'+str(random.randint(0,101))
uid_list.append(user_id)
if(user_id in uid_list):
uid_list.remove(user_id)
user_id = 'user' + str(random.randint(0, 101))
uid_list.append(user_id)
return user_id
#This dictionary will have user id and associate created new_profile
def addToDict():
#user_directory={} unable to use this making it global
user_directory['used_id']=user_id()
user_directory['profile']=new_profile()
for key,value in user_directory.items():
user_directory[key]=value
return user_directory
if(choice==1):
# myuser=addToDict() this appraoch did not work
#addToDict>> adding it here will not get this option in while loop, put inside while
while True:
addToDict()
print('Add another entry?')
choice=input()
#Put the line below to see if number increases
print('Current', len(user_directory)-1)
if(choice!='stop'):
continue
else:
break
for k,v in user_directory.items():
print(k,v)
Bad indentation in the last line of new_profile(). The return is running on the first iteration. Try:
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
Btw, you don't seem to be following most conventions/standards in Python. Take a look at this simple tutorial about PEP, the official style guide. This way you can make better looking code and we can help faster :)
Your code contains a couple of bugs. I can only guess what you want to do. Lets start with the obvious: The function addToDict() should probably add a new user to the dictionary.
What you usually want is to have a dictionary which maps a user_id onto a profile:
def addUserToDict(user_dictionary, user_id, profile):
user_directory[user_id] = profile
And then in the input loop below you call this function with your dictionary, a new user id and a new profile.
A second bug is in user_id(): You always return a list with one new element, with a new random user id. And you always discard the first generated user id and then you add a second one.
In my code I have a function that needs to return either a string or None depending on what is present in the database. However at the moment the result is a list with the string answer inside, or None. Is there any change that could be made that would result in just a string or None being returned, rather than having to index the list?
Here is the code:
def retrieve_player_name(username):
param = [(username)]
command = ("""
SELECT username FROM players
WHERE username = ?
""")
result = cur.execute(command, param).fetchone()
if result is not None:
return result[0]
Thanks in advance.
A database cursors fetches entire rows, not values.
Even a row with a single value inside is still a row.
If you don't want to write row[0] multiple times, create a helper function execute_and_return_a_single_value_from_query().
so I need to loop through dictionaries of dictionaries in dictionaries. Basically I am saving information like this to a dictionary:
accounts = {}
def accountcreator():
newusername = raw_input()
newpassword = raw_input()
UUID = 0
UUID += 1
accounts[newusername] = {newpassword:UUID}
Then in another function I want to loop through all of these values, so for example this is what I have so far. This correctly loops through all of the newusernames.
def accounts():
for usernames in accounts:
#I do not know what to do from here on out
#I want it to loop through all of the newpasswords and UUID
#And the UUIDs would be saved to a new variable
Please help me, I just want a simple answer on how to loop through all of the values.
Thank You!
EDIT
So basically this is a example:
def accountcreator():
newusername = raw_input() #For raw input I put in cool-account-name
newpassword = raw_input() #For raw input I put in this-is-a-password
UUID = 0
UUID += 1
accounts[newusername] = {newpassword:UUID} #So basically what is being saved is accounts[cool-account-name] = {this-is-a-password:1}
So after that happens I want this to happen with the accounts function. I want it to print each separate item, so basically it would print each of the follow: username, password, and UUID. So supplied with the information above it would print Username: cool-account-name, Password: this-is-a-password, and the UUID: 1.
You just need to add another loop over the values of accounts[usernames]
def accounts():
for usernames in accounts:
for passwords in accounts[usernames]:
# Here you can access the UUID you want through: accounts[usernames][passwords]
Dictionaries work differently than lists, so you will have to use the .values() or .keys() to iterate.
accounts.keys() would return all the keys in a dictionary:
d = {1:2,3:4}
for v in d.keys():
print (v)
# Would print 1 and 3
# And
for v in d.keys():
print (d[v])
# Would print 2 and 4
accounts.values() would return all the values of those keys in a dictionary:
d = {1:2,3:4}
for v in d.values():
print (v)
# Would print 2 and 4
You also must put global accounts line in each function, so that it would be able to access the accounts variable defined from outside. Otherwise, each function would create its own accounts variable or give an error
I'm making a search function for my website that breaks the entered text by spaces and then checks each work with __contains. I want to expand this so that I can pass through what columns I want it to check __contains with such as "First name", "Last Name"... ect.
What I have now:
def getSearchQuery(search,list,columns=None):
"""
Breaks up the search string and makes a query list
Filters the given list based on the query list
"""
if not columns:
columns = { name }
search = search.strip('\'"').split(" ")
for col in columns:
queries = [Q(col__contains=value) for value in search]
query = queries.pop()
for item in queries:
query |= item
return list.filter(query)
Issue is Q(col__contains=value) doesnt work as "col" is not a column. Is there some way to tell django that that is a variable and not the actual column? I have tried googling this but honestly dont know how to phrase it without putting all my code.
Do it this way:
import operator
from functools import reduce
def getSearchQuery(search, list, columns=None):
"""
Breaks up the search string and makes a query list
Filters the given list based on the query list
"""
if not columns:
return list
search = search.strip('\'"').split(" ")
queries = []
for col in columns:
queries.extend([Q((col+'__icontains', value)) for value in search])
return list.filter(reduce(operator.or_, queries))