Python: Removing an item from a list based on input()? - python

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)

Related

How to correlate a selection from a list of options with the associated command?

So basically, what I'm trying to do is to create a menu that allows me to modify the contents of a text file. It's supposed to look like this:
Question 1
I think I already know how to create the menu, as shown here:
print("User Management")
print("1.Add new record")
print("2.View all record")
print("3.Search record")
print("4.Exit")
option = int(input("Enter your choice: "))
if option == 1 :
The problem I have I have no idea how to correlate the options to the commands. For example, if I wanted to correlate this:
name = input("Please enter your name:")
email = input("Please enter your email address:")
f = open("user.txt","a")
f.write("\n"+name+","+email)
f.close()
print("Record added."))
to 1 so whenever I input 1 in the "Enter your choice" it allows me to add a name and email address to the text file, etc. Here's an example I can find:
Example
I have been told that using the if and elseif functions allows me to do that, but I have no idea how. I'm quite new to Python, so forgive me if I seem ignorant. Any help will be appreciated.
You're right in that using a conditional (the fancy technical term for if/elseif/else) is the way to do that. Assuming that the text you have included in your question is accurate, it's likely that you haven't indented the code that is meant to be in the if block.
Python uses indentation (that is, spaces or tabs) to indicate what code is within each control structure. So in your example, if you want to only execute the second block of text if option == 1 you would want:
print("User Management")
print("1.Add new record")
print("2.View all record")
print("3.Search record")
print("4.Exit")
option = int(input("Enter your choice: "))
if option == 1 :
name = input("Please enter your name:")
email = input("Please enter your email address:")
f = open("user.txt","a")
f.write("\n"+name+","+email)
f.close()
print("Record added."))
For more on using if and other control flow, see the tutorial here.

Python: How to require an input to correspond with a previous input?

all. Python newbie here.
Simply-put here is my basic idea:
I want to create a "Login" feature where people must input a valid username from a preset tuple.
Next, once a valid name is entered, they will be asked to enter the corresponding code name, which is saved to a dictionary. (I have a feeling that I am over-complicating this, or maybe the dictionary is the wrong idea entirely, so any advice on how to simplify would be great).
real_names = ("JD", "JM" "JC")
player_ids = {"JD":"Arrow","JM":"Bullet","JC":"Blade"}
while True:
# user must input a name from the real_names tuple
name = input("User unidentified. Please input your name: ")
# if username is not in tuple, rerun script
if not name in real_names:
print("Invalid username detected")
continue
print(f"Positive ID! Welcome, {name}")
break
The above code works just fine. But next, I want to make a new input that requires the player ID to match the previously input name. In Pseudo-code, something like this:
# While True Loop:
id = input("Please confirm user Code Name: ")
#ID must correspond to keyword in dictionary
if ID value does not match username Keyword:
print("Invalid ID")
continue
print("Identity confirmed!")
break
Am I on the right path? If so, how would I syntax the second part? If the dictionary is the wrong idea entirely, please provide a good alternative. Many thanks!
player_ids[name] is the value you're looking for. So, you want something like this:
if id != player_ids[name]:
print("invalid ID")
Also, the dictionary already keeps track of player names, so you don't need the real_names tuple.
This previous answer works perfect, because you are looking up the value based on the key from a dictionary. Finally, one little tip, it's always good practice to avoid naming variables after reserved variables and keywords, that is to say, use another variable name just in case you are going to use to use the id() function again in the program.

How to update a list and a dictionary in python even after rerunning the code? [duplicate]

This question already has answers here:
How to save a dictionary to a file?
(12 answers)
Closed 2 years ago.
I am currently creating a signup and login page for an application but whenever I create a new username/password combo, I see it in my list right after creating it (I print the dictionary at the end of the program so I can see it) but after I decide to rerun the code, the usernames and passwords that I just created are gone. How do I get these to stay even after rerunning the code?
I do not know if adding my code will help here (I do not think that it will) but I will add the bits that I feel could potentially be the most helpful:
import re
usernames_passwords = {'lmaoidontknow': 'password123',
'evillover456': 'waterworld332',
'xyzitsme': 'notmypass',
'unicornpops': 'blahbleh76'}
while not chosen_user:
chosen_user = input("""Enter the username that you would like. Please keep it between 6 and 15
characters. Do not use special characters such as '&', '#', or '!' in your username. Underscores are
allowed.\n>""")
if (6 <= len(chosen_user) <= 15) and re.search(r"^[a-zA-Z0-9_]+$", chosen_user):
print('')
else:
print('Username does not meet the requirements. Please try again.')
chosen_user = False
if chosen_user in input_usernames:
print('This username is already taken. PLease try again.')
chosen_user = False
The dictionary at the top was created just to test certain things such as making sure usernames were not replicated and they are not permanent. Whenever I rerun my code, that dictionary is the only usernames/passwords that remain and I want all usernames and passwords that I input to stay.
Edit: This is only the username code. Password code can be included if asked for but I do not think it will make much of a difference.
When you use a hardcoded dictionary , its data would not persist when you rerun server , you need to use db to store and make them persisitent.
Why dont you store the chosen_user to your usernames_passwords? Let's say:
if (6 <= len(chosen_user) <= 15) and re.search(r"^[a-zA-Z0-9_]+$", chosen_user):
pass_word = input("Enter your password: ")
else:
print('Username does not meet the requirements. Please try again.')
chosen_user = False
continue
if chosen_user in input_usernames:
print('This username is already taken. PLease try again.')
chosen_user = False
continue
else:
usernames_passwords[chosen_user] = pass_word
But I highly recommend that you should store your username and password in database to access them, or you could store to a file with password is encrypted

How to ask user's name with the use of def function more efficiently

I've basically made a def function to ask user's name with the input
but when I tried to make an input to get the user's name accordingly, I came to realise that each input has to be assigned individually so as to later print that input linked according to what the user inserted their name.
## Ask user's name with the use of def function.
def asking_username():
print("What's your name? ")
username = input()
return username
print("Hello, " + asking_username().title() + "!")
The code above that I made has no problem, but I'd like to make the input to get an user insert in the same line as the print("What's your name? ").
How do you individually assign each input so that it does not get confused with the other input in case multiple inputs are inserted?
How about:
username = input("Enter your name\n")
This works, because I'm using the newline character ("\n").

How can i update part of a list within a tuple? Also IndexError: list index out of range what am I doing wrong?

pnew to python and I am playing around with lists within tuples. I want to delete just the password not the Username, and update the password after the password has been deleted, however i tested the code to find out that it deletes the whole tuple and list within the tuple, then it gives me IndexError: list index out of range....any help would be appreciated.
Users=[("Jim","password1"),("Bob","password2"),("Helen","password3"),("Beverly","blue")]
def changePassword():
a=raw_input("Enter old password to continue:\n")
for i in range(len(Users)):
c,d=Users[i]
if a==d:
Users.remove(Users[i])
print "Password deleted"
print Users
if a!=d:
print"Incorrect"
changePassword()
a=raw_input("Enter new password:\n")
for i in range(len(Users)):
c,d=Users[i]
if a==d:
Users.append(Users[i])
changePassword()
There are several problems with your function, unless I completely misunderstand its purpose, but let’s start with the IndexError you get.
This is the code where it happens:
for i in range(len(Users)):
c,d=Users[i]
if a==d:
Users.remove(Users[i])
print "Password deleted"
print Users
So what happens here? You loop over the length of your list and if you matched the password then you remove the current user from the list. After that you continue iterating over the previously calculated length of the list. So, if you delete one item from the list, its length is reduced by one, but the for loop will still iterate over the old length (because range(len(Users)) is immediately evaluated). So if you just deleted one user from the list, the last value for i will try to access an item that no longer exists in the list.
There is a related problem which would occur directly as a follow-up, and that is that you would skip elements in the loop. You are removing an item from the list but you are also advancing i just as you would if no item was removed. So when you remove, say, item 1, then the new item 1 is the one that was previously 2. So when you advance to 2, you will have skipped that item.
So what can you do to fix this? Well, there are different methods. You could make a while loop instead and handle that indexing in a “classic” way (incrementing yourself and always checking the length in the while condition). You could also keep a second list to remember the items you are going to delete later (after the loop). However in your case, I think it might be a good idea to do something completely different.
From how I understood your function, you want to write something that allows you to change the password for a single user. So you enter the current password, then the new password and it will update the entry for the user in the list. This is not what is happening in your version as of now. What your function does is the following:
Ask for current password
Remove all users which have a matching password
Print "Incorrect" if the last user in the list did not have the entered password (it will only see the last value of d, so it will only check the very last user)
Ask for new password
Loop through the user list again and save only the last user (again, c and d will contain the last value after the loop)
If the last user had the same password as you have entered (why would you want to check that, you want to enter a new password), then append the very same user (because i again points at the last index in the list) to the list.
As you can see, there are some weird things going on, probably not intended. What you probably want to do instead is something like this:
Ask for the current password
Find the user for that password
Ask for the new password
Remove the old user from the list
Append a modified user to the list
So maybe something like this:
oldPassword = raw_input('Enter your old password to continue:\n') # 1
found = False
for name, password in Users:
if password == oldPassword: # 2
found = True
break
if found:
newPassword = raw_input('Enter new password:\n') # 3
Users.remove((name, password)) # 4
Users.append((name, newPassword)) # 5
else:
print 'Incorrect password'
I am not sure that a list of tuples is the best way to store user ids and passwords.
Maybe you could use a dictionary instead, that would look like this:
Passwords = {"Jim": "password1", "Bob": "password2", "Helen":"password3", "Beverly": "blue"}
This way you are sure that two different users will not have the same id.
Also, retrieving a user by its password is not a good idea, as several users may have the same
password. You should prompt for the user id first, or pass it as a parameter of your change password function. Something like this :
def changePassword(userId):
input=raw_input("Enter old password to continue:\n")
if input == Passwords[userId]:
new_password = raw_input("Enter new password:\n")
Passwords[userId] = new_password
else:
print "Wrong password"
changePassword(userId)

Categories

Resources