Sorry if the answer to this question may be obvious, but I'm very new to Python (just first started reading a small document about the differing structure and other things from C this morning). While practicing, I decided to make an ATM. However, something weird in the verification process happened, where it compares the input password to the password in a .txt file representing a user database. Despite the two strings are perfectly equal (and yes, I've checked the type, both are class str), my script is completely failing to compare the two correctly! I'm looking and I'm sure I'm missing something obvious, but I just can't find it.
Here's the relevant bits:
class MockUserInterface:
def __init__(self):
ccn = input('Enter your Credit Card Number --> ')
password = input('Enter the corresponding password --> ')
self.db = MockDatabase()
self.processUser(ccn, password)
processUser(self, ccn, password) passes ccn and password to VerifyUser to get a False|dictionary value...
class MockDatabase:
def __init__(self):
self.initdata = open('D:/users.txt', 'r')
self.data = {}
line = 0
for user in self.initdata:
line += 1
splitted_line = user.split(',')
self.data[splitted_line[0]] = {'Name' : splitted_line[1], 'Password' : splitted_line[2], 'Balance' : splitted_line[3], 'id' : line}
self.initdata.close()
def verifyUser(self, ccn, password):
if ccn in self.data:
if ccn == self.data[ccn]['Password']:
return self.data[ccn]
else:
print(password, self.data[ccn]['Password'])
else:
print(self.data)
The users.txt looks like this:
13376669999,Jack Farenheight,sh11gl3myd1ggl3d4ggl3,90001
10419949001,Sardin Morkin,5h1s1s2w31rd,90102
12345678900,Johnathan Paul,w3ll0fh1sm4j3sty,91235
85423472912,Jacob Shlomi,s3ndm35h3b11m8,-431
59283247532,Anon Tony,r34lp0l1t1k,-9999
After running the script, the output is:
C:\Python33\python.exe D:/PythonProjects/ATM(caspomat).py
Enter your Credit Card Number --> 13376669999
Enter the corresponding password --> sh11gl3myd1ggl3d4ggl3
sh11gl3myd1ggl3d4ggl3 sh11gl3myd1ggl3d4ggl3
Process finished with exit code 0
Again, sorry if the answer is obvious or I'm not giving enough info!
You are comparing ccn to the password - not the password arg with the user's stored password...
if ccn == self.data[ccn]['Password']:
should be
if password == self.data[ccn]['Password']:
Related
Usage
I am using the replit browser IDE for this project. Also, I am using replit's database for this project.
Problem
So as you can see, in the code below, I am asking the user to log in or Sign up, while saving the user's data of money, deposits, inventory in a key-value pair into the database of replit. It is simple to do that, first I import replit:
from replit import db
And then I assign the key-value pairs to a list like:
username = input("Enter new Username: ")
password = input("Enter new password: ")
db[username] = [password, 300000, [], 500, 0, False]
# the password, money, inventory, allowed deposit, deposited, and boolean for working or not, respectively.
But to actually uses the user's stats saved to their value pair, I have to make the username available in all places in the code. Rather I assigned them to variables:
self.money = db[username][1]
self.inventory = db[username][2]
self.deposit_allowed = db[username][3]
self.deposited = db[username][4]
self.working = db[username][5]
But despite doing that, I get errors that "user name is not defined" and "self.inventory is not defined". I am getting the values using the list as you will see below
The Real Question
My real question is that how can I make the variables, that I have put up, have the values of the list that I have assigned to the value pair of the user's name and make it work globally. Because later in the code, I append to the self.inventory list which is in the value pair list assigned to the user.
Code
Here is a portion of the important code that I am using.
class Game:
def __init__(self, username):
self.money = db[username][1]
self.inventory = db[username][2]
self.deposit_allowed = db[username][3]
self.deposited = db[username][4]
self.working = db[username][5]
def database(self):
enter_game = input("Do you want to [1] Login\n[2] Signup:\n>")
while enter_game == '1' or enter_game == '2':
if enter_game == '1':
username = input("Enter user name: ")
password = input("Enter password: ")
if username in db.keys():
if db[username][0] == password:
print("Loggedd In")
break
else:
print("Invalid Username, Password")
break
if enter_game == '2':
username = input("Enter new Username: ")
password = input("Enter new password: ")
db[username] = [password, 300000, [], 500, 0, False]
break
Also, the project is literally massive, so rather, I have attached a link to go to the real code(The code that is used here is in the gameplay.py file):
Click here to go to the repl with the code.
Or if that doesn't work, click here:
https://replit.com/#OldWizard209/Life-SIMULATOR-In-Development-2#gameplay.py
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
database=[['username1','password1'],['username2','password2']]
def check_match():
check_username()
check_password()
for pair in database:
if check_username==pair[0]:
if check_password==pair[1]:
print('login succesful!')
return
else:
print('login failed')
return
This is the code I have currently to check if index 0 of a list matches index 1 of the same list, It's not working though. check_username() and check_password() hold the contents of a list based on user input.
I realized I called the incorrect functions in the given function, that's my bad, thanks for the help though!
Here is a simple answer. You can modify it accordingly but i made it to satisfy the basic needs;
database=[['username1','password1'],['username2','password2']]
username = 'username1'
password = 'password2'
def login(username, password):
for i in range(len(database)):
if username == database[i][0] and password == database[i][1]:
print("login successfull")
return
print("invalid credentials")
login(username, password)
username and password can be taken from the user.
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".
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.