Username and Password Variable Incorrect - python

Helo guys
i'm trying to create a login system, it's run normally when i input username and password directlt after i signed up on my own code, but when i try to login using false username or password bruteforcely variable "p" or "u" is changed by itself. I dunno why it's happened here's my code
sorry for my bad english and my bad code(it's weird"), i'm new in programming language and python "i've tried my best" so if anyone wants to fix my code or something else please help me, 1 more question is there any code to loop when the input is false? i used a function that call the lastest function if the input is false
import os
import sys
import re
def apus():
sys.stdout.write(CURSOR_UP_ONE)
sys.stdout.write(ERASE_LINE)
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
def main():
os.system("cls")
print(""""
Welcome To X Bank
Enter Any Key To Continue
""")
x = input()
menu()
def menu():
os.system('cls')
print("------------------------------------------------------------------------")
print('''
Don't Have An Account Yet? Please Sign Up
1. Login
2. Sign Up
''')
print("------------------------------------------------------------------------")
opsimenu()
def opsimenu():
#os.system("cls")
a = int(input())
os.system("cls")
if a == 1:
login()
elif a == 2:
signu()
else:
menu()
def ulog():
login()
def login():
os.system('cls')
print("Enter Your Username And Password \n \n")
C = input("Username = ")
D = input("Password = ")
while True:
if C == u and D == p:
login2()
break
else:
print("Your Username Or Password Is Incorrect")
ulog()
def login2():
os.system("cls")
print("Login Succesful")
def signu():
global Address
global Name
#print("\n ")
print("""
Your Username And Password *
*Must be at least 8 characters.
*must be between [a-z]
*Must be at least one alphabet should be of Upper Case [A-Z]
*Must be at least 1 number or digit between [0-9].
*Must be at least 1 character from [!##$%^&*].
""")
Name = str(input("Full Name:"))
Address = str(input("Address: "))
enteruser()
def signup():
enteruser()
def enteruser():
global u
Username = (input("Username:"))
flag = 0
while True:
if (len(Username) < 8):
flag = -1
break
elif not re.search("[a-z]", Username):
flag = -1
break
elif not re.search("[A-Z]", Username):
flag = -1
break
elif not re.search("[0-9]", Username):
flag = -1
break
elif not re.search("[!##$%^&*]", Username):
flag = -1
break
elif re.search("\s", Username):
flag = -1
break
else:
flag = 0
break
if flag == -1:
apus()
#print("Invalid Username")
signup()
u = Username
pw()
def ulangpw():
pw()
def pw():
global p
Password = str(input("Password:"))
while True:
if (len(Password) < 8):
flag = -1
break
elif not re.search("[a-z]", Password):
flag = -1
break
elif not re.search("[A-Z]", Password):
flag = -1
break
elif not re.search("[0-9]", Password):
flag = -1
break
elif not re.search("[!##$%^&*]", Password):
flag = -1
break
elif re.search("\s", Password):
flag = -1
break
else:
flag = 0
break
if flag == -1:
print("Invalid Password")
apus()
apus()
ulangpw()
p = Password
os.system("cls")
validating()
def validating():
print(" ---------------------------------------------------")
print(" You have successfully created your account.\n Press Any Key To Login. \n \n Validating Your Data")
print("\n • Full Name ="+ Name)
print(" • Address ="+ Address)
print(" • Username ="+ u)
print(" • Password ="+ p)
print(" ---------------------------------------------------")
#p = Password
confirm = str(input("\n Make sure all registration data that is filled in is correct> Y/N "))
while True:
if confirm == "Y" or confirm =="y":
login()
break
elif confirm == "N" or confirm == 'n':
os.system("cls")
signu()
break
else:
confirm = str(input("\n Make sure all registration data that is filled in is correct> Y/N ="))
break
>main()

python wont print this:
print("""
Your Username And Password *
*Must be at least 8 characters.
*must be between [a-z]
*Must be at least one alphabet should be of Upper Case [A-Z]
*Must be at least 1 number or digit between [0-9].
*Must be at least 1 character from [!##$%^&*].
""")
Because it is syntax for uncommenting text
""" multiline comment line 1
multiline comment line 2 """
You have to use quotes like
print("Hi Dad")

Related

Python, Username and Password with 3 attempts

I have started learning python about 2 weeks ago and am trying to create a password system that can store multiple usernames and passwords. I am trying to add a bit of code where it makes you wait a minute if you input a wrong password 3 times.
I keep on getting an error where if you get the password wrong 3 times and wait the 60 seconds, even if you do input the right password and username it prints "Your password is wrong. You have only 3 attempts left."
Can somebody help and point out flaws that I have in the code?
import time
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
success = 0
Tries = 0
Valid = False
Pass = ""
def login():
global success
global Pass
global Tries
inuser = input(str("Enter your username: \n"))
inpass = input(str("Enter your password: \n"))
if inuser not in username:
print("username not found in directory")
login()
else:
posUser = username.index(inuser)
Pass = password[posUser]
while success != 1:
if Tries == 3:
print("You have had too many attempts. Wait 60 seconds before trying again")
for i in range(60, 0, -1):
time.sleep(1)
print(i)
if Tries == 3:
Tries = 0
inuser=str("0")
inuser=str("0")
login()
else:
break
if Pass == inpass:
success=1
else:
Tries += 1
AttemptsLeft = (3 - Tries)+ 1
print("Your password is wrong. You have only {} attempts left.".format(AttemptsLeft))
login()
login()
if success==1:
print("Welcome to ------")
If you get rid of the recursion, everything will get simpler.
import time
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
success = 0
Tries = 0
Valid = False
Pass = ""
def login():
global success
global Pass
global Tries
while success != 1:
inuser = input(str("Enter your username: \n"))
inpass = input(str("Enter your password: \n"))
if inuser not in username:
print("username not found in directory")
else:
posUser = username.index(inuser)
Pass = password[posUser]
if Tries == 3:
print("You have had too many attempts. Wait 60 seconds before trying again")
for i in range(60, 0, -1):
time.sleep(1)
print(i)
Tries = 0
inuser=str("0")
inuser=str("0")
if Pass == inpass:
success=1
elif Pass != "":
Tries += 1
AttemptsLeft = (3 - Tries)+ 1
print("Your password is wrong. You have only {} attempts left.".format(AttemptsLeft))
login()
if success==1:
print("Welcome to ------")
You should also consider getting rid of the global variables. Instead, return values using return.
import time
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
success = 0
Tries = 0
Valid = False
Pass = ""
def login():
success = 0
Pass = ""
Tries = 0
while success != 1:
inuser = input(str("Enter your username: \n"))
inpass = input(str("Enter your password: \n"))
if inuser not in username:
print("username not found in directory")
else:
posUser = username.index(inuser)
Pass = password[posUser]
if Tries == 3:
print("You have had too many attempts. Wait 60 seconds before trying again")
for i in range(10, 0, -1):
time.sleep(1)
print(i)
Tries = 0
inuser=str("0")
inuser=str("0")
if Pass == inpass:
return True
elif Pass != "":
Tries += 1
AttemptsLeft = (3 - Tries)+ 1
print("Your password is wrong. You have only {} attempts left.".format(AttemptsLeft))
if login():
print("Welcome to ------")
Your code needed some refining. I also made a timer for stopping. Also, you should use getpass library to not show the password.
import time
import getpass
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
Tries = 1
def login():
global Tries
print("\n----------------- Login -----------------------\n")
inuser = input("Enter your username: ")
inpass = getpass.getpass("Enter your password: ")
if inuser not in username:
print(f"User {inuser} was not found.")
login()
else:
xindex=username.index(inuser)
passw=password[xindex]
if inpass==passw:
return True
else:
if Tries==3:
print("\nToo many attempts. Please wait for 60 seconds.")
for k in range(x,0,-1):
b=f"Time left: {k} Seconds"
print(b,end="\r")
time.sleep(1)
Tries=0
login()
else:
Tries+=1
print("\nWrong Password or Username.")
login()
x=login()
if x:
print("Welcome to ---------")
Others have provided the solution, I will try to provide the reasoning:
This is because of the recursion in line number 38 where you're calling the login function after setting Tries=0.
When the recursive call is made, the compiler puts the rest of the statements below it on hold (you can imagine all the below statements pushed to a stack to be executed later). The program counter now goes to the start of the function: Where you'll enter the right username and password, therefore it sets the success variable to 1. Now that your function has completed, the compiler had a set of pending statements before remember?
It goes and executes them. But in there, the value of the variable inpass is still the old, incorrect one and that is why it prints out Wrong password. You can understand this by printing out inpass just before the line
if Pass == inpass:
TlDr; Get rid of the recursion

The simplest way to check for UPPERCASES

Here, I am trying to validate a password and check to see if there are capitals and numbers in the password before saving it as a different variable. Using functions, is it possible for me to do so. The indents have changed on the format, so please help me with other aspects.
def length(long):
while len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
if password.isupper() = True:
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
This is what I have now done:
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
errors = []
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
bool Capcheck = False
bool DigCheck = False
while CapCheck = False or CapCheck = False:
length(password)
if not any(x.isupper() for x in password):
errors.append("Your password needs at least 1 capital.")
else:
CapCheck = True
break
if not any(x.islower() for x in password):
errors.append("......... Why?")
if not any(x.isdigit() for x in password):
errors.append("You need to have at least 1 digit")
else:
DigCheck = True
break
if errors:
print(" ".join(errors))
password = input("Please enter a stronger password")
Apparently there is an error with my boolean here, please help
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
Try using islower():
password.islower()
This returns True if there are no Uppercases in the password.
Now if you want to check if it has number i it, you have to follow #jubnvz:
any(i.isdigit() for i in password)
or a more specific way:
any(map(str.isdigit, password))
And for your password entries, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
break
If you want to and a confirm password too, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
passwordcon = input(""Please confirm your password:")
if passwordcon == password:
break
else:
print("Your passwords do not match, try again'")
any([p.isupper() for p in password])

How to fix unknown login after multiple atemps

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

Python Intended Block error

I am sorry but i have a problem that i dont understand...
def login_screen():
print(30 * "-")
print(" LOGIN")
print(30 * "-")
username = print("Please enter your username: ")
password = print("Please enter your password: ")
with open('logins.txt', 'r') as csvfile:
loginreader = csv.reader(csvfile, delimiter=',', quotechar= None)
for codes in loginreader:
if len(codes) == L_LEN:
if codes[L_USERNAME] == username and codes[L_PASSWORD] == password and codes[L_ADMIN] == "Yes":
admin_console()
elif username == row[L_USERNAME] and password == row[PASSWORD] and row[L_ADMIN] == "No":
#Temp normal console here
else:
clearscreen()
error_head()
print("Unknown account")
input("Press [ENTER] To continue...")
login_screen()
elif len(codes) != M_LEN:
next(csvfile, None)
So the problem is that it comes with the following error:
File "G:\Python\DatabaseStandardRewrite\Login.py", line 49
else:
^
IndentationError: expected an indented block
But i dont get it! (Yes, all the other things are defined in the rest of the document!
Does anyone of you see my mistake?
Natan
Python does not permit blocks to be empty; you need at least one statement, and a comment does not count. So in the elif block before your else, you should put pass.
elif username == row[L_USERNAME] and password == row[PASSWORD] and row[L_ADMIN] == "No":
#Temp normal console here
pass
else:
clearscreen()

In python how can I have 2 loops where the second one returns to the first one once a given condition is met?

I am new to programming, and for fun i thought i would create a login/register system that works through the terminal with inputs. My problem is I have 2 while loops, and they both check to see if a variable called loggedin is equal to true or false. When you login during the first loop, It sets loggedin equal to True so that the second loop will start, but if you logout during the second loop, I want it to return you to the first loop where it asks you to login or register. I tried to accomplish this by having it so when you input logout it sets the logginin variable equal to false, hence bringing you back to the first loop, but instead it just quits the program! People have told me to use functions, but I am not sure how to implement this into my program. Thank you for any help you can offer me.
import time
loggedin = False
users = {}
mail = {}
print("Welcome to the network\nIf you have an account, type login\nIf you have no account, type register.\n")
while loggedin == False:
option = input("register/login > ")
if option.lower() != "login" and option.lower() != "register":
print("That is not an option")
elif option == "register":
print("REGISTER\nType in your new username")
while True:
newusername = input("> ")
if len(newusername) > 0 and newusername.isalpha():
break
else:
print("This is not a valid username")
while True:
print("Type in your new password")
newpassword = input("> ")
if len(newpassword) > 0 and newpassword.isalpha():
print("Account has been created")
users[str(newusername)] = str(newpassword)
mail[newusername] = []
break
else:
print("This is not a valid password")
else:
print("Type your username")
while True:
username = input("> ")
if str(username) in users:
break
else:
print("Username not found")
print("Type your password")
while True:
password = input("> ")
if str(password) == users[username]:
time.sleep(1)
print("Password correct")
print("Logging in")
loggedin = True
break
else:
print("Password incorrect")
print("Welcome to your account " + username)
print("OPTIONS: view mail | send mail | logout")
while loggedin == True:
option = input("> ")
if option.lower() != "view mail" and option.lower() != "send mail" and option.lower() != "logout":
print("Invalid option")
elif option == "send mail":
while True:
print("Type the username of the person you would like to send mail to")
recipient = input("> ")
if str(recipient) not in mail:
print("There is no one with that username!")
break
else:
print("Enter subject")
subject = input("> ")
print("Enter context")
context = input("> ")
sender = username
mail[recipient] = ["Sent from: " + str(sender),"Subject: " + str(subject),"Context" + str(context)]
time.pause(1)
print("Mail has been sent!")
break
elif option == "view mail":
print("Current mail")
print(mail)
else:
print("Logging out")
loggedin = False
When you want a loop to return somewhere else, it is usually an indicator, that you'd better use a function instead ;)
Ok, here is an updated code:
import time
def readUsername():
while True:
newusername = input("> ")
if len(newusername) > 0 and newusername.isalpha():
return newusername
else:
print("This is not a valid username")
continue
def registerUser(username):
while True:
print("Type in your new password")
newpassword = input("> ")
if len(newpassword) > 0 and newpassword.isalpha():
print("Account has been created")
users[str(username)] = str(newpassword)
mail[username] = []
break
else:
print("This is not a valid password")
loggedin = False
users = {}
mail = {}
print("Welcome to the network\nIf you have an account, type login\nIf you have no account, type register.\n")
while loggedin == False:
option = input("register/login > ")
if option.lower() != "login" and option.lower() != "register":
print("That is not an option")
elif option == "register":
print("REGISTER\nType in your new username")
newusername = readUsername()
registerUser(newusername)
else:
....
"Return to the first" is just another loop:
while True:
while not loggedIn:
# do login/register
while loggedIn:
# do other stuff

Categories