I'm using Python 3.6.3.
I am trying to validate a username and password from a csv file. The usernames and subsequent passwords are on new lines in the text file, so when appended to an empty array I called "up" it was turned into a 2d array with each line a list within "up". I ask the user for a username and a password. So then I tried to use a for loop (for x in up) to loop over each list in up via up[up.index(x)], and then used .index(username) straight afterwards in a variable called j (j = up[up.index(x)].index(username)). The code will be given, with the section I'm having trouble with highlighted.
These are the contents of the csv file: Text File
When I run the code the it returns an error that says the username in not in the list. I've searched for answers but couldn't find anything. Is there something that I've overlooked?
Any help will be gratefully appreciated.
import csv
validoption = ["i","u"]
while True:
option = input("Sign in or sign up\nPlease enter 'i' to sign in or 'u' to sign up: ")
if option in validoption:
if option is "i":
with open("login.txt","r") as l:
up = []
read = csv.reader(l)
count = 0
for line in read:
up.append(line)
count=+1
invalid = True
while invalid:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if [[y is username for y in x] for x in up]:
for x in up:
j = up[up.index(x)].index(username)
if password in up[up.index(x)][j+1]:
invalid = False
else:
print("Password is incorrect")
else:
print("Username is not recognised")
else:
with open("login.txt","a") as l:
username = input("Please enter your username: ")
while True:
password = input("Please enter your password\nPlease make sure that your password is longer than 8 characters, has a capiatal letter and a number: ")
if len(password)<8:
if any(p.isupper() for p in password):
if any(p.isdigit() for p in password):
break
else:
print("Password must have one number in it\n")
else:
print("Password must have one capital letter\n")
else:
print("Password must have more than 8 charaters")
userdetails = username+","+password
l.write(userdetails)
l.write("\n")
Thank you :)
y is username tests if the two values are the same object, not equivalent objects. Use == instead.
Additionally, you should consider using the username as the key of a dict, then you can use in and eliminate some of the loops in your application code.
Related
branching off from my previous question. How can i import data from a text file and then store it in a dictionary with a specific key such as:
there is a space between each username and password but they appear directly below each other on text file
Text file:
username,password
user2,password2
user3,password3
into a dictionary in python as follows:
Database = {username: password,user2: password2,user3: password3}
which i can then use in a log in validificator to confirm wheter both username and password is correct
So you have a user/pwd pair per line? You can loop through the lines of your files and split with ,:
db = {}
with open("file.txt", "r") as f:
for l in f.readlines():
words = l.strip().split(',')
if len(words) > 1: # only considering lines with at least one comma
db[words[0]] = words[1]
I'm using Flask and trying to insert names (text) into an SQLite3 DB. The DB has one table (guests) and one column (name). However, it will only accept 1 character during the insert; anything more is failing.
If I hardcode 'nm' as a value, it still fails, so I don't think it's the Html template. I can manually add a value of varying length to the DB with the 'DB Browser' app, so I'm really at a loss here. Here's a code snippet.
#app.route('/addrec', methods=['POST', 'GET'])
def addrec():
msg = "msg"
if request.method == 'POST':
try:
nm = request.form['nm']
with sqlite3.connect("database.db") as con:
cur = con.cursor()
cur.execute('''Insert into guests values (?)''', nm)
con.commit()
msg = "Record successfully added"
Second argument to cur.execute should be a tuple:
cur.execute('''Insert into guests values (?)''', (nm,))
Why? If, for example, you call that argument arg then arg[0] is the string value you require (nm): the first item in that tuple.
Otherwise (when passing nm instead of the tuple) it will read nm[0] which is the first character of the string nm.
The program is about finding factors and if the user enters a special character or an alphabet it will show an error and I wanted to ask the user to try again "Invalid input please try again" after the error shows and also after the program shows the factors I wanted the user to have the chance to find another factor again "Try again? Yes/No"
I've tried the
while True:
if input("Try Again? (Yes/No)").strip().upper() == 'No':
break
but i don't know how to make it work.
Any other solutions will do
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
try:
num = int(input("Enter a number: "))
print_factors(num)
except ValueError:
print("Sorry, I didn't understand that.");
The program works and I just wanted to put some add ons
while True:
try:
num = int(input("Enter an integer (0 to exit): "))
if num == 0:
break
print(num)
except ValueError:
print("Sorry, you must enter an integer")
So I made this very small function. it is a bonehead easy function but frankly borderline my capabilities.. Im learning. The function works as expected, but I would like to go further. I would like to make it so I can either give it an argument (a username) and just get the information for that single user, or default to reporting all users. is this possible w/o starting over from what I have so far?
I have just poked around and seen some examples but nothing that I can fit into my script. that I can understand at least.
import boto3
iam = boto3.client('iam')
def user_group():
for myusers in iam.list_users()['Users']:
Group = iam.list_groups_for_user(UserName=myusers['UserName'])
print("User: " + myusers['UserName'])
for groupName in Group['Groups']:
print("Group: " + groupName['GroupName'])
print("----------------------------")
user_group()
I would like to have the ability to run this script in two fashions.
1) add an argument(s) of 'username' so I can get the response for a particular user
2) default to getting response for all users if no argument is given.
This can be done by using an argument with a default value:
def user_group(user = None):
if user is None:
print("No user")
else:
print(user)
user_group()
user_group('some user')
prints
No user
some user
In your case you may want to write
def user_group(user = None):
users_to_list = iam.list_users()['Users'] if user is None else [user]
for myusers in user_to_list:
...
I am a new python user and have recently started working on a project to create a quiz in python. I want to make an account for every person who takes the quiz. I'm saving all the user names and passwords in a text file and the program will check the file for the user name and password if a user wants to log in. This is my code but when I run it it prints an output for every line on text in the file. I want just one output based on the whole file. Does somebody know how to fix this?:
choice = input("are you registered user?")
if choice == "1":
age = input ("age? ")
name = input ("name? ")
yrgroup = input("yr group? ")
username = name[:3] + age
print ("your username is ", username)
password = input ("password? ")
students = open("students.txt","a")
students.write(password)
students.write(" ")
students.write(age)
students.write(" ")
students.write(yrgroup)
students.write(" ")
students.write(username)
students.write(" ")
students.write(name)
students.write(" ")
students.write("\n")
students.close()
elif choice == "2":
user = input ("please enter your username: ")
pas = input ("please enter password: ")
with open("students.txt","r") as file:
for line in file:
word = line.split(" ")
if pas in word:
print ("LOGGING IN")
else:
print ("WRONG")
else:
print("invalid input")
It prints this when I run it:
hello everyone
are you registered user?2
please enter your username: ale15
please enter password: meow
WRONG
WRONG
WRONG
LOGGING IN
I need it to output just one line that says whether it's wrong or logging in.
You can do
user = input ("please enter your username: ")
pas = input ("please enter password: ")
result = False
with open("students.txt","r") as file:
for line in file:
word = line.split(" ")
if pas in word:
result = True
if (result):
print('LOGGIN IN')
else:
print('WRONG')