I have a made a function in which I am taking value from user and want to send that value to another function for verification. But the problem is that I am unable to take value from user because that part of code is not running. The interpreter takes me directly to else part of the while loop. Here is my code:
from userAccountDatabase import *
FirstName = ""
LastName = ""
dateOfBirth = ""
userDetails = []
def userDetailsValidation(fieldvalue, fieldName, database):
for entry in database:
if fieldName in entry and entry[fieldName] == fieldvalue:
print("correct value")
return True
else:
return False
def userInputs(FirstName, LastName, dateOfBirth):
FirstName = str(input("Enter First Name").upper()) # This part of code is not running
while True:
if(userDetailsValidation(FirstName, "FirstName", userAccountDetails)) == True:
userDetails.append(FirstName)
break
# directly take me to this
else:
print('Enter valid First Name')
FirstName = str(input("Enter First Name").upper())
userInputs(FirstName, LastName, dateOfBirth)
Related
I have user info from a SQL Server - a username and password -
and now I want to create a dictionary
{ID : password}
but if I have more then one it just saves the last one I put in
for i in (cursor.execute('select * from Person')):
idNameDict = {i[0]:i[3]}
I want to do it this way so it would be easier for me to do check if the based on the ID that the password input would be correct because right now and it seems to long
def logIn(userName,userPassword):
userID=[]
global p
lbl = Label(root)
lbl.grid(row=5,column=1)
for user in (cursor.execute('select * from Person')):
p = Person(user[0],user[1],user[2],user[3])
userID.append(p)
for id in userID:
if userName == id.ID:
if userPassword == id.password:
userPage(root,userName)
else:
lbl.config(text= "Invalid Password")
else:
lbl.config(text= "Invalid User Name")
Your current code doesn't work properly because you declare the dictionary from scratch in each iteration. You need to do it in the following way:
idNameDict = {}
for i in (cursor.execute('select * from Person')):
idNameDict[i[0]] = i[3]
So im having trouble displaying the admins first name, for some reason it keeps saying it doesnt exist, please give me some feedback on whats wrong, very appreciated
below you can find the admin class where we set all parameters like first name and last name etc
after that weve got the bank system class where ive imported the admin class and instanced it and still nothing, even after adding the missing positional argument it says that fname does not exist
class Admin:
def __init__(self, fname, lname, address, user_name, password, full_rights):
self.fname = fname
self.lname = lname
self.address = address
self.user_name = user_name
self.password = password
self.full_admin_rights = full_rights
def update_first_name(self, fname):
self.fname = fname
def update_last_name(self, lname):
self.lname = lname
def get_first_name(self):
return self.fname
def get_last_name(self):
return self.lname
from customer_account import CustomerAccount
from admin import Admin
accounts_list = []
admins_list = []
class BankSystem(object):
def __init__(self):
self.accounts_list = []
self.admins_list = []
self.load_bank_data()
def load_bank_data(self):
# create admins
admin_1 = Admin("Julian", "Padget", ["12", "London Road", "Birmingham", "B95 7TT"], "id1188", "1441", True)
self.admins_list.append(admin_1)
admin_2 = Admin("Cathy", "Newman", ["47", "Mars Street", "Newcastle", "NE12 6TZ"], "id3313", "2442", False)
self.admins_list.append(admin_2)
def search_admins_by_name(self, admin_username):
found_admin =None
for a in self.admins_list:
username =a.get_username()
if username ==admin_username:
found_admin =a
break
if found_admin ==None:
print("\n The Admin %s does not exist! Try again...\n"%admin_username)
return found_admin
def main_menu(self):
#print the options you have
print()
print()
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("Welcome to the Python Bank System")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Admin login")
print ("2) Quit Python Bank System")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_main_options(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
username = input ("\n Please input admin username: ")
password = input ("\n Please input admin password: ")
admin_obj = self.admin_login(username, password)
if admin_obj != None:
self.run_admin_options(admin_obj)
elif choice == 2:
loop = 0
print ("\n Thank-You for stopping by the bank!")
def admin_login(self, username, password):
found_admin=self.search_admins_by_name(username)
msg="\n Login failed"
if found_admin!=None:
if found_admin.get_password()==password:
print("Login Sucssesful")
return msg,found_admin
def admin_menu(self, admin_obj):
#print the options you have
admin_obj = Admin
print (" ")
print ("Welcome Admin %s %s : Avilable options are:" %(admin_obj.get_first_name(), admin_obj.get_last_name()))
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Transfer money")
print ("2) Customer account operations & profile settings")
print ("3) Delete customer")
print ("4) Print all customers detail")
print ("5) Sign out")
print (" ")
option = int(input ("Choose your option: "))
return option
app = BankSystem()
app.run_main_options()
At least two problems:
BankSystem.admin_login() returns a pair consisting of a message and an admin object, but run_main_options() assigns that pair to a single variable admin_obj. You should change it to something like msg, admin_obj = … to behave like you appear to expect.
BankSystem.admin_menu() overwrites the object it was passed on the first line. This line should be removed.
I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue
My functions are printing when they are run, but I want to either print from my master file or create a separate print function. I don't know how to pass the return value to my print.
Master.py:
import main
import split
import password
main.py:
import split
def main():
# first_name = raw_input('please enter Your Name: ')
# family_name = raw_input('Please enter Your Surname: ')
# student_ID = raw_input('Please enter your Student ID number: ')
first_name = 'Benjamin'
family_name = 'Montgomery'
student_ID = '1000036317'
login = split.letters(first_name, family_name, student_ID)
print login
return login
main()
split.py:
# import main
def letters(first_name,family_name,student_ID):
name = first_name[:3]
lastname = family_name[:3]
ID_tree = student_ID[:3]
login = name+lastname+ID_tree
# print login
return str(login)
# letters(first_name,family_name,student_ID)
Your functions look ok, but be careful about creating modules that share the same names with common functions and methods. "split" is a method of string. I tested out your code with minor changes and it printed fine (here's what I got):
login -> BenMon100
#msplit.py
def letters(first_name,family_name,student_ID):
name = first_name[:3]
lastname = family_name[:3]
ID_tree = student_ID[:3]
login = name+lastname+ID_tree
# print login
return str(login)
#main.py
import msplit
def main():
# first_name = raw_input('please enter Your Name: ')
# family_name = raw_input('Please enter Your Surname: ')
# student_ID = raw_input('Please enter your Student ID number: ')
first_name = 'Benjamin'
family_name = 'Montgomery'
student_ID = '1000036317'
login = msplit.letters(first_name, family_name, student_ID)
print 'login ->', login
return login
main()
When I execute the below python code I have written, (I am trying to create a user name based off three distinct scenarios (1.user enters First, middle, and last name, 2. user enters first and last name, 3. user enters only last name. I am attempting to create a username based off the first 4 characters of the last name+first initial (when provided)+middle initial(when provided). When I execute the below code, using the first+last name combination or just last name, I receive
lastName = (listnames[2])
IndexError: list index out of range
def entirename(fullName):
lowername = str.lower(fullName)
delimiter =' '
listnames = (lowername.split(delimiter))
lastName = (listnames[2])
lname = lastName[0:4]
fInit = listnames[0]
fname = fInit[0]
mInit = listnames [1]
mname = mInit[0]
username =lname+fname+mname
return
def firstlast(fullName):
lowername = str.lower(fullName)
delimiter =' '
listnames = (lowername.split(delimiter))
lstName = (listnames[1])
lname = lastName[0:4]
fInit = listnames[0]
fname = fInit[0]
username = lname+fname
return
def last(fullName):
lowername = str.lower(fullName)
delimiter =' '
listnames = (lowername.split(delimiter))
lstName2 = (listnames[0])
lname = lstName2[0:4]
username = lname
return
def main():
print "Hello! This program will contruct a new userid for you."
print ""
fullName = raw_input('Please enter your full name: ')
while True:
if fullName[2]:
entirename(fullName)
break
elif fullname[1]:
firstlast(fullName)
break
elif fullname[0]:
last(fullName)
break
main()
Or you could write something simpler like:
def get_id():
print "Hello! This program will contruct a new userid for you.\n"
name = raw_input('Please enter your full name: ').lower().split(' ')
userid = name[-1][:4] # first 4 chars of last name
if len(name) > 1:
userid += name[0][0] # first char of opt first name
if len(name) > 2:
userid += name[1][0] # first char of opt middle name
return userid
userid = get_id()
print 'userid:', userid
I think your main() is wrong. ... fullname[2] is the third character of the string... if I am not mistaken...? Since it's not split yet.
EDIT:
So split() it in main() and you should be good to go.
Also notable that you can't str.lower() a list. Which is what tipped me off.
RE-EDIT:
This should do the trick. Fully tested rewrite:
def main():
print "Hello! This program will contruct a new userid for you.\n"
fullstring = raw_input('Please enter your full name: ')
fullName = fullstring.split(' ')
lowerName = list()
for each in fullName :
lowerName.append(each.lower())
lowerName.reverse()
lastname = lowerName.pop(0)[0:4]
lowerName.reverse()
if lowerName : lastname += lowerName.pop(0)[0]
if lowerName : lastname += lowerName.pop(0)[0]
return lastname
main()