Brand new to coding in python and coding in general - python

I am tinkering with some code online and stumbled upon this one :
import os
import time
#Must Access this to continue.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()
I am trying to make it so after the username and password has been implemented, that this sequence happens next:
def mainname():
while True:
Firstname = input("Enter First Name:")
Lastname = input("Enter Last Name:")
if Firstname == 'Cher, Madonna':
time.sleep(2)
print("May I have your autograph, please?")
else:
print("that's a nice name")
mainname()
But what happens is, after I put in the username and password it then loops back to inputting the username and password. How do I make it so after the username and password has been implemented, then it goes to the first name and last name sequence? Thank you very much for the help

The code that checks the password is in a while True: loop, so it will keep looping and asking for the password regardless.
You want to break out of the loop on success, so add a break after you successfully log in.

Right after you have confirmed that the password is correct just add break. This will end the while loop as the correct username and password is entered.

Related

How can I pass a variable to a function without continuing with the original function it was called from in Python?

I am not an expert when it comes to Python and I am trying to put several functions together to do the following:
Ask for a name, if it exists, ask for a password and if it is correct, provide access
If the name is incorrect, ask the user to either change it or register
When registering, I want to call another function to check the validity of the password (Password Checker) and then jump back to the rest of the userRegistration function, if the password is strong enough.
However, even when I provide a new password that is too short or long, it will jump back into the original function and execute the rest of the code. I know that the code is not yet finished, but I know that I am not doing it correctly. Any advice, please? Also, when it comes to the final failed attempt for providing the password/username and I want the application to say "Too many attempts", where would be the best place to put it?
The rest of the code pretty much works as expected under ideal conditions (hashing, OTP, SQL, ...)
Here is my code so far:
import sqlite3
import hashlib
import pyotp
import sys
from password_validator import PasswordValidator
connection = sqlite3.connect("localDB.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE passwords")
cursor.execute("CREATE TABLE passwords (name, password)")
cursor.execute("INSERT INTO passwords VALUES ('Tomas','password123')")
def OTP():
totp = pyotp.TOTP('base32secret3232')
print("This is your one-time passcode: ")
print(totp.now())
userOTP = input("Please provided your passcode: ")
otpass = totp.verify(userOTP)
if otpass == True:
print("You are now logged in")
sys.exit()
else:
print("Access Forbidden")
sys.exit()
def correctUsername(username):
print("Account found, please provide your password: ")
retry = 0
while retry<3:
userPassword = input()
cursor.execute('SELECT password FROM passwords WHERE name=?', [username])
match = cursor.fetchone()
dbPassword = match[0]
# print(dbPassword)
hashedCorrectPassword = hashlib.sha256(str(dbPassword).encode('utf-8')).hexdigest()
hashedInputPassword = hashlib.sha256(str(userPassword).encode('utf-8')).hexdigest()
#print(hashedCorrectPassword)
#print(hashedInputPassword)
try:
if hashedInputPassword == hashedCorrectPassword:
print("That's correct, welcome.")
OTP()
else:
print("That's incorrect, please try again.")
retry += 1
continue
except:
break
print("Maximum tries exceeded")
def passwordValidator(registrationPassword):
schema = PasswordValidator()
schema.min(8)
schema.max(15)
schema.has().uppercase()
schema.has().lowercase()
validatePassword = schema.validate(registrationPassword)
if validatePassword == True:
print("Good password")
else:
print("Try again - not strong enough")
def userRegistration():
compliance = bool
print("Register here")
registrationName = input("What is your name?")
print("Your name is ", registrationName)
registrationPassword = input("What is your password?")
passwordValidator(registrationPassword)
cursor.execute("INSERT INTO passwords VALUES (?,?)",(registrationName, registrationPassword))
print("User successfully registered, please login with your new details: ")
passwordDatabase()
def passwordDatabase():
print("Please enter your username: ")
retry = 0
while retry<3:
try:
username = input()
if username == "YES":
userRegistration()
else:
cursor.execute('SELECT name FROM passwords WHERE name=?', [username])
match = cursor.fetchone()
if match is None:
print("No account found, please try again, or type YES for registration")
retry += 1
continue
else:
correctUsername(username)
break
except:
break
print("Maximum tries exceeded.")
One option is to make passwordValidator both ask for and return the password. The key step here though is to put this asking process in a loop. Something like this
def passwordValidator():
while True:
valid_password = True
password = input("What is your password?")
#
#
# validation steps here, if it is invalid, set valid_password to False
if valid_password:
return password
If an invalid password is entered, the while loop will continue and the user will be prompted again to input a password.
Then you can do
def userRegistration():
compliance = bool
print("Register here")
registrationName = input("What is your name?")
print("Your name is ", registrationName)
registrationPassword = passwordValidator(registrationPassword)
cursor.execute("INSERT INTO passwords VALUES (?,?)",(registrationName, registrationPassword))
print("User successfully registered, please login with your new details: ")
passwordDatabase()

Repeating until done

So Ive got this code and I want to make it repeat itself until the user makes his username not start with a symbol or number.
name=name.capitalize()
print(name)
surname= input("surname")
surname=surname.capitalize()
print(surname)
password= input("password")
username= input("username")
first_char = username[0]
if first_char.isalpha():
print('done')
else: print('username must start with a letter')
I haven't tested this code, but it seems like all you need is a simple while loop like so:
surname = input("surname")
while not surname[0].isalpha():
print("surname must start with a letter")
surname = input("surname")
If you are using python 3.8, you can use the := operator for a nice way to write this:
while not (username := input("username: "))[0].isalpha():
print('username must start with a letter')
# do stuff
Otherwise your choices are going to be:
(a) Repeat a line of code
username = input("username: ")
while not username[0].isalpha():
print('username must start with a letter')
username = input("username: ")
# do stuff
or (b) Use an infinite look with a break:
while True:
username = input("username: ")
if username[0].isalpha():
break
print('username must start with a letter')
# do stuff
You are close:
name = input("Name:").capitalize()
print(name)
surname = input("Surname:").capitalize()
password = input("Password:")
username = input("Username:")
while not username[0].isalpha():
print('Done')
Alternative:
name, surname, password, username = input("Name:").capitalize(), input('Surname:').capitalize(), input('Password'), input('Username')
while not username[0].isalpha():
print('Username must start with a letter')
print('Done')

How to make my code break out of loop and actually detect a certain input

I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break

My python login program won't compare separate lines in a text file to the persons inputs

I want my login program to take a username and password input from the user, and then check it to see if it is the same to the usernames and passwords as in the files. However, the code isn't working and I think I'm missing something:
def login():
with open("username.txt","r") as username:
usrn_read = username.read()
username.close()
with open("password.txt","r") as password:
passw_read = password.read()
password.close()
inp_usern = input("Username: ")
inp_passw = input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable.open("database.txt","a")
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def end():
print("Thankyou!")
def forward():
print("This would continue to quiz!")
login()
Any help would be appreciated!
Username file
bob12
alexi90
john08
UPDATE
With the code below it works, but only on the first line of the text file:
def login():
username = open("username.txt","r")
usrn_read = username.readline().replace('\n', '')
username.close()
password = open("password.txt","r")
passw_read = password.readline().replace('\n', '')
username.close()
inp_usern = input("Username: ")
inp_passw = input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable = open("database.txt","a")
variable.write("\n Login succesful for: "+inp_usern)
variable.write(" Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def forward():
print("This would continue to quiz!")
login()
And here are the files (first is username, second is password, and they are separate files):
bob12
alexi90
bob00
alexi00
Now that it can read the first line separately from the other lines of the file, how do I get it to read the other lines separately as well? Thank you!
One small observation: if you are opening your file with context manager, you dont have to worry abt closing it.Thats the beauty of it
with open("file1.txt", "r") as filename
Your actions
Get rid of those two file.close() statements
Going forward it is a good idea to dump the input files and the error messages you saw when you submit the question to SO.
Based on my investigation two things are happening:
The first more important one is the usage of input. When you use input, python actually tries to evaluate the inputted value. So you should have seen an error like this:
Username: ababababbaba
NameError: "name 'ababababbaba' is not defined"
To fix this, use raw_input instead and you should no longer have this problem. See this SO answer here for more details https://stackoverflow.com/a/4960216/4765841
The second potential problem depends on what the contents of the input file (username.txt and password.txt). If you have a new line character (\n) then when you read the line you would actually get 'myusername\n' which will not match the user's input of myusername. To fix this, you must strip the \n from the string before saving it to your usrn_read and passw_read variables.
This is what the whole thing should look like now:
def login():
with open("username.txt","r") as username:
usrn_read = username.read().strip("\n")
username.close()
with open("password.txt","r") as password:
passw_read = password.read().strip("\n")
password.close()
inp_usern = raw_input("Username: ")
inp_passw = raw_input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable.open("database.txt","a")
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def end():
print("Thankyou!")
def forward():
print("This would continue to quiz!")
login()
Addendum, this answer assumes that variable.open is valid. Otherwise I think you need to change that line to:
with open("database.txt","a") as variable:
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
i'm working on python 2.7
i used raw_input instead of input -> refer to this What's the difference between raw_input() and input() in python3.x?
also the variable "variable" needed to be assigned first
def login():
with open("username.txt","r") as username:
usrn_read = username.read()
username.close()
with open("password.txt","r") as password:
passw_read = password.read()
password.close()
inp_usern = raw_input("Username: ")
inp_passw = raw_input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable = open("database.txt","a")
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def end():
print("Thankyou!")
def forward():
print("This would continue to quiz!")
login()
Because the username/password does not equal the three lines of the file combined.
bob12
alexi90
john08
You need to split the file into separate parts: bob12, alexi90, john08, on the \n. Then, throw it away: .replace('\n', '').

How to make the user exit the program on a passowrd program in python

Can someone try to help me make with this, please. So once the user guesses 3 times the entire program closes, but once the user gets it wrong it doesn't make them exit the program. Yes I'm aware that I'm asking the same question again but I haven't got my question answered yet so please can someone help.
Here's another one I'm trying out. Any Suggestions on how to do exit the program if the user gets a certain number of attempts by trying to guess the password wrong. I've been trying to use sys.exit and exit()but it hasn't been working for me, so maybe you can try to that , (but remember my teacher wants it so that it on IDLE).
Counter=1
Password=("Test")
Password=input("Enter Password: ")
if Password == "Test":
print("Successful Login")
while Password != "Test":
Password=input("Enter Password: ")
Counter=Counter+1
if Counter == 3:
print("Locked Out: ")
break
counter = 1
password = input("Enter password: ")
while True:
if counter == 3:
print("Locked out")
exit()
elif password == "Test":
print("That is the correct password!")
break
else:
password = input("Wrong password, try again: ")
counter += 1
Move your counter check into the while loop.
Also use getpass for getting password input in python :)
import sys
import getpass
counter = 1
password = getpass.getpass("Enter Password: ")
while password != "Test":
counter = counter + 1
password = getpass.getpass("Incorrect, try again: ")
if counter == 3:
print("Locked Out")
sys.exit(1)
print("Logged on!")
You need to move the condition counter==3 inside the while loop
This can also be done in this way
import sys
password = input("Enter password : ")
for __ in range(2): # loop thrice
if (password=="Test"):
break #user has enterd correct password so break
password = input("Incorrect, try again : ")
else:
print ("Locked out")
sys.exit(1)
#You can put your normal code that is supposed to be
# executed after the correct password is entered
print ("Correct password is entered :)")
#Do whatever you want here
An even better way is to wrap this password-checking thing into a function.
import sys
def checkPassword():
password = input("Enter password : ")
for __ in range(2):
if (password=="Test"):
return True
password = input("Incorrect, try again : ")
else:
print ("Locked out")
return False
if (checkPassword()):
#continue doing you main thing
print ("Correct password entered successfully")

Categories