if x in [list] iterator - python

def new_user() -> str:
users = []
print("Welcome to The 'Create New User' Interface")
sleep(0.5)
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
if x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
else:
users.append(x)
print("Your Account Access Name is: " + str(x))
So I'm not sure how to word this question but I have this block of code and as you can see I want to check if the user inputted name already exists, and if it does it'll prompt for a new name and add it to the list, and if it doesn't already exist, it'll add it to the list, but there's a way around this, if the list already contains a name and the user inputs that same name the if x in users: code will run and when prompted to enter another name, if they enter that same name, it wont recognize that it already exists and add it to the list either way, how can i prevent this?

To get valid user input wrap the request in a loop and when you have valid input break out, e.g.:
print("Enter Name to Use for Account Access")
print("*Name is Case Sensitive to Access Account*")
while True:
x = input("Enter a Name: ")
if x not in users: # Valid input
break
print("That User Already Exists!")
users.append(x)
print("Your Account Access Name is:", x)

Solution
users = []
print("Welcome to The 'Create New User' Interface")
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
while x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
Simply just changed your if loop to a while loop that will continue until a unique name is given.
Suggestions
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = '' #now users can not enter a empty user_name
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
for i in range(0, len(users)): #different loop to enable use of lower()
while user_name.lower() == users[i].lower(): #removes need for unique cases
print("That User Already Exists!")
user_name = '' #again stopping empty fields
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
users.append(user_name)
print("Your Account Access Name is: " + user_name)
For start we can create a loop that will reject any blank user_name.
Next we can use .lower() when checking to see if user_name exists in users[]. By doing this we can preserve the unique case format the user wants to use to store their name(perhaps for display purposes) but at the same time we can check to see if user_name already exists regardless of case format.
Cleaning it up we can go with something like this:
def ask_user(message=''): #create function to check for blank inputs
user_name = ''
while not user_name:
user_name = input(message)
return user_name
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = ask_user("Enter Name to Use for Account Access: ")
for i in range(0, len(users)):
while user_name.lower() == users[i].lower():
print("\nThat User Already Exists!") #newline for clarity
user_name = ask_user("Enter Name to Use for Account Access: ")
users.append(user_name)
print("\nYour Account Access Name is: " + user_name) #newline for clarity
Here I created ask_user which handles blank inputs. Then added a \n in a few spots to help with readability.
Output
(xenial)vash#localhost:~/pcc/10$ python3 helping.py
Welcome to The 'Create New User' Interface
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: vash
Your Account Access Name is: vash
Enter Name to Use for Account Access: VASH
That User Already Exists!
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: p0seidon
Your Account Access Name is: p0seidon
Enter Name to Use for Account Access: P0SEidoN
That User Already Exists!
Hope this helps!

Related

How do I iterate over every value in a key where the value is the instance of a class?

I want to iterate over every instance i stored as a value to a number stored as a key in a dictionary. Where if I were to make an account named jason, it would be assigned 1, then if I were to make a new one, it would be assigned 2. That part is already done but the iteration part is very confusing for me. Why does it only go through the first key value pair in the dictionary?
Ps: I am new to oop this is my first oop thing where i did not follow any guides so that id would actually learn. Thank you <3
class Bank:
serialnum = 0
username = ""
email = ""
password = ""
bal = 0
def __init__(self,count):
self.serialnum = count
self.username = input("What's your username? \n")
self.email = input("What's your email? \n")
self.password = input("What's your password \n")
self.bal = input("How much balance do you have \n")
def withdraw(money):
self.bal= bal-money
print (bal)
global count
count = 0 #counts and is the serial num
accounts = {} #accounts dictionary
def accountcreate(): #gets called when account does not exist
global count
while True:
serial = int(count)
account = Bank(count)
print("The serial is {}".format(count))
count += 1
accounts[serial] = account
print("Your account has been created, please use the username registered. ")
break
accountaccess()
def accountverify(name):#if accountverify returns false, prompts the accountcreate function
username = ""
start = 0
balance = 0
if 0 in accounts: #essentially means if the first account has been made
for key in accounts: #loops through accounts in accounts dictionary
#sets the keys gotten and sets the un to the username attribute of every key
if hasattr((accounts[key]),"username") == name:
print("logged in as ", name, "Password is \n",
(getattr((accounts[key]), "password")),
"Account balance is ", getattr((accounts[key]), "bal"))
action = input("What do you want to do? \n -Withdraw \n -Deposit \n -Transfer \n -Make another account \n")
if "make" in action:
print("Making another account... \n Please enter your credentials")
makeaccount = accountcreate()
else: #if username does not exist
print("First item in list is ",(getattr((accounts[key]),"username")))
print(accounts)
accountask = input("Account does not exist, make a new account? Yes or No \n").lower()
if accountask == "yes":
makeAccount = accountcreate()
else: #makes first account
ask1 = (input("Account does not exist, would you like to make an account? Yes or No \n")).lower()
if ask1 == "yes":
makeAccount = accountcreate()
def accountaccess(): #accesses account
ask = (input("Do you want to access an account? Yes, or no. "))
if ask == "yes":
getname = (input("What is your username? ")).lower()
ver = accountverify(getname)
loop = False
loop = True
while loop == True: #mainloop
ask = (input("Do you want to access an account? Yes, or no. \n")).lower()
if ask == "yes":
getname = (input("What is your username? ")).lower()
ver = accountverify(getname)
loop = False
The replit link
It would also be helpful to know how to store the username as the name of the value since what is shown there is incredibly cryptic
In this image, every new username registered is a new instance of the Bank class. But the for loop only goes on the first one
The part of your code that is causing the issue is
if hasattr((accounts[key]),"username") == name:
print("logged in as ", name, "Password is \n",
(getattr((accounts[key]), "password")),
"Account balance is ", getattr((accounts[key]), "bal"))
The return from hasattr is a boolean and cannot be compared to name.
Try changing it too
if hasattr(accounts[key],"username"):
if accounts[key].username == name:
....
Also your use of getattr() is incorrect and unnecessary since you can simply access those attributes directly.
For example:
account = accounts[key]
print(account.username)
print(account.password)
print(account.bal)
with all of that in mind your accountsverify function should look more like this:
def accountverify(name):
start = 0
balance = 0
if 0 in accounts:
for key in accounts:
account = accounts[key]
if account.username == name:
print(f"logged in as {name} Password is \n {account.password} \n Account balance is {account.bal}")
action = input("What do you want to do? \n -Withdraw \n -Deposit \n -Transfer \n -Make another account \n")
if "make" in action:
print("Making another account... \n Please enter your credentials")
makeaccount = accountcreate()
else: #if username does not exist
print("First item in list is ",account.username)
print(accounts)
accountask = input("Account does not exist, make a new account? Yes or No \n").lower()
if accountask == "yes":
makeAccount = accountcreate()
As far as making the Bank class print the accounts name you just need to overwrite the __str__ method.
class Bank:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name

TypeError in simple registration/login program

For practice purposes I tried coding a little registration/login system which stores the registered users' data in a list.
I tried to solve this by getting user input (name, nickname and password), then create a list with the chosen "Name" which then stores "Nickname" and "PW" . This then should be then stored in the created list "users" which is being created in the beginning.
So I would have a list with different names/persons which includes their data.
The problem is that in the else statement it won't let me create the name-variable list with (username, password) in it. "TypeError: string indices must be integers"
users = []
def register():
print("Please insert your Name")
name = input()
print("Please insert your Username")
username = input()
print("Please type your Password")
userpw = input()
if name in users:
print("Account already exist, try again")
register()
else:
users.append(name[username, userpw])
This code creates a dictionary for a user and then check if its already registrated. I recommend using some sort of database to avoid dataloss from program restarts.
users = []
def register():
print("Please insert your Name")
name = input()
print("Please insert your Username")
username = input()
print("Please type your Password")
userpw = input()
for x in users:
if x['name'] == name:
print("Account already exist, try again")
register()
return
user = {'name': name,
'username': username,
'password': userpw}
users.append(user)

How to delete one value of keys from dictionary?

I'm trying to delete a specific input of user using del function but it deletes the whole key values below it
for account3 in accounts:
print("\t ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
userinput = input('Account Name you want to delete: ')
for account4 in accounts:
if userinput == account4["Name"]:
userinput = input('Re-enter name to confirm: ')
for account5 in accounts:
if userinput == account5["Name"]:
del account5["Name"], account5["Username"], account5["Password"]
print('Deleted Successfully!')
menu()
break
After the user confirms the deletion, it deletes all values in the dictionary and gives a key error: "name". Is there any way to delete only the information given by the user?
Setting the values to None is what you want instead of deleting the entries.
Replace the del line with this.
account5["Name"], account5["Username"], account5["Password"] = None, None, None
To avoid having to loop through the list multiple times to find the matching account, I suggest building a dict that maps the name to each account, and using accounts.remove() to remove the account.
accounts_by_name = {account["Name"]: account for account in accounts}
for account in accounts:
print("\t ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
name = input("Account name you want to delete: ")
if name not in accounts_by_name:
continue
if input("Re-enter name to confirm: ") != name:
continue
accounts.remove(accounts_by_name[name])
menu()
break

Python - unavailable username

I am trying to create a small program that registers a user to a text file. It asks the user to create a username and it checks if the chosen username already exists in that text file. If so I need the user to be in loop until they enter a different username. The file contains usernames and passwords for each individual separated by ", " eg. (Sanele, afkojs). Each user is stored in a separate line. My code is not keeping the user in this loop it goes through
cont_ = False
while not cont_ :
new_username = input(" Create a Username: ")
unavail_usernames = file_opener("user_info") *#function that opens the text file*
for names in unavail_usernames:
user_info_list = names.split(", ") *#Every user is stored in a separate line*
if new_username != user_info_list[0]:
cont_ = True
if not cont_:
print("username unavailable, enter a different username")
unavail_usernames.seek(0)
Try this:
l=['a,b,c','d,e,f','g,h,i']
inp = input()
while inp in list(map(lambda x:x.split(',')[0],l)):
print("username unavailable, enter a different username")
inp=input()
print('Username is available')
This code
for names in unavail_usernames:
user_info_list = names.split(", ") *#Every user is stored in a separate line*
if new_username != user_info_list[0]:
cont_ = True
set cont_ to True as soon as different name is found. You are checking: does file hold any username different than given? whilst you should: does all username in file are different from given?

Password - Login not working Python

I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue

Categories

Resources