This is the part of my code that doesn't work. The else statement works fine but when the password is wrong the program just closes abruptly.
if logged_in == 'admin':
tries = -3
while tries < 0:
password = input("enter supersecret password. ")
if password != 'strange alien colour':
print("incorrect password. Try again. " + tries + " tries left.")
tries = tries + i
else:
print("Hello admin, would you like to see a status report?")
input()
import sys
sys.exit(0)
This is the entire code:
users = ['anonymous', 'me', 'bill', 'me123']
i = 1
while i == 1:
logged_in = input("Username:\n")
if logged_in == 'admin':
tries = -3
while tries < 0:
password = input("enter supersecret password. ")
if password != 'strange alien colour':
print("incorrect password. Try again. " + tries + " tries left.")
tries = tries + i
else:
print("Hello admin, would you like to see a status report?")
input()
import sys
sys.exit(0)
if logged_in in users:
print ("Hello " + logged_in + ", welcome back!")
break
else:
print ("invalid username. Do you wish to create an account? (Y/N)\n")
create_account = input()
if create_account == 'Y' or create_account == 'y':
new_username = input("Enter new username: ")
print("You have creted a new account. Welcome, " + new_username)
users.append(new_username)
else:
print ("Goodbye.")
break
input()
Your error is that on this line
print("incorrect password. Try again. " + tries + " tries left.")
tries is an int, whereas the other parts are strings. As you cannot add these two types, you get an error which is
TypeError: must be str, not int
To fix this just change the line to
print("incorrect password. Try again. " + str(tries) + " tries left.")
On an unrelated note, it is usually recommended that imports are at the top of your program.
print("incorrect password. Try again. " + tries + " tries left.")
This is incorrect as tries is an integer and therefore cannot be concatenated with the two other parts in the quotation marks as they are strings and needs to be converted into a string first to do so. eg.
print("incorrect password. Try again. " + str(tries) + " tries left.")
Related
The code is meant to be a simple login code that saves the login information to a .txt file and then when logging in reads the text file to check the user details.
The code runs up until I create an account or try to login and put in my username and password then it comes back with None. I don't understand why it's coming back with None
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
loginexisting()
elif account == "N":
createacc()
else:
print("please type Y or N")
AskAccount()
def loginexisting():
print("Your account already exists, please login\n")
username = input("Please enter your username:")
password = input("Please enter your password:")
f = open('accounts.txt', 'r')
info = f.read()
info = info.split()
if username in info:
index= info.index(username) +1
usr_password = info[index]
if usr_password == password:
return "Welcome Back," + username
else:
return "password entered is wrong"
else:
print("Username is not correct")
print(createacc())
def createacc():
print("Lets create an account for you\n")
username = input("Please input your username:\n")
password = input("please input your password\n")
f = open("accounts.txt",'r')
info = f.read()
if username in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("accounts.txt",'w')
info = info + " " + username + " " + password
f.write(info)
f.close()
print("Your account details have been saved\n")
print("please login\n")
print(AskAccount())
At the end of your file, you print(AskAccount()). This prints the return value of the function, but AskAccount does not have a return statement, thus it returns None. If you want it to print your desired output, you will need to add return statements.
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
return loginexisting()
elif account == "N":
return createacc()
else:
print("please type Y or N")
return AskAccount()
password = "nothing"
tries = 0
while password != "secret":
tries = tries + 1
password = input("What is the secret password? ")
print("sorry, please try again. ")
if tries == 3:
print("You have been locked out")
exit()
print("Correct! Enter the maze!")
when i write the correct password i get this in return
What is the secret password? secret.
sorry, please try again.
Correct! Enter the maze
Python has no do-while, so one of ways to do similar thing is
password = ""
tries = 0
while True:
password = input("What is the secret password? ")
if password == "secret":
break
print("sorry, please try again. ")
tries += 1
if tries == 3:
print("You have been locked out")
exit()
print("Correct! Enter the maze!")
You can use this code:
password = "nothing"
tries = 0
while password != "secret":
tries = tries + 1
password = input("What is the secret password? ")
if password == "secret":
break
else:
print("sorry, please try again. ")
if tries == 3:
print("You have been locked out")
exit()
print("Correct! Enter the maze!")
If you do not want the password to be seen, you can use the following library
getpass()
example:
import getpass
p = getpass.getpass(prompt='What is the secret password? ')
if p.lower() == 'secret':
print('Correct! Enter the maze!')
else:
print('sorry, please try again.')
I have wrote this simple login and registartion program:
import os
from os import path
def start():
startup = input ('are you an existing user? y/n : ')
if startup == "y":
print ("Lets login then")
login()
if startup == "n":
print ("Lets make you an account")
new_account()
else:
print ("That is an invalid input, please try again")
start()
def new_account():
new_username = input ('what do you want your username to be? ')
print ('okay...')
new_pass = input ('your new password... ')
checker_pass = input ('retype it... ')
if new_pass == checker_pass:
print ('you have entered correct passwords')
print ('Now please login ')
print (' ')
print ('..................................')
print (' ')
saveFile = open( new_username + '.txt','w')
saveFile.write(new_pass)
saveFile.close()
login()
else:
print ('you have done something wrong. Please start again')
new_account()
def login():
print (' ')
print ('..................................')
print ("")
user_name = input ('enter username: ')
file_check = path.exists(user_name + '.txt')
if file_check == False:
print ("That username dosent exist, please start again")
start()
if file_check == True:
Pass_check = open(user_name + '.txt' , 'r').read()
password = input ('enter your password: ')
if Pass_check != password:
print('That didnt quite match. Please start again')
start()
elif Pass_check == password:
print ('Welcome to your account.')
start()
once i have entered a valid username or password it then says:
That is an invalid input, please try again
are you an existing user? y/n :
this is part of the program but isnt supposed to occur once you have been welcomed to your account.
has anyone got a soulution so that once you recieve "welcome to your account" nothing else happens.
i would like it done so that the program dosent fully stop as im looking to put this code into another program.
thanks fin.
THE OUTPUT:
are you an existing user? y/n : y
Lets login then
..................................
enter username: finndude
enter your password: test
Welcome to your account.
That is an invalid input, please try again
are you an existing user? y/n :
i dont want the last two lines to appear
Add a boolean flag value to the start() function that says whether to display the line or not. When calling from login() pass True, when calling recursively from start() then pass False.
Hey I have wrote this code however I cannot see what is wrong with it, it is saying that the username is wrong yet if I print it, it returns exactly what i input.
ea = input("Do you already have an account")
if ea == "Yes" or ea == "yes":
Ausername = input("Input your username")
Apassword = input("Input your password")
f=open("login.txt","r")
lines=f.readlines()
username=lines[0]
if (Ausername) == (username):
print("Welcome to the quiz")
else:
print("Access denied")
f.close()
else:
name = input("Input your name")
yeargroup = input("Input your year group")
age = str(input("Input your age"))
firstusername = ((name[0]+name[1]+name[2])+(age))
print((firstusername)+(" is your username"))
firstpassword = input("Enter what you want your password to be")
print(firstusername)
print(firstpassword)
login = open("login.txt","a")
login.write(firstusername + "\n" + name + "\n" + yeargroup + "\n" + age + "\n" + firstpassword + "\n")
login.close()
print("---------------------------------------------------")
File data is read in by default with the trailing newline. Did you try calling str.strip before comparing your strings?
if Ausername == username.strip():
...
Also, if you want to do case insensitive comparisons, you should convert your string to lowercase using str.lower to reduce the size of your search space:
if ea.lower() == "yes":
...
I am writing a program that asks the user to enter a password. If the password matches the constant I've set it prints out a "successfully logged in message". However if the password is incorrect, it gives the number of guesses left and asks the user to try again. The program should end after 3 incorrect guesses but it keeps on asking even after 3 attempts have been used. I think the problem is in my while loop but I am unsure.
Code:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
Right now you never exit your while loop. To break out of it, use the break keyword.
To exit your program completely, you will need to import sys and sys.exit()
I suggest adding these to your if ALLOWED == 0 statement.
You need to use break to exit the loop, or add a secondary condition, otherwise it will keep going anyway until the password is correct.
So, either:
while (password != PASSWORD) and (ALLOWED > 0):
Or:
if ALLOWED == 0:
print("You have been locked out")
break
The condition password != PASSWORD is not enough to exit the loop (It will exit the loop only if you give the right password). Add the condition also in while (password != PASSWORD and ALLOWED > 0)
Change print("You have been locked out") to sys.exit("You have been locked out") (or otherwise exit the main). Remember to import sys to use sys.exit.
Your while loop requires a correct password to finish, and there is no other way to exit the loop. I suggest a break statement:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
break
password = input("Enter again ")
print("You have successfully logged into the system")
You may want to do more research if your program needs to be secure.
Managed to make it work but just making it check if ALLOWED == 0 and if it does print "you are locked out", and if ALLOWED <= 0 then it will not let you go any further.
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD or ALLOWED <= 0:
ALLOWED = ALLOWED - 1
if ALLOWED > 0: print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0: print("You have been locked out")
if ALLOWED < 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
also wrote a different version which seemed easier in my opinion
def main():
USERNAME = "admin"
PASSWORD = "root"
ATTEMPTS = 3
while ATTEMPTS >= 1:
print("You have",ATTEMPTS,"attempts left")
if ATTEMPTS == 0:
break
user = input("Please enter your username:")
password = input("Now enter your password:")
if user == USERNAME and password == PASSWORD:
print("\nYou have successfully logged into the system")
return
else:
print("\nThis user name or password does not exist\n")
ATTEMPTS -= 1
print("you have been locked out.")
main()