Get username from previous def into another def with if statement - python

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

Related

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".

Reassigning variable from None to Value python [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 2 years ago.
I am trying make a script that will accept 3 inputs first is username as input second and third are bar codes i need to compare, but after the first input of the user I want it to stop asking me for the user and just save and use it and cant seem to do it. I am assigning the user_global to be None at start so can I use an if to run the get_user function but when the script runs it second loop time it gives None as value to the user again and i cant seem to remember how to remove the user from the loop and save it after the first iteration because i am real dumb, as I stated before. Here is the code:
while True:
def get_user():
user=input("Enter User :")
user_global = user
print(user)
print(user_global)
user_global = None
if user_global == None:
get_user()
a = datetime.datetime.now()
print(a)
def gun_read():
barcode1=input("Please the first barcode the barcode!?")
print(barcode1)
barcode2=input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
else:
print("you fcked up broooo!!")
# if os.cwd() ima csv file add to csv else create csv
gun_read()
Help, please ? Also ignore prints and datetime.
By default, Python doesn't allow you to assign global variables. In get_user() what it's doing is making a new variable called global_user. To change this behaviour, have global user_global on a line before you assign the variable.
Unless I'm missing something,
user = None
def get_user():
return input("Enter User :")
def gun_read():
barcode1 = input("Please the first barcode the barcode!?")
print(barcode1)
barcode2 = input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
return True
else:
print("you fcked up broooo!!")
return False
def main():
global user # so we can write to the global user variable
user = get_user() # grab the username and write it
while True: # repeat gun reads until the end of time
gun_read()
if __name__ == "__main__":
main()
first of all, keep your def functions always on top for readability, second of all why is the whole thing in while True:? And lastly in get_user() you can call gun_read()
def get_user():
user=input("Enter User :")
user_global = user
print(user)
print(user_global)
gun_read()
def gun_read():
barcode1=input("Please the first barcode the barcode!?")
print(barcode1)
barcode2=input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
else:
print("you fcked up broooo!!")
user_global = None
while True:
if user_global == None:
get_user()
else:
gun_read()

How to create a unique alphanumeric id each time and ensure it doesn't exist in my existing list using python?

I need to assign a unique name that contains the word 'user' and a certain random numbers to a user. Something like user32944, user80890 etc. So I write a program something like this
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
user_name = ""
while(True):
if user_name not in user_list:
user_name = "user" + str(random.random() * 100000).split(".")[0]
break
print(user_name)
But if I deliberately set the user_name to something that already exists in the list, my program doesn't exit the loop and the program hangs.
What am I doing wrong?
You only perform a action when the generated username is not in the list, but you don't do anything when the username is in the list. And therefore you don't exit the while loop and the program will hang.
The following code sample does what you want. Although i recommend you to explore the uuid package in python.
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
def generateRandomUsername():
randomNr = random.randint(1,3)
if randomNr == 1:
return "user32944"
else:
return "user" + str(random.random() * 100000).split(".")[0]
def getRandomUniqueUsername():
while(True):
username = generateRandomUsername()
if username not in user_list:
print('Created user \'%s\'' % username)
return username
else:
print("Username \'%s\'already exists, generating new one" % username)
def printUsernameList():
for username in user_list:
print('Username: %s' % username)
#Create 4 random usernames
for i in range(4):
username = getRandomUniqueUsername()
user_list.append(username)
print('Printing user_list...')
printUsernameList()
That will never exit the loop because you are never satisfying the IF condition and there is no conditional expression on while too, you gave True in while condition -> which means it loops infinitely.
So if you do not satsifying the IF condition then write a logic what you would want to do incase IF does not get statisified and then break out of the loop.
And if you want guid with just random alphanumeric ids, then use uuid package in python.

'AttributeError:' when I try to unpickle dictionary

I have made a program on python 3.5 which you can find out the password linked to a username, make a new password for an existing user and add a new user and password to the dictionary then pickles it so every time I load the program all the usernames and passwords will be there.
The error that comes up is after you create the pickle file(after running it for the first time) then on line 6 the error
AttributeError: Can't get attribute 'NewPass' on <module '__main__' (built-in)>
occurs.
Here is my script:
import sys
import pickle
import os
if os.path.exists("branston.p"):
LOGG = pickle.load(open('branston.p', 'rb'))
else:
LOGG = {'Sam': ('CHRIST')}
def Find():
Username = input("Say a Username.")
print (LOGG[Username])
def NewPass():
Username = Input("Enter your username.")
Newpass = input("Enter your new password")
if NewPass == input("Confirm password"):
LOGG[Username] = (NewPass)
def NewEntry():
NewUser = input("Enter your new username.")
Newpass = input("Enter your new password.")
LOGG[NewUser] = (NewPass)
loop = True
while loop == True:
function = input("Say what you want me to do.'Find', 'NewPass', 'NewEntry', 'Stop'.")
if function == ("Find"):
Find()
elif function == ("NewPass"):
NewPass()
elif function == ("NewEntry"):
NewEntry()
elif function == ("Stop"):
f = open('branston.p', 'wb')
pickle.dump(LOGG, f)
f.close()
sys.exit()
Any help would be appreciated. Thanks!
When you do this
LOGG[NewUser] = (NewPass)
You are assigning the function NewPass to your dict entry. You are probably intending to assign the password string and therefore it should be.
LOGG[NewUser] = Newpass
Note: Parenthesis are superfluous. I'd also suggest avoiding using upper case letters as the first character of your variable names, as otherwise it is easy to confuse variable and function names.

if True: update, if False: restart

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.

Categories

Resources