Python: updating assigned variable created in other function - python

I am trying to create registration and login and forgot password functions.
this is my code
def regi():
global new, unname, answer, passcode
print('**New Registration**'.capitalize().center(100))
uname = input("Enter User Name: ")
passcode = input("Enter Password: ")
questn()
new = [name, uname, passcode, security]
print(f'Your Business {bname} has created.\nWelcome to Business World')
newbusiness()
def login():
chances = 5
global old
userid = input('Enter User Id: ')
password = input('Enter Password: ')
try:
if userid and password in new:
pass
else:
print('Wrong Credentials')
chances -= 1
login()
except NameError:
print('No Username found. Please register.')
time.sleep(2)
print('Redirecting to registration block.')
time.sleep(2)
regi()
def questn():
global security
questions = {
1: 'What is your favourite color?',
2: 'What is your mother tongue?',
3: 'What is your favourite place of weekend?'
}
for k, v in questions.items(): print(f'{k}: {v}')
qselct = input("Please select one security question: ")
answr = input('Enter your answer: ')
security = [qselct, answr]
def forgotpass():
questions = {
1: 'What is your favourite color?',
2: 'What is your mother tongue?',
3: 'What is your favourite place of weekend?'
}
for k, v in questions.items(): print(f'{k}: {v}')
comparequet = input("Select Security Quesion: ")
compareans = input("Enter your answer (Case Sensitive): ")
if comparequet and compareans in security:
passcode = input('Enter new password: ') # i stuck here
when i try to reassign 'Passcode' using input(), in pycharm its giving this
Shadows name 'passcode' from outer scope
so how can i update passcode in regi(), here in forgotpass().
Note: helpful if you suggest any improvements in above code. I am using learned subject in the above code. learned TRY used there.

I think you just have to bring in a
global passcode
before using this variable.

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

Nea login part loop?

im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.

Greeting name taken from the dictionary

pins = {"Mike":1234, "Joe":1111, "Jack":2222}
pin = int(input("Enter your pin: "))
if pin in pins.values():
nameinp = pins.get(pin)
print("Hello Mr." + nameinp)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for key in pins.keys():
print(key)
input()
So the idea is to make greeting screen for the particular person who inserted his own pin code, tried to research didn't find the answer, hope you will help!
Answers to all of you
There is no error, there is a question:
how to make that when you put in password that is equal some value, and later when the system recognizes your password prints("Greetings" + value)
You have the order of the dictionary key-value pairs interchanged. So instead of
pins = {"Mike":1234, "Joe":1111, "Jack":2222}
you should do
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
I took the liberty to change the variable name to be more descriptive what it actually does: Given a pin it returns the username. For example: user_from_pin[1111] == "Joe". The rest of the script should be adapted a little bit to work with this definition:
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
pin = int(input("Enter your pin: "))
user = user_from_pin.get(pin)
if user:
print("Hello Mr." + user)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for value in pins.values():
print(values)
input()

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

Adding new users/passwords to dictionary in python email application

I'm having a bit of trouble with this program I've been working on for part of the final for my ITP 100 class. It's supposed to be an email application where you can log in if you are an existing user, or create a new username and password. I'm able to log into existing users with their passwords, and I can create a new username, but when I try to create the new password for it, I keep getting errors. I'm sure it's because I'm not updating the dictionary properly. I'm still pretty new to Python, so hopefully this all makes sense. Any advice?
Also, my program seems to be stuck in an "if loop..?". Whenever I successfully log into an existing user, it show that I've been logged in, but will also go back to the original question "Are you a registered user? y/n? Press q to quit"
Any help is greatly appreciated. Thank you.
import re
users = {}
users={"nkk202": "konrad", "jfk101": "frederick"}
choice = None
login = None
createPassword = None
createUser = None
createLogin = None
print("Welcome to Kmail. The most trusted name in electronic mail.")
print("\nLet's get started")
while choice != "q":
choice = input("Are you a registered user? y/n? Press q to quit: ")
if choice == "q":
print("Thank you for using Kmail. Goodbye.")
if choice == "n":
print("Okay then, let's set up an account for you then.")
createUser = input("Create login name: ")
if createUser in users:
print("I'm sorry, that username is already in use. Please try another!\n")
else:
createPassword = input("Enter a password: ")
if len(createPassword) <5:
print("I'm sorry, this password is too short. Please try another.")
passValue = {1:'Weak', 2:'Good', 3:'Excellent'}
passStrength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', createPassword):
passStrength['has_upper'] = True
if re.search(r'[a-z]', createPassword):
passStrength['has_lower'] = True
if re.search(r'[0-9]', createPassword):
passStrength['has_num'] = True
value = len([b for b in passStrength.values() if b])
print ('Password is %s' % passValue[value])
users.update((createUser, createPassword))
elif choice == "y":
login = input("Enter your username: ")
if login in users:
password = input("Enter your password: ")
if users[login] == password:
print("Welcome", login, "!")
else:
print
print("I'm sorry, either the password/username was unaccaptable, or does not exist. Please try again. \n")
Seems like you just want
users[createUser] = createPassword

Categories

Resources