Alright so here's the code
def user_password():
input('Please Enter Password: ')
#profiles
def intercept():
user_password()
if user_password == "intercept":
print("this is working so far")
else:
print("Incorect Password")
def Jimmy():
user_password()
if user_password == "Jimmy":
print("this is working so far")
else:
print("Incorect Password")
def Tommy():
user_password()
if user_password == "Tommy":
print("this is working so far")
else:
print("Incorect Password")
#login
user_functions = dict(
intercept=intercept,
Jimmy=Jimmy,
Tommy=Tommy,
# ...
)
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
else:
print("Error: Unknown function.")
PROBLEMS:
My code always starts with asking for the password even though I don't want it
to.
When I change the first variable to a function it fixes this
Why does it execute when I'm just setting the variable. I'm pretty sure I shouldn't have to use a function instead of a variable
No matter what it always ends up as Incorrect Password even if I give the correct password
I think you are trying to write something like that:
def get_user_password():
return input('Please Enter Password: ')
def Jimmy():
user_password = get_user_password()
if user_password == "Jimmy":
print("this is working so far")
Related
No matter what I do, the code always reverts to the first username or password is incorrect statement. Here is the code:
lines = []
usernames = []
passwords = []
foundU = False
foundP = False
counter = 0
with open("login_project/logins.txt", "r+") as f:
lines = f.readlines()
f.close()
for element in lines:
if counter % 2 == 0:
usernames.append(element.strip())
else:
passwords.append(element.strip())
counter += 1
def Search(lista, val, found):
for i in range(0, len(lista)):
if lista[i] == val:
found = True
else:
pass
return found
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
Search(usernames, username, foundU)
Search(passwords, password, foundP)
if foundU == False or foundP == False:
print("Username or password is incorrect")
elif usernames.index(username) != passwords.index(password):
print("Username or password is incorrect 2")
else:
print("Login succesful")
login()
The error occurs here mainly:
if foundU == False or foundP == False:
print("Username or password is incorrect")
elif usernames.index(username) != passwords.index(password):
print("Username or password is incorrect 2")
else:
print("Login succesful")
Would appreciate any help, only doing this at a GCSE level so I am still quite a begginer.
edit: also in the file is just:
User01
password
User02
password2
Search never changes foundU or foundP. Passing a variable to a function in Python doesn't necessarily mean that if you change the variable in the function, that it will change the original. You just need to do something like foundU = Search(usernames, username). In addition, since foundU and foundP are globals, if you want to change their values globally, you have to declare them as globals:
...
def login():
global foundU
global foundP
username = input("Please enter your username: ")
password = input("Please enter your password: ")
foundU = Search(usernames, username, foundU)
foundP = Search(passwords, password, foundP)
...
However, Search is unnecessary, since Python's in operator does what you want. So you could just do:
foundU = username in usernames
foundP = password in passwords
You have global variables foundU and foundP - these are not being modified inside your function when you call search. Even if they were - your function would simply create a local copy unless you "tell" your code not to.
def login():
global foundU # to modify a global from local scope
global foundP
username = input("Please enter your username: ")
password = input("Please enter your password: ")
# set var using returned val from call to function
foundU = Search(usernames, username, foundU)
foundP = Search(passwords, password, foundP)
If you were to have your login routine return an indicator of login (a bool perhaps) to where it is called, you may be better to remove the global vars and just use two locals.
After posting this, I noticed another problem with using the search function as implemented, and with using the "in" keyword as suggested.. neither will ensure that the username and password match... any username with any password would get authenticated.... so, here is a version that seems to work but it does not need the global vars
lines = []
usernames = []
passwords = []
counter = 0
with open("login_project/logins.txt", "r+") as f:
lines = f.readlines()
f.close()
# ensure there is a password for each user
assert len(usernames) == len(passwords), "Error reading file"
for element in lines:
if counter % 2 == 0:
usernames.append(element.strip())
else:
passwords.append(element.strip())
counter += 1
def validate(u_name, password):
'''Check that user and p/w are at same indices
in each of the lists'''
for i in range(0, len(usernames)):
if usernames[i] == u_name:
if passwords[i] == password:
return True
return False
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
found = validate(username, password)
if found:
print("Login successful")
return True
else:
print("Username or password is incorrect")
return False
login()
A better data structure may be to use a dict for usernames (keys) and passwords(values) and write these to a json file which looks very similar with the caveat that all the data is stored as str.
i'm trying to implement login attempt system to my current code, but i don't know where i should tick it. Can someone suggest anything? I would like to give three attempts to login, if user fails to login, system will lock user out. I just dont know where to position the code properly.
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
The better way to do this problem is by having a JSON file instead of a txt file. You can have the file in this format:
{
"username": {
"password": "",
"attempts": 0,
}
}
In the login() function increment and write the count of attempts if the password is wrong.
And before the function begins read the JSON and check if the attempts value is greater than 3. If it is greater send an appropriate message else to continue the login action and ask for the password.
Your code had some minor errors which I have handled here:
import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0: # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "\n"+name[0]+","+password) # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)
Hi i'm new in python and in programming in general ! i tried to make a login system with python but it doesnt seem to be working as i expect
the problem is even if i enter false login informations at the end the program will print login successful instead of printing incorrect username or password
NOTE : i'm not trying to make real login system it's just some practice form what i learned
signup_username = ""
signup_password = ""
login_username = ""
login_password = ""
false_login_info = False
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
signup()
print("Signup successful")
login()
if login_username != signup_username or login_password != signup_password :
print("Incorrect username or password")
else :
print("login successful")
EXPECTED Result :
1) if login informations are same as signup infos i should get :
- Login successful
2) if login informations are NOT same as signup infos i shoul get :
- Incorrect username or password
ACTUAL Result :
in both cases the program will print login successful
You need to return the values from your functions. The names defined inside the function are not the same as those that exist outside of the function. In this case, I have appended x to the names in the global scope to differentiate them from the ones inside the function to hopefully make it clearer. I could have used the same names both inside the function and outside; it wouldn't have made a difference. You can see more here.
There is no need to "initialise" the variables as empty strings before the function call. Instead, we'll just create them in the function, return them, and then unpack them into the variables ending in x.
false_login_info = False # You never use this
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
return signup_username, signup_password
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
return login_username, login_password
signup_usernamex, signup_passwordx = signup()
print("Signup successful")
login_usernamex, login_passwordx = login()
if login_usernamex != signup_usernamex or login_passwordx != signup_passwordx:
print("Incorrect username or password")
else :
print("login successful")
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
I'm having a bit of trouble with this program I've been working on for part of the final for my ITP 100 class. It's supposed to be an email application where you can log in if you are an existing user, or create a new username and password. I'm able to log into existing users with their passwords, and I can create a new username, but when I try to create the new password for it, I keep getting errors. I'm sure it's because I'm not updating the dictionary properly. I'm still pretty new to Python, so hopefully this all makes sense. Any advice?
Also, my program seems to be stuck in an "if loop..?". Whenever I successfully log into an existing user, it show that I've been logged in, but will also go back to the original question "Are you a registered user? y/n? Press q to quit"
Any help is greatly appreciated. Thank you.
import re
users = {}
users={"nkk202": "konrad", "jfk101": "frederick"}
choice = None
login = None
createPassword = None
createUser = None
createLogin = None
print("Welcome to Kmail. The most trusted name in electronic mail.")
print("\nLet's get started")
while choice != "q":
choice = input("Are you a registered user? y/n? Press q to quit: ")
if choice == "q":
print("Thank you for using Kmail. Goodbye.")
if choice == "n":
print("Okay then, let's set up an account for you then.")
createUser = input("Create login name: ")
if createUser in users:
print("I'm sorry, that username is already in use. Please try another!\n")
else:
createPassword = input("Enter a password: ")
if len(createPassword) <5:
print("I'm sorry, this password is too short. Please try another.")
passValue = {1:'Weak', 2:'Good', 3:'Excellent'}
passStrength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', createPassword):
passStrength['has_upper'] = True
if re.search(r'[a-z]', createPassword):
passStrength['has_lower'] = True
if re.search(r'[0-9]', createPassword):
passStrength['has_num'] = True
value = len([b for b in passStrength.values() if b])
print ('Password is %s' % passValue[value])
users.update((createUser, createPassword))
elif choice == "y":
login = input("Enter your username: ")
if login in users:
password = input("Enter your password: ")
if users[login] == password:
print("Welcome", login, "!")
else:
print
print("I'm sorry, either the password/username was unaccaptable, or does not exist. Please try again. \n")
Seems like you just want
users[createUser] = createPassword