first post here on stack overflow :D
Firstly, at school currently i'm working on a little door entry system and most of the code (only short maybe 30 lines max) is at the school pc - however ive just downloaded Anaconda because i cant get python to download and im using Spyder,
And im trying to sort out a little error im getting so i can fix it at school, pretty much i want to allow the user to enter a code that will be stored into the 'code' variable and then if the 'code' is in the 'database' variable the door will open if not it'll tell you access is denied and loop the program for the next person/next attempt - What i have here to post is the bare minimum of my program but its pretty much the part im struggling with - i have had the program working multiple times with the codes being presented seperately but im looking on making them into a list instead for easier usability - and its a challenge thats been set
while True:
code = input ('Please enter your user ID ')
database = ['001','002','003']
if code == database:
print ('access granted')
else:
print ('Acess denied')
Thats my code so far :D
You want in not ==:
database = ['001','002','003'] # create once
while True:
code = input('Please enter your user ID ')
if code in database:
print ('access granted')
break # break if code is in our list
print ('Access denied') # or print access denied and ask again
You are currently comparing a list to a string as in if "001" == ['001','002','003'] etc.., in tests for membership as in is this element contained in my list.
On another note for small datasets it is irrelevant but when doing a lookup over larger sized datasets using a set is a very efficient way to test for membership:
database = {'001','002','003'} # set literal
If you don't want to break an are not validating forget the while and just ask the user once:
def get_access(db):
code = input('Please enter your user ID ')
if code in db:
print('access granted')
return True
print('Access denied') # or print access denied and ask again
return False
Then to use the function:
database = {'001','002','003'}
granted = get_access(db)
if granted:
.............
If you do want to loop indefinitely you need the else:
while True:
code = input('Please enter your user ID '):
if code in db:
print('access granted')
else:
print('Access denied')
Here is my version:-
database = ('001', '002', '003')
while input('Please enter your user ID ') not in database:
print ('Acess denied')
print ('access granted')
As the other answer said you need to be testing if the input is in (or not in) the database list.
Related
I am trying to make a login script check for a verified email the check script is
#check for verification
while True:
if "'emailVerified': True" in accountinfo:
break
else:
print("Your email has not been verified! Please verify it with the new link we have sent.")
auth.send_email_verification(user['idToken'])
menu()
The value in the table I am trying to find is
'emailVerified': True
It keeps saying it can not find it though the value is there. How do I make it look for that? Am I doing it wrong?
It looks like you are trying to use the string "'emailVerified': True" as a key to the accountinfo dictionary object (representing an account's info I think).
The think the best way to do it would be to do this:
while True:
if accountinfo['users'][0]['emailVerified']:
break
else:
print("Your email has not been verified! Please verify it with the new link we have sent.")
auth.send_email_verification(user['idToken'])
menu()
Although this is quite bad and the structure of your accountinfo object is convoluted. I think you should either split it up into two objects or just unpack the lists into key value pairs for the entire accountinfo object. I would avoid having to use [0] (or having to use [i]) to index the List within the dictionary object, which has ANOTHER dictionary in it! That is very confusing hierarchy of python objects.
You should try to change the accountinfo object to allow this:
while True:
if accountinfo['emailVerified']:
break
else:
print("Your email has not been verified! Please verify it with the new link we have sent.")
auth.send_email_verification(user['idToken'])
menu()
Your user validation logic is not very clear. But if you simply ask why emailVerified: True is in accountinfo, but if "'emailVerified': True" in accountinfo always gets False. The answer is they are different types. The left is a string, the right is a dictionary(or json).
Can you try this function:
def is_any_user_email_verified(accountinfo):
return any(u for u in accountinfo['users'] if u['emailVerified'])
# usage:
if is_any_user_email_verified(accountinfo):
break
I'm trying to create a personnal password vault. Basically I want to create a program that asks me what I want to do and depending on my input (New, or Access "title of website here") the program either lets me add a website title with it's corresponding username and password. Then in I type "Access..." i should get the username and password returned relative to the website's tite I input after the Access input. OFC all of this data is to be stored in a text file.
PROBLEM:
The problem is that when I check the text file, it stays blank. I tried changing the access mode (a, r, etc) and it doesn't work. Not only that, but the program returns only the last data entered, and not whichever data in select.
Keep in mind I'm a beginner.
Below is the code used:
vault = open("Passvault.txt", "a")
total = True
while total == True:
creation = True
action = input("What do you want to do? ")
if action == "New" or action == "new":
title = input("Add website: ")
username = input("Create username: ")
password = input("Create password: ")
vault.write("Title:" + username)
vault.write("\n")
vault.write("Username:" + username)
vault.write("\n")
vault.write("Password:" + password)
elif action == "Access " + title:
print(title)
print("Username: " + username)
print("Password: " + password)
creation = False
elif action == "Close":
creation = False
total = False
vault.close()
First of all, you are not reading the file. Reading AND writing in 'append' ('a') mode is a bad idea (see potential cursor issues).
I tested the code on Google Colab and it works. Note that the writing occurs only if you close the file.
Suggestions:
It is a good time to learn about databases. Even a simple Excel file would fit your goal better (check package csv).
Use 'a+' as the mode of opening the file: if the file does not exist, create it.
Try to open and close the file a bit more frequently, say, each time when you want to write something. Also with clause may be useful (https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)
First of all, where do you define the variable title used in the elif condition. Another that how you are reading the file for title. Third and most important that your problem clearly mentions is that you are not seeing results being saved and that is because you don't close the file instantly and close method actually writes all data and saves the file in the end. Another way to save data before closing the file is by using the flush method.
Try this code:
vault = open("Passvault.txt", "a")
total = True
while total == True:
creation = True
action = input("What do you want to do? ")
if action.lower() == "new":
title = input("Add website: ")
username = input("Create username: ")
password = input("Create password: ")
vault.write("Title:" + username)
vault.write("\n")
vault.write("Username:" + username)
vault.write("\n")
vault.write("Password:" + password)
elif action == "Access " + title:
print(title)
print("Username: " + username)
print("Password: " + password)
creation = False
elif action == "Close":
creation = False
total = False
vault.close()
You didn't close the file at the end.
First of all you seem to be a bit confused how everything is working here so lets me clarify and then I will point out all the problems.
You first create a variable vault and assign it to file opened via append(a) mode.
Now append mode is used generally to append data, here you want to both read and write
data so you need to use read and write permission(r+).
Second , you are trying to create a vault and don't encrypt it any way. the problem is
that anyone can see it as a plain text by opening that file.
Now you set total to True and then use it for infinite while loop.
The problem here is that you can directly do while True so that loop continues
forever and you don't need to assign total a value of True because it doesn't need to
be changed as you can use break keyword to break out of loop. You just wasted memory
by assigning variable to True
Now inside the while loop, you create creation variable but never use it for a purpose, so it is I think not needed or you might have another plan and might use it in the future so I won't say about it.
Now you get input from the user and set it's value to action variable. This step is OK but I wan't to clarify that there are several security problems here but since they are very complex so I won't tell them here but this should be OK.
Now's the time of conditions:
Now in first if condition, you check is action == 'New or action == 'new', here you don't need to includeor` , although that's okay and there is no problem with it, you can do better. .lower() is a string method and it lower cases all the letters of the alphabet.
Either you can do if action.lower() in ['new' , 'create' , 'n' ....all inputs you want ] , note here you dont have to include '.....all inputs you want' , Its just to tell you that you need to put there all inputs on which you want the condition to be true.
Or you can simply do if action.lower() == 'new'
Now only if the condition is true this code runs
You create title variable and set it to user input, now here's too security problem but due to complexity I won't go into much deep. Always remember , wherever you have user interaction with application , there's a chance of security problem there.
Then you get the password and same problem. But also notice that you don't encrypt anything here. That's a big issue.
Now you write everything to the file but be aware that .write() doesn't write directly. You either have to call .flush() or close the file via .close() . But notice the problem , you called .close() but in the very end and out of the infinite while loop. You can tell that that close command is out of while loop by telling that both while loop and close are at the same level. If you have to put it inside while loop, you need to indent it a bit just like other code which is inside while loop. But that is also not gonna work because you close the file and you can't reuse it withot reopening it so either you put both open and close parts inside while loop or you use the .flush() method. This is the biggest bug due to which you are facing such a problem.
Now's the time of elif conditon
Here you see that in the condition you do if action == 'Access ' + title: and there are several problems here.
First you see that you directly compare action to access and you can do it better by using that list trich used in above if condition and can use .lower() method
Second that you use the title variable which notice only get defined when the above if condition runs. What if the above if condition doesn't run and what is the user directly said 'Access Google" or anything accept the above if condition such as "#^%&GJ" . Then elif condition will run and your variable title will not be found by python and then your program will crash. So it is better that you first search that if the input contains Access and the break it into Access And The keyword after it. There are several functions you can use like .strip() or others. Visit this link fore more methods.
Third, you are using the file cursor without being aware of it. Just like cursor in any text editor, the file handler also has a cursor which move foreward as you read the file and in the end it will reach the end of the file and once again you read , it wont return anything since there's nothing ahead of it. To know more about it, visit this link.
And these were the main problems due to which your code is not working correctly
There are also many more problems such as
Your way of reading from file
Your way of writing to the file
No error handling
Your way of closing the file
Your way of handling file
No encryptions
Security problems
Etc.
But for now, that's gonna help you in your task.
Good Luck And Smart Work!
For one of my assignments there's an offer for extra credit if we can add a new feature that the professor didn't already tell us to do in the assignment instructions. It's a password saver program and I'm saving websites/passwords to a list using a caeser cypher. I'm trying to create a password deletion feature that's based on user specific input.
For example, here's a random template list:
passwords = [["facebook", "gGjjI%%%66"], ["youtube", "coYtF###12$"]]
Let's say I wanted to delete the password in the passwords list for youtube. I've done some research and it appears that remove() may be a good choice for what I'm trying to do, but I'm having issues putting it into practice.
if choice == '6':
input("Enter the password you want to delete: ")
for keyvalue in passwords:
print(keyvalue[0])
deletePassword = input()
for i in range(len(passwords)):
if deletePassword in passwords[i][0]:
passwords.remove(deletePassword)
The issue here is, after I input the website name I want to delete the password for, like youtube in this case, after I hit enter, it reprints the list which still includes what I wanted to delete, and then if I hit enter again, it'll throw: ValueError: list.remove(x): x not in list
Any suggestions on how to fix this, or pointing me in the right direction on how to do this a better way?
Replace:
input("Enter the password you want to delete: ")
with
print("Enter the password you want to delete: ")
(you have two inputs, and you just drop the value of the first one)
You could try this:
deletePassword = input("Enter the password you want to delete: ")
passwords = [password for password in passwords if password[0] != deletePassword]
I am going to recommend you store the passwords as a dictionary, rather than a list of lists. This allows you to lookup/access the sites by name rather than numeric index (which gets changed with each modification to the list).
passwords = [["facebook", "gGjjI%%%66"], ["youtube", "coYtF###12$"]]
passwords = dict(passwords)
# passwords is now {'facebook': 'gGjjI%%%66', 'youtube': 'coYtF###12$'}
if choice == '6':
print("Enter the site name of the password you want to delete: ")
for site in passwords:
print(' ', site)
deletePassword = input('>')
if deletePassword in passwords:
passwords.pop(deletePassword)
This is a simple login program - the logic works in VB.Net but I cannot translate it into Python. The Python code does NOT work, however the VB.Net code provided by two users (un_lucky and Jerry) on Stackoverflow does. Can anyone point out a fix for the python code for me please? It basically produces a series of "Access Denied" instead of just one, when the password is incorrect, and if the username or password is the SECOND in the array, then it produces one Access Denied followed by an Access Granted.
count=0
for counter in range(0,len(fields)):
if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
count=count+1
if count > 0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
and here is the VB.net code (logic) that does work to achieve pretty much the same thing except that the python program above is reading from a text file.
It now works perfectly (nearly) but a blank entry in username and password also produces "Access Granted"...can't figure out why!
Whole code below:
def verifylogin():
fin=open("moosebook.txt","r")
data=fin.readlines()
for line in data:
fields=line.split()
fields=[i.rstrip("','") for i in fields] #strips the named character from END of field
fields=[i.replace("'",'') for i in fields]#when reading the list, you want to remoe the ',' so it isn't part of the username or password
fields=[i.replace("(",'') for i in fields] #simiarly, remove the bracket and replace it
fields=[i.replace(")",'') for i in fields] #simiarly, remove the bracket and replace it
line=line.rstrip()
print(fields)
flag=0
for counter in range(0,len(fields)):
if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
flag=flag+1
if flag>0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
Indentation is important in Python. You put your if test inside the loop. You need to remove the extra indentation to place it outside the loop:
for counter in range(0,len(fields)):
if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
count=count+1
if count > 0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
Note how the if and else lines now start at the same column as the for line.
Because in your code the if statement was indented to a deeper level (the same as the if test checking for the password) you created the labels multiple times, once for each run through the loop.
Indentation works to delimit blocks of code the same way that the VB.NET code uses Next and End If to delimit the loop and the conditional tests explicitly.
The loop can probably be cleaned up; calling textlogin.get() and textpassword.get() just the once, and using zip() to pair up the field values, and any() to see if there is a first match (which is enough here):
login, pw = textlogin.get(), textpassword.get()
if any(pair == (login, pw) for pair in zip(fields, fields[1:])):
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
If you meant to loop through the fields as pairs (and not as a sliding window), then use:
login, pw = textlogin.get(), textpassword.get()
fields_iter = iter(fields)
if any(pair == (login, pw) for pair in zip(fields_iter, fields_iter)):
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
I apologize for my earlier questions as they were vague and difficult to answer. I am still fairly new to programming and am still learning the ins and outs of it all. So please bear with me. Now to the background information. I am using python 3.3.0. I have it loaded onto the Eclipse IDE and that is what I am using to write the code and test it in.
Now to the question: I am trying to learn how to create and use dictionaries. As such my assignment is to create a price matching code that through user interface will not only be able to search through a dictionary for the items (which are the keys and the locations and prices which are the values associated with the keys.) So far I have created a user interface that will run through well enough without any errors however (at least within the IDE) When I run through and input all of the prompts the empty dictionary is not updated and as such I cannot then make a call into the dictionary for the earlier input.
I have the code I have written so far below, and would like if someone could tell me if I am doing things correctly. And if there are any better ways of going about this. I am still learning so more detailed explanations around code jargon would be useful.
print("let's Price match")
decition = input("Are you adding to the price match list?")
if decition == "yes":
pricematchlist = {"Snapple":["Tops",99]}
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = input("Now how much was the item")
int(price)
pricematchlist[item]=location,price
print(pricematchlist)
else:
pricematchlist = {"Snapple":["Tops",99]}
reply = input("Ok so you want to search up a previous price?")
if reply == "yes":
search = input("What was the item?")
pricematchlist.item(search)
These are a few minor changes. For dictionaries: you are using them correctly.
print("let's Price match")
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes":
# pricematchlist = {"Snapple":["Tops",99]}
# If this whole code block is called repeatedly, you don't want to reassign it
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = int(input("Now how much was the item"))
# int(price) does nothing with reassigning price
pricematchlist[item]=location,price
print(pricematchlist)
else:
reply = input("Ok so you want to search up a previous price?").lower()
if reply == "yes":
search = input("What was the item?")
print pricematchlist[search] # easier way of accessing a value