if True: update, if False: restart - python

import getpass
class UserRegistration(object):
def __init__(self):
pass
def register(self):
register = self.register
self.username_and_password = {}
username = raw_input("Choose Username> ")
password = getpass.getpass("Choose Password> ")
confirm_password = getpass.getpass("Confirm Password> ")
if password == confirm_password:
self.username_and_password[username] = password
else:
print "Passwords didn't match"
return register
go = UserRegistration()
go.register()
Simple program that prompts user for username and password
If the passwords don't match, I want it to restart the process and prompt the user to enter password again
At the moment, it prints the string but doesn't restart the process.
Any ideas?

Call the method again:
else:
print "Passwords didn't match"
self.register()
def register(self): is a method of the class, so you call it with self.register,, there is no need to use register = self.register
If you just want to prompt for the password and store multiple instance details in the dict:
class UserRegistration(object):
username_and_password = {}
def __init__(self):
self.username = ""
def register_name(self):
self.username = raw_input("Choose Username> ")
self.register_pass()
def register_pass(self):
password = getpass.getpass("Choose Password> ")
confirm_password = getpass.getpass("Confirm Password> ")
if password == confirm_password:
self.username_and_password[self.username] = password
else:
print "Passwords didn't match"
self.register_pass()
You can also use a while loop:
class UserRegistration(object):
username_and_password = {}
def __init__(self):
self.username = ""
def register_name(self):
while True:
self.username = raw_input("Choose Username> ")
if self.username in self.username_and_password:
print "Username taken, please try again"
continue
else:
return self.register_pass()
def register_pass(self):
while True:
password = getpass.getpass("Choose Password> ")
confirm_password = getpass.getpass("Confirm Password> ")
if password == confirm_password:
self.username_and_password[self.username] = password
return
else:
print "Passwords didn't match"
continue

You need to call self.register(), and calling register() would do this, but in a way that will not pay off in the long run. (Though what you really need is just a loop. Recursion will result a pointless copies of your class on the stack.)
What is wrong here indicates the need to expound a really basic Python concept:
Python names do not do or invoke things. Only the operators do, and they do so by calling named methods of some object. So it is the parentheses, or the dot, if you are using a property, that cause the execution. Functions, and even methods or properties are objects. Saying 'return register' means 'return the object representing function that does this', not 'invoke this function and return the result'.
Also, since people have a hard time thinking of a method, rather than a function, as an object, assigning self.register to another variable is bizarre. Referring to bound things with local variables, especially of the same name, is generally a way to create bugs, unless you are doing something quite ornate.

Related

Get username from previous def into another def with if statement

I have some code where I'd like to use the inputted username again in another def, but it doesn't generate anything. I get a username with the following code without issues (s_print is a slow print for reference):
def input_username():
username = input()
user = username
s_print('Hello {}!'.format(user))
return user
input_username()
Then I have a def a bit later on in the code with various if statements:
def options_input():
if option == '1': etc.
elif option == 'Bye':
end_user = input_username()
s_print('Goodbye {}!.'.format(end_user))
else: etc.
options_input()
I want to get the username inputted in def input_username to be reprinted in the def options_input elif option == 'Bye' but it just generates blank with no error code/message, like it's looping continuously through code. What is going wrong?
input_username() is a function
when you call a input_username() you need to save it in a variable to use it later
username = input_username()
and then later in options_input()
end_user = username
this line:
end_user = input_username()
asks you to input username again it doesent have old one

How do I store the values into this dict so that in the next iteration it would work?

I'm not sure how to store the values taken from the user input (to generate new username and password) and store it in the iass dict, so in the next iteration it would work:
iass = {}
class login:
def __init__(self):
pass
def passcheck(self):
for key, value in iass.copy().items():
if self.username == key and self.password == value:
print("Granted Access")
else:
A = str(input("Enter Desired Name: "))
B = str(input("Enter Desired Password: "))
iass[A] = B
A1 = login()
A1.username = str(input("Enter Username: "))
A1.password = str(input("Password: "))
A1.passcheck()
Your usage of a class/object is a little strange. Usually one would create a class for something that represents an object (a noun) in the real world. In your application, this might be User.
Login would be a method in that class.
Your method passcheck is also a bit strangely constructed. As you've just asked for the input of Username and Password, you can reuse these at all times. You don't need to ask them again. I'd recommend you to pass username and password as parameters in the login method, rather than setting them directly as parameters. Your code could look somewhat like this
iass = []
iass.append({'myuser': 'mypwd'})
class User:
def __init__(self):
pass
def login(self, username, password):
for key, value in iass.items():
if username == key and password == value:
print("Granted Access")
return
# User not found, so we're adding him
iass.append({username: password})
A1 = User()
username = str(input("Enter Username: "))
password = str(input("Password: "))
A1.login(username, password)
Note: didn't run this in the python parser. might have some issues :-)
Please run pylint on your code.
It will uncover bugs for you before you run it.
It will improve the code readability. This helps everyone: yourself and others who will read your code.
Code changes:
Remove the iass.copy() call. It was unnecessary; though not creating a bug.
To make the code "work" you need to initialize iass with a key and value:
iass = {"ding": "dong"}
Remove the else: block. That is causing an extra prompt which is only confusing and would be considered a bug.
Now when the user enters a username, password "ding" and "dong" your check will "pass".

Creating a Login System

I am trying to create a login system. I could make the system without implementing class and just functions. I would like to make each steps into specific methods without writing all into one function.
My question is how to revert back into login asking username and password if the character length is > 5 or wrong password.
If the username and password not in the list how do i revert it back or do i need to code again?
class LoginSystem:
def __init__(self):
self.user_id = input("Please enter your user id: ")
self.user_password = input("Please enter your password: ")
def login(self):
username = self.user_id
password = self.user_password
if len(username) <= 5 and len(password) <= 5:
print("Logging In")
else:
print("Error! Max Length is 5 chars.") #return back to
login system
def check_system(self):
registered_user = {
"test#gmail.com": "test"
}
if self.user_id in registered_user:
print("Successful")
else:
new_user = input("Id not found! Are you are new user?\n [Y]es or [N]o\n")
new_user = new_user.lower()
if new_user == "Y":
return back to login system
elif new_user == "N": #how to return back to main login system
new_username = input("Please enter your user id: ")
new_userpassword = input("Please enter your password: ")
else:
return #back to login system
Your LoginSystem treats the wrong data as its instance attributes. The set of registered users is constant across method calls; the login method itself should be prompting for the user id and password.
class LoginSystem:
def __init__(self):
self.users = {"test#gmail.com": "test"}
def login(self):
while True:
username = input("Please enter your user id: ")
password = input("Please enter your password: ")
if len(username) <= 5 and len(password) <= 5 and self.check_system(username, password):
print("Logging In")
break
else:
# TODO Disallow infinite retries to get it right
print("Error! Max Length is 5 chars.")
def check_system(self, name, password):
try:
expected_password = self.registered_user[name]
except KeyError:
# Or try to add a new user to the system here
return False
if password != expected_password:
return False
return True
A separate method can be added to add a new user to the system where necessary.

I cant get the expected output in my code (signup login system)

Hi i'm new in python and in programming in general ! i tried to make a login system with python but it doesnt seem to be working as i expect
the problem is even if i enter false login informations at the end the program will print login successful instead of printing incorrect username or password
NOTE : i'm not trying to make real login system it's just some practice form what i learned
signup_username = ""
signup_password = ""
login_username = ""
login_password = ""
false_login_info = False
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
signup()
print("Signup successful")
login()
if login_username != signup_username or login_password != signup_password :
print("Incorrect username or password")
else :
print("login successful")
EXPECTED Result :
1) if login informations are same as signup infos i should get :
- Login successful
2) if login informations are NOT same as signup infos i shoul get :
- Incorrect username or password
ACTUAL Result :
in both cases the program will print login successful
You need to return the values from your functions. The names defined inside the function are not the same as those that exist outside of the function. In this case, I have appended x to the names in the global scope to differentiate them from the ones inside the function to hopefully make it clearer. I could have used the same names both inside the function and outside; it wouldn't have made a difference. You can see more here.
There is no need to "initialise" the variables as empty strings before the function call. Instead, we'll just create them in the function, return them, and then unpack them into the variables ending in x.
false_login_info = False # You never use this
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
return signup_username, signup_password
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
return login_username, login_password
signup_usernamex, signup_passwordx = signup()
print("Signup successful")
login_usernamex, login_passwordx = login()
if login_usernamex != signup_usernamex or login_passwordx != signup_passwordx:
print("Incorrect username or password")
else :
print("login successful")

Variable and Function help // Python

Alright so here's the code
def user_password():
input('Please Enter Password: ')
#profiles
def intercept():
user_password()
if user_password == "intercept":
print("this is working so far")
else:
print("Incorect Password")
def Jimmy():
user_password()
if user_password == "Jimmy":
print("this is working so far")
else:
print("Incorect Password")
def Tommy():
user_password()
if user_password == "Tommy":
print("this is working so far")
else:
print("Incorect Password")
#login
user_functions = dict(
intercept=intercept,
Jimmy=Jimmy,
Tommy=Tommy,
# ...
)
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
else:
print("Error: Unknown function.")
PROBLEMS:
My code always starts with asking for the password even though I don't want it
to.
When I change the first variable to a function it fixes this
Why does it execute when I'm just setting the variable. I'm pretty sure I shouldn't have to use a function instead of a variable
No matter what it always ends up as Incorrect Password even if I give the correct password
I think you are trying to write something like that:
def get_user_password():
return input('Please Enter Password: ')
def Jimmy():
user_password = get_user_password()
if user_password == "Jimmy":
print("this is working so far")

Categories

Resources