The menu provides input options to the user. The main focus is on having the functions being called without error as previously experienced. The resolution was that my code was incorrectly formatted. displayed() first then login() and register().
Resolution:
def displayMenu():
global menu_input
menu_input = input("Please enter one of the following options:\n r - register user\n a - add task\n va- view all tasks\n vm - view my tasks\n e - exit\n")
if menu_input == "r":
register()
elif menu_input == "a":
add_task()
elif menu_input == "va":
view_all()
elif menu_input == "vm":
view_more()
elif menu_input == "e":
exit()
return menu_input
displayMenu()
def login():
username = input("Please enter your username?:\n")
password = input("Please enter your password?:\n")
for line in open("user.txt","r").readlines():
field = line.strip().split(",")
if username == field[0] and password == field[1]:
print("Username & Password Correct!\n")
return True
print("Username & Password Incorrect\n")
return False
login()
def register():
register = False
while register == False:
username = input("Please enter a username?: ")
password = input("Please enter a password?: ")
password_check = input("Please re-enter the password?:")
if password == password_check:
file = open("user.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
register = True
print ("Your login details have been saved. ")
else:
print("Passwords doesn't match!")
register()
You should declare the register function before you call to the displayMenu().
Try to move you function declarations to the top of your code.
The resolution for me was moving my function login() below all my other functions without calling them unless in the displayMenu() & displayMenu_Admin().
Also, I had to read up on functions() as I didn't understand the concept fully.
Related
I am creating a simple program that checks a text file for usernames and passwords. if the username and password is found a message is printed and access to granted. it returns the success message if the details are correct however when i run my code i am prompted to enter my username and password twice.
this is the code
def login():
loginUsername = input("Enter Username: ")
loginPassword = input("Enter PASSWORD: ")
with open('password.txt') as data:
accounts = data.readlines()
userfound = False
for line in accounts:
splitline = line.split("\t")
if loginUsername == splitline[0] and loginPassword == splitline[1]:
userfound = True
break
return userfound
options = input("please make a choice 1 to register a new user account, 2 to login or 3 to exit to program \n")
user_found = login()
if options == "1":
register()
elif options == "2":
login()
elif options == "3":
sys.exit()
else:
print("Please make a valid choice")
if user_found:
print("LOGGED IN")
# print menu
else:
print("Login FAILED")
this is what happens when the program runs. in this case incorrect details were run
please make a choice 1 to register a new user account, 2 to login or 3 to exit to program
2
Enter Username: 22
Enter PASSWORD: ww
Enter Username: ww
Enter PASSWORD: ww
Login FAILED
login is called twice. On user_found = login() and
elif options == "2":
login()
You should probably only include it in the if-else statement.
if options == "1":
register()
elif options == "2":
user_found = login()
elif options == "3":
sys.exit()
else:
print("Please make a valid choice")
The prompt to enter username and password is displayed twice because login() is called once irrespective of the user choice in the below line.
user_found = login()
The same login() is called for the second time when the user enters the choice 2.
elif options == "2":
login()
If i understand your requirement correctly, The code needs to be modified like below.
options = input("please make a choice 1 to register a new user account, 2 to login or 3 to exit to program \n")
if options == "1":
register()
elif options == "2":
user_found = login()
elif options == "3":
sys.exit()
else:
print("Please make a valid choice")
if user_found:
print("LOGGED IN")
# print menu
else:
print("Login FAILED")
I am new in Python, I would like to ask how can make my code work.
in login() function, if the username and password are correct, log = True, then when go to main() function, log variable is not defined.
Then i found online where add log = login() in main() function, like this
def main():
log = login()
if log == True:
identifier = loginChoice()
if identifier == 1:
customerMain()
if identifier == 2:
adminMain()
It works for that people, but for me, it goes into endless loop where it keeps calling login() function.
Below is my whole code
def loginChoice():
print("\n","Login as:")
print("1. Customer")
print("2. Admin")
choice =int(input())
if choice == 1:
login()
return choice
if choice == 2:
login()
return choice
def login():
print("\n", "Login menu")
user = input("Username: ")
passw = input("Password: ")
fhand = open("userpassword.txt", "r")
for line in fhand.readlines():
us, pw = line.strip().split("\t")
if (user == us) and (passw == pw):
log = True
print("Login successful!")
return True
else:
print ("Wrong username/password")
return False
def main():
if log == True:
identifier = loginChoice()
if identifier == 1:
customerMain()
if identifier == 2:
adminMain()
Thanks for helping me.
The screenshot of the login menu is in loop
I modified your code.this will works fine
but the customerMian() and adminMain() function not defined.
def loginChoice():
print("\n","Login as:")
print("1. Customer")
print("2. Admin")
choice =int(input())
return choice
def login():
print("\n", "Login menu")
user = input("Username: ")
passw = input("Password: ")
fhand = open("userpassword.txt", "r")
for line in fhand.readlines():
us,pw = line.strip().split("\t")
if (user == us) and (passw == pw):
print("Login successful!")
return True
else:
print ("Wrong username/password")
return False
if __name__ == '__main__':
log = login()
if log == True:
identifier = loginChoice()
if identifier == 1:
customerMain()
if identifier == 2:
adminMain()
I'm a total newbie to programming and have just begun my first project which is a simple login app.
So far my code looks like this:
def login_or_registration():
user_choice = input("Login (L) or Registration (R)? ").lower()
if user_choice == "l":
print("You will be redirected to the login window.")
login()
elif user_choice == "r":
print("You will be redirected to the registration window.")
registration()
else:
print("Invalid choice.")
def registration():
name = input("Name: ")
surname = input("Surname: ")
username = input("Username: ")
pass1 = input("Password: ")
pass2 = input("Repeat password: ")
if pass1 != pass2:
print("Passwords don't match!")
email = input("E-mail: ")
age = input("Age: ")
while True:
if not age.isdecimal():
print("Please enter a number.")
if not name.isalpha():
print("Please use only letters for Name and Surname.")
if not surname.isalpha():
print("Please use only letters for Name and Surname.")
break
with open("userbase.txt", "a") as f:
f.write(username + "\n" + pass1 + "\n" + surname + "\n" + name + "\n" + email + "\n" + age + "\n" + "\n")
f.close()
user_choice = input("Would you like to log in now? (Y/N) ").lower()
if user_choice == "y":
login()
else:
"Quitting."
def login():
logged_in = False
username = input("USERNAME: ")
password = input("PASSWORD: ")
while logged_in == False:
f = open("userbase.txt", "r")
for line in f:
if line == username:
logged_in = True
print("Logged in!")
print("User not found!")
login_or_registration()
I know its incomplete and messy but for now i want to work on a function for logging in. My idea was to create a function that would iterate over a text file and search for a match to the users input I know it's not perfect and could have many problems but for now I want to avoid modules. I wrote the function login() but it doesn't work and I don't have an idea how to make it run. My idea was to make an if statement that would be checked for every iteration of a for loop inside a while loop combined with a boolean that would be set to True after the statement is true.
When I log in as an "existing user", it works perfectly when I log in first try
But in the while loop, when I get the login incorrect and it prompts me again and THEN I get the login correct, it comes up as login failed
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()
I expect the output for the login to be successful, but it says incorrect unlike when I get it right the first try
After Python has read a file, its "Prompt" is at the end of the file. If you do call read on the fileobject again it will return nothin since there is nothing left to read.
With seek(x) you can place the "Prompt" to the postion x. In you case 0 since you want to read the file again.
I injected the line on the right place:
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
accountFileR.seek(0) # <---- injected line
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()
This code is at the start and when I run the code it doesn't do anything and nothing shows up, please help?
users = {}
status = ""
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
I expect the output to be a login system that then leads to a quiz but when I run it all I get is blank space
All you're doing is creating a couple of variables and declaring some functions.
Neither of those things will result in any output. If you want the functions to run, you'll actually need to call them from somewhere, such as by putting register() or login() (with no indentation) after the function definitions.
You defined the functions, but didn't call either, you should call one or both at the end of your script like :
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
login()