Python Module Printing - python

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()

Related

TypeError: get_first_name() missing 1 required positional argument: 'self' in Python

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.

Unable to take input from user in python

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)

Password - Login not working Python

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

How can I get my login function to work properly

I'm trying to build a working login function that will take me to my menu.
Here is the code I have:
def login(userlist):
verified = False
name = input('username: ')
password = input('password: ')
while not verified:
name = input('username: ')
password = input('password: ')
if [name, password] in userlist:
verified = True
print('You logged in the system!')
else:
print('invalid username\password.')
return verified
Even though I type in the correct username and password into the program, it keeps saying Invalid...
What am I missing? Also, userlist is a textfile with the usernames and passwords are separated by lines. I'm able to read the file because of my load function:
def load():
user_file = open('userdata.txt', 'r')
userlist = []
line = user_file.readline()
while line != '':
line = line.split()
userlist.append(line)
line = user_file.readline()
user_file.close()
return userlist
My text file ends up looking like this:
username #password #list
Sam #password #[1,2,...]
(the list of numbers doesn't actually spill over to the next line)
Here is my registration function, which I think is relevant.
def register(userlist):
# ASK FOR USERNAME
name = input('Choose your username: ')
while search(userlist, name):
print('The username is not available. Choose somethng else. ')
name = input('Choose your username: ')
# ASKING FOR PASSWORD
password = input('Choose your password: ')
p = input('Retype your password: ')
while p != password:
password = input('Choose your password: ')
p = input('Retype your password: ')
# SURVEY INDEX
a = list(range(26))
user = [name, p, a]
userlist.append(user)
print('Your registration is successful, your user namw ia: ', name)
user_file = open('userdata.txt', 'a')
user_file.write(str(name) + ' ' + str(p) + ' ' + str(a)+ '\n')
user_file.close()
return userlist
if userlist is file IO object:
for i in userlist.readlines():
if [name, password] in i.split() # assumes no whitespace in password is allowed
verified = True
print('You logged in the system!')
if userlist is a dict:
if (name,password) in userlist.items()
You have issues with your load function. When you checked if [name, password] were in the userlist you hadn't stored the username and password together, they were in separate lists in the userlist.
So I changed the load function to do what you wanted.
I changed the load function though assuming your text file looks like this (missing line breaks is fine as well).
EDIT: Okay so I made changes to my answer now I know what your text file looks like.
def login(userlist):
verified = False
print(userlist)
while not verified:
name = input('username: ')
password = input('password: ')
if [name, password] in userlist:
verified = True
print('You logged in the system!')
else:
print('invalid username\password.')
return verified
def load():
userlist = []
with open('test.txt', 'r') as user_file:
for line in user_file:
line = line.strip()
if not line:
continue
userlist.append(line.split()[:2]) # Gets only name and password
return userlist
if __name__ == '__main__':
user_list = load()
login(user_list)
If you would like to change to a dictionary, instead then you can do this
if [name, password] in userlist: becomes if userlist.get(name) == password:
userlist = [] becomes userlist = {}
userlist.append(line.split()[:2]) becomes
name, password = line.split()[:2]
userlist[name] = password
Side Note:
I would suggest changing your write line to something cleaner.
user_file.write("{0} {1} {2}\n".format(name, p, a))

perform different splits based off different criteria to create a distinct output

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()

Categories

Resources