I am a total amateur when it comes to python and I have came across an issue:
if input() == existingUsername:
print('Sorry, that username is taken, please try again:')
However, I need to access exisingUsername before it is declared, because I've defined it at the bottom of my code. I know you can do this in javascript with the let variable, but how can I do it in python?:
let existingUsername;
//code
existingUsername = 'name'
You can't use a variable before declaring it.
You could however use an empty string:
existingUsername = ""
# .
# .
# the rest of your program
# .
# .
username = input()
if username == existingUsername:
print('Sorry, that username is taken, please try again:')
else:
# assign new username here
existingUsername = username
Related
I'm making a account login system in python by having the username and password stored in a separate file and the program access it, then read the password and compare it with what the user has entered. It can read the password in the file but for some reason when it compares it to what the user has entered, it always says it's wrong.
I've tried comparing the actual password to the user's input and I know it's reading the file right as I made it print out what it read and it printed the correct password. I've also made it print the user's input to make sure that's right and that was working too.
Just so you know, the file already exists which contains the password on the second line and it finds the right file as the file is named after the account that it's for.
Account = str(input("Enter the username. "))
Account_Password = str(input("Enter the password. "))
AccountFileName = (Account + ".txt")
with open(AccountFileName,"r") as AF:
for x, line in enumerate(AF):
if x == 1:
Account_Password_Check = (line)
if Account_Password == Account_Password_Check:
print("Welcome, " + Account + "!")
else:
print("Either the username or password were incorrect.")
If the user input is the same as the password, it should print, "Welcome (username here)!" and if they're different then it should print, "Either the username or password were incorrect."
If you know what's wrong, please let me know.
Thanks.
In comments to your question, you will find the first reason why it doesn't work, but:
for x, line in enumerate(AF):
if x == 1:
Account_Password_Check = (line)
Is also not fully correct, enumerate start count from zero, but condition checks 1 line, it means that you will compare your current user password from previous. The correct version will be
for x, line in enumerate(AF):
if x == 0:
Account_Password_Check = line.strip()
break
When trying to run my program I get the error that the continue function is out of the loop.
As I have checked my syntax I don't know what is the problem, and when trying to indent I get an error for indenting too much.
while True:
print('What is your username')
name = input()
if name != 'Banana': # Username doesn't have to be equal to
continue # If the username is correct they will pass on the next question
print('Hello, Banana. What is the password? (It is a dog') # How would I put a real hint
password = input() # Input password
if password == 'AkitadaMonsta':
break # They don't have to start over again
print('Access granted.') # Allowing them in
This is further to an issue I asked about on here yesterday What is the best way to validate user input against the contents of a list?). I got a good suggestion using a function like so:
getuser = input("Please enter your username :")
print("1. render_device")
print("2. audit_device")
askuser = input("Would you like to render_device or audit_device? : ")
def verify_input(sites_set):
get_site_name = input("Please enter the site name you'd like to render :")
if get_site_name in sites_set:
print('Proceed')
return
else:
print('Not in either list, please enter a valid site')
verify_input(sites_set)
if askuser == "1":
sites_2017 = ["bob", "joe", "charlie"]
sites_2018 = ["sarah", "kelly", "christine"]
verify_input(set(sites_2017 + sites_2018))
This works correctly within the function and when it is called. However, the issue is that I need get_site_name as a global variable since its input is referenced later in the script (not in a function). When I make get_site_name global, the function can reference it and works correctly when a valid site is input, but when an invalid site is input it just keeps looping the "Not in either list" error over and over, probably because the raw_input in the get_site_name variable isn't defined locally.
What would be the best way to remedy this?
What about:
def verify_input(sites_set):
while get_site_name not in sites_set:
get_site_name = input("Please enter the site name you'd like to render :")
print('Proceed')
return
The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.
Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).
import pickle
import time
def loaddict():
try:
with open("dictAcc.txt", "rb") as pkf:
return pickle.load(pkf)
except IOError:
with open("dictAcc.txt", "w+") as pkf:
pickle.dump(dict(), pkf)
return dict()
def savedict(dictAcc):
with open("dictAcc.txt", "wb") as pkf:
pickle.dump(dictAcc, pkf)
def userPass():
dictAcc = loaddict() #Load the dict
checkAccount = raw_input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = raw_input("Please Set Your New Username: ")
password = raw_input("Please Set Your New Password: ")
if (userName in dictAcc):
print("Username is taken")
userPass()
else:
dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
savedict(dictAcc) #Save the dict
time.sleep(1.5)
# dataInput() Code ends
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = raw_input("Type in your Username: ")
loginPass = raw_input("Type in your Password: ")
dictAcc = loaddict() #Load the dict
if (tries < 3):
for key in dictAcc:
if (loginUserName == key and loginPass == dictAcc[key]):
print("You have successfully logged in!")
# dataInput() Code ends
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(3)
tries=1 #To restart the tries counter
login()
global tries
tries=1
userPass()
There are different ways to do this. I'll mention two.
As you noticed, all variables created by your program are erased when the program finishes executing.
One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.
However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.
You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.
How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.
Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.
So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.
A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.
I am new to programming and am wondering if this is possible. I am trying to create a password protected script, where the password is entered once and then required to progress the script the next time the script is opened. I am storing and encrypting the password in a file, and then checking to see if the file exists the next time the script is opened. The problem I am running into is checking to see if the passwords match, since the original password is in a function as a local variable.
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = encrypt(pw, 10) #encodes the string with a key in a seperate encrypt function
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
#I can not check pwCheck == pw since pw is a local var.
#progression of script here
else:
createFile()
I know that it is considered bad for to make a local variable global. Is there a way to restructure what I have so far to make this work? As I wrote this, I think I may have came up with a possible solution but I do not have time to test it now. Do I run the same encrypt function with the same key for pwCheck and then check if it is == to the first line of PW.txt? Is that correct and/or are there other solutions?
Thank you.
Using Windows, Python 3.4
Instead of "encrypt", perhaps use a 1-way hash.. Then, you can hash the subsequently entered password and check it versus the hash stored in the file... Something like:
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = sha.new(pw).digest
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
previous = open('PW.txt', 'r')
prevPass = previous.read()
hashed = sha.new(pwCheck).digest()
if (hashed==prevPass):
#progression of script here
else:
createFile()
I really hope that this is just an exercise, because if you care about security, you should be using some other authentication mechanism to gate access. Most obviously, unix permissions, and sudo to gate access.
Assuming it is an exercise only, simply have a function which checks the input against the file. Something like:
def doAuth():
isAuthed = getPassInput() == getPassFromFile()
if isAuthed:
return True
else:
raise HellNoException("Passwords differ")