My code is quite simple, and so the question, this is my code
import pandas as pd
import numpy as np
from io import StringIO
def main():
#usernames and passwords
users = "usernames,passwords\nSimone,123456"
#login
def login_system():
login = input("Login or SignUP: ")
if login == "Login" or login == "login":
#data reading
df = pd.read_csv(StringIO(users), usecols=["usernames", "passwords"])
username = input()
password = input()
#login if statement
if username == df["usernames"][0] and password == df["passwords"][0]:
print("Login Succeeded")
else:
print("Login Failed")
return
login_system()
return
main()
it compiles and everything the problem is that it doesn't do what it is supposed to, here is the answer that the compiler gives
Login or SignUP: Login
Simone
123456
Login Failed
Could someone explain to me why the if statement doesn't work
It looks like you want to look up whether the username and password matches the entry in the csv file that you read into the df. You can filter the df to check if any row matches both username and password. If there is any such row, you have a match. See this toy example:
row1list = ['Simone', 'password1']
row2list = ['YEETter', 'password2']
df = pd.DataFrame([row1list, row2list], columns=['usernames', 'passwords'])
username = 'Simone'
password = 'password1'
dfu = df[(df['usernames'] == username) & (df['passwords'] == password)]
print(dfu)
# usernames passwords
# 0 Simone password1
if len(dfu) > 0:
print("Login Succeeded")
else:
print("Login Failed")
Related
I am new to programming and have recently been trying to learn/understand OOP. I decided to do a password manager as a project to help me learn as I have already done it using FP. However, I have gotten a tad lost in what I am doing and would greatly appreciate some help. I am lost in the creation of a user account and making an object out of it. And then use this in a login function to access the users password collection and make new passwords or edit existing ones if the credentials of the account match those in a dictionary of users. But i don't know how to do this honestly.
Any comments regarding my code style, like its readability and if it follows convention would also be of help.
`import random
import string
import secrets
class User():
def __init__(self, username, credentials, password_dict) -> None:
self.credentials = {}
self.password_dict = {}
def passGen(self, passDicts):
n = int(input('Define password length. Longer passwords are safer.'))
source = string.ascii_letters + string.digits
password = ''.join((random.choice(source) for i in range(n)))
print('Password has been generated!')
print('Would you like to save this password? Type y or n: ')
yon = input()
if yon == 'y':
site = input('Please enter the site password is to be used:')
self.password_dict[site] = password
if yon == 'n':
print('Okay')
main()
return self.password_dict
#^Generates a new password for a given site and saves it to the users password (dictionary) collection
def Credentials(self, credentials):
username = str(input('Enter username: '))
password = str(input('Enter password for your account'))
if username in credentials:
print('')
self.credentials[username] = password
def main():
choice = input()
if choice == '1':
login()
if choice == '2':
`
#^^^
main() above is to display the menu and take the user to their saved passwords. Choice 1 is
login and choice 2 is exit. This will take the user to a menu where the can check passwords, download password dictionary as a text file, or edit existing passwords for a specified site.
I'd format it as following:
import random
import string
import secrets
class User():
def __init__(self, username, credentials, password_dict) -> None:
self.credentials = {}
self.password_dict = {}
def Credentials(self, credentials): # save username and password
username = str(input('Enter username: '))
password = str(input('Enter password for your account'))
if username in credentials:
print('')
self.credentials[username] = password
def passGen(self, passDicts): # random password generator
n = int(input('Define password length. Longer passwords are safer.'))
source = string.ascii_letters + string.digits
password = ''.join((random.choice(source) for i in range(n)))
print('Password has been generated!')
print('Would you like to save this password? Type y or n: ')
yon = input()
if yon == 'y':
site = input('Please enter the site password is to be used:')
self.password_dict[site] = password
if yon == 'n':
print('Okay')
main()
return self.password_dict
def main():
choice = input()
if choice == '1':
login()
if choice == '2':
loginUsername = input("Enter Username: ")
loginPassword = input("Enter PASSWORD: ")
data=open('database.txt', 'r')
accounts = data.readlines()
for line in data:
accounts = line.split(",")
if (loginUsername == accounts[0] and loginPassword == accounts[1]):
print("LOGGED IN")
else:
print("Login FAILED")
print(accounts)
I want to make a text login system, which will ask for the username first. After checking the text file which stored username and password, the system will ask for password. But I don't know how to read the first column (which is username, the structure of the text file is "username, password"). If i use readlines() and split(","). But there is "n" at the end of the password.
# You should always use CamelCase for class names and snake_case
# for everything else in Python as recommended in PEP8.
username = input("Enter Username: ")
password = input("Enter Password: ")
# You can use a list to store the database's credentials.
credentials = []
# You can use context manager that will automatically
# close the file for you, when you are done with it.
with open("database.txt") as data:
for line in data:
line = line.strip("\n")
credentials.append(line.split(","))
authorized = False
for credential in credentials:
db_username = credential[0]
db_password = credential[1]
if username == db_username and password == db_password:
authorized = True
if authorized:
print("Login Succeeded.")
else:
print("Login Failed.")
The "n" at the end of the password is probably the newline character \n. In order to remove it, you can use the rstrip() function:
mystring = "password\n"
print(mystring.rstrip())
>>> 'password'
I'm trying to create a simple login sequence in terminal but I can't figure out how to check if both the username and the password are in the same position in the list
usernames = ['username', 'hello']
passwords = ['password', 'world']
# my code so far:
from getpass import getpass
import time
import logins
username = input('Username: ')
password = input('Password: ')
print('Logging In...')
time.sleep(1)
def check_login(user, pasw):
if user in logins.users and pasw in logins.passes:
print('Valid')
else:
print('Invalid user and password, try again.')
check_login(username, password)
#It works except for the fact that i can input (username, world) or (hello, password)
#I'm trying to check that each username and password are in the same order (0,0, 1,1, etc) and
#return it as valid. Any help is appreciated :)
You can use zip:
def check_login(user, pasw):
if (user, pasw) in zip(logins.users, logins.passes):
print('Valid')
else:
print('Invalid user and password, try again.')
If you are to call this method repeatedly, it is better to create a O(1) lookup structure:
lookup = dict(zip(logins.users, logins.passes))
def check_login(user, pasw):
if lookup.get(user, None) == pasw:
print('Valid')
else:
print('Invalid user and password, try again.')
From what I get about this question, you can just check their indices using index inbuilt to lists to assert if both the user and password are at the same location.
def check_login(user, pasw):
if user in logins.users and pasw in logins.passes and logins.users.index(user)==logins.passes.index(pasw):
print('Valid')
else:
print('Invalid user and password, try again.')
This question already has answers here:
Simple boolean inequality operators mistake
(6 answers)
Closed 4 years ago.
I had previously made a simple logging in code and it was working but when i went to separate data from the code to another .py file and import it, it will not progress passed the "username: " input part (it keeps loading the input for username). Does that mean that the file is not being imported correctly or is it in the main code?
Login.py
print ("Loading please wait...")
import logindata
import inputdata
import time
time.sleep(1.5)
username = ""
while username != logindata.user1 or username != logindata.user2:
print ("Username: ")
username = input()
password = ""
while password != logindata.passw1 or password != logindata.passw2:
print ("password")
password = input()
if username == logindata.user1 and password == logindata.passw1:
print ("Logging in...")
time.sleep(3)
print ("Welcome, user1!")
if username == logindata.user2 and password == logindata.passw2:
print ("Logging in...")
time.sleep(3)
print ("Welcome, user2!")
logindata.py
#Login Data#
user1 = "user1"
passw1 = "pass1"
user2 = "user2"
passw2 = "pass2"
############
It was previously working before i added a second "user" to it.
The issue is in this line:
while username != logindata.user1 or username != logindata.user2:
If user1 and user2 are different, than the condition will always evaluate to false. You'll want to use and rather than or.
Also, you'll probably want to connect the username & password, and not allow user1 to login with the password for user2 and vice versa ...
Change the or to an and.
username = ""
while username != logindata.user1 and username != logindata.user2:
print ("Username: ")
username = input()
password = ""
while password != logindata.passw1 and password != logindata.passw2:
print ("password")
password = input()
When you type in something that matches logindata.user1, user != logindata.user2 evaluates to True and the loop continues. Therefore, you need the username to not match both logindata.user1 and logindata.user2. Same goes for the password.
This is the part where the user logs in into the game. The database is hosted on mlab, there is a collection of documents named loginInfo defined as mycol.
The problem that I am facing is that when it returns the id, I have no way of checking if it is a valid one since I would not be able to check with any sort of local list in Python. How do I fix it?
import pymongo
def login():
print('Login\nRegister\nPlay as Guest')
login_input = input('What would you like to do?')
if login_input == 'Login':
username = input('Username:')
username_fromDB = mycol.find({"username": username})
if username_fromDB == username:
password = input('Password:')
password_fromDB = mycol.find({"password": password})
if password == password_fromDB:
print('Login success!\n')
mainMenu()
elif login_input == 'Register':
new_username = input('Username:')
new_password = input('Password:')
tobeaddedtodb = {"username": new_username, "password": new_password}
adding = mycol.insert_one(tobeaddedtodb)
print("Registered!\n")
elif login_input == 'Play as Guest':
mainMenu()
username_fromDB = mycol.find({"username": username})
This is wrong because find() returns a cursor object, not the username as you expect.
Assuming that loginInfo collection contains unique usernames and respective passwords, there's no need to make 2 find() queries to database. You can just retrieve a user entity and check if input-provided password matches the one stored in database.
And since usernames are unique, you should use find_one() instead of find(). If user was successfully found it returns dict, otherwise you get None.
Try something like this:
import pymongo
def login():
print('Login\nRegister\nPlay as Guest')
login_input = input('What would you like to do?')
if login_input == 'Login':
username_inp = input('Username:')
pwd_inp = input('Password:')
user_found = mycol.find_one({"username": username_inp}) # query by specified username
if user_found: # user exists
if pwd_inp == user_found['password']:
print('Login success!\n')
mainMenu()
else:
print('Wrong password')
else:
print('User not found')
elif login_input == 'Register':
new_username = input('Username:')
new_password = input('Password:')
tobeaddedtodb = {"username": new_username, "password": new_password}
adding = mycol.insert_one(tobeaddedtodb)
print("Registered!\n")
elif login_input == 'Play as Guest':
mainMenu()