Python repeating wrong username loop - python

I'm trying to make a system that checks for a user name in a separate text file, and if it doesn't exist tell them this and prompt them to re enter the password. This works the first time they get the username incorrect, however subsequent times it repeats the message multiple times.
Here is the code I have so far:
def existingUser():
annoyingProblem = 0
print("Welcome back")
while True:
existingUsername = input("What is your user name?")
for i in range(100):
with open("logins.txt", "r") as logins2:
for num, line in enumerate(logins2, 1):
if existingUsername in line:
correctPassword()
else:
if annoyingProblem == 99:
print("That doesn't seem to match. Please try again")
else:
annoyingProblem = annoyingProblem + 1

If I understood correctly you want to check whether the given username is valid , and if its wrong you want give 99 chances to user
input.txt
sandeep
lade
venkat
Code(here max chances are 3)
def existingUser():
annoyingProblem = 0
print("Welcome back")
while True:
existingUsername = str(raw_input("What is your user name?"))
with open("infile.txt", "r") as logins2:
for num, line in enumerate(logins2, 1):
if existingUsername in line:
correctPassword()
print("That doesn't seem to match. Please try again")
annoyingProblem = annoyingProblem + 1
if annoyingProblem == 3:
print("exceeded number of attempts")
break
Output
>>> existingUser()
Welcome back
What is your user name?nope
That doesn't seem to match. Please try again
What is your user name?nope
That doesn't seem to match. Please try again
What is your user name?nope
That doesn't seem to match. Please try again
exceeded number of attempts

I don't even know how that compiles, as long as you have an "else" in a different tab column than the "if". Maybe that can be your problem, as you are testing things in a way you don't want. Also, existing username is read once and is not changed. So the "if" will be true a hundred times!

I think you dont have to use all the looping stuff. As each username is a line.. we can use the below as the file probably will not be huge.. like 100mb..
def existingUser():
existingUsername = input("What is your user name?")
if existingUsername in open('logins.txt').read():
correctPassword()
else:
print("That doesn't seem to match. Please try again")

Related

How to find specific words in a separate text file? (PYTHON)

Im doing a homework assignment and will need to locate a specific word in python. Any help would be much appreciated. I am quite new to coding. I would like help on how to answer this question.
I have seen multiple tutorial's but none have helped me so far.
y=()
answer=str(input("Do you want to create an account, y or n?"))
if answer=="y":
file = open("database.txt", "r")
username = input("Enter a username :")
password = input("Now enter a password :")
file = open("database.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
else:
username1=input("Enter your username:")
password1=input("Now enter your password:")
for line in open("database.txt","r").readlines():
login_info = line.split()
if username1 == login_info and password1 == login_info:
print("Incorrect")
else:
print("Correct")
I expected the output to say correct when all the criteria is met but instead it outputs correct when i enter anything.
The indentation in the second part of your code is messed up, because the if- and else-statement should be inside of the for loop. Also you split the loaded lines into a list (login_info) but incorrectly check that against the username and password variables. And you use the default split() function which uses a whitespace as a separator, but you use a comma. I also put the else statement out of the for loop, because otherwise it will print every time the line is not the one where the user is stored. Try this for the second part:
else:
username1=input("Enter your username:")
password1=input("Now enter your password:")
for line in open("database.txt","r").readlines():
login_info = line.split(",")
if username1 == login_info[0] and password1 == login_info[1].replace("\n", ""):
print("Correct")
break #Exit the for loop if the user is found
else: #Only executed when break is not called
print("incorrect")

How can I see if my password variable is within a line so that my code can proceed?

I am creating a password re-setter for school, and i want to check that if the password is within the first line of the text file, then it can say "Okay, choose a new password")
Newpass=""
Network=""
setpass=""
Newpass=""
password=""
def newpass():
Network=open("Userandpass.txt")
lines=Network.readlines()
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password in line:
newpass=input("Okay, choose a new password ")
Network.close()
Network=open("Userandpass.txt","a")
if len(newpass)>= 8 and newpass[0].isalnum()==True and newpass[0].isupper()==True:
print('password change successful')
Network.write("New Password : " + newpass )
Network.close()
break
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
Network=open("Userandpass.txt","w")
Network.write(input("What is your Username")+",")
Network.write(input("Password:")+ ",")
question=input("Do you want to change your password?")
if question=="yes":
Network.close()
newpass()
else:
Network.close()
print("Okay thank you.")
Please help! I have been looking all over here and i can't find a solution
You can try by two things :
lines=Network.read() # change here
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password == lines.split(",")[1]: # change here also
Explanation :
The problem with readlines is o/p as list where read return as string which is better one to use here .
The second thing it returns as a single string ie, combined form of name and password just with ,. So if you split it you will get an list of separated values. Then you can take only password from it and check with input.
In your code you are just checking the input element is just present in that whole string, not checking whether it is same password or not
You said you needed this for school, so i assume it's somewhat urgent:
All the changes i did are minor and i commented what i did and why.
# no need to intialize these variables
#Newpass=""
#Network=""
#setpass=""
#Newpass=""
#password=""
def newpass():
# the with open() construct takes care of closing the file for you and gives you a nice handle for working with the file object.
with open("Userandpass.txt") as Network:
# this reads all filecontents into a list and while doing so strips away any kind of whitespace.
username,current_password=[x.strip() for x in Network.readlines()]
for i in range (3):
password=input("just to confirm it is you, re-enter your old password: ")
if password == current_password:
# communicate the requirements instead of letting potential users run into errors
newpass=input("Okay, choose a new password (must be 8 chars or more, alphanumeric and have it's first letter capitalized.) ")
if len(newpass)>= 8 and newpass.isalnum() and newpass[0].isupper():
with open("Userandpass.txt","a") as Network:
print('password change successful')
Network.write("New Password : " + newpass )
return
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
with open("Userandpass.txt","w") as pwfile:
# separate by newline instead of punctuation => personal preference
pwfile.write(input("What is your Username? ")+"\n")
pwfile.write(input("Password: ")+ "\n")
question=input("Do you want to change your password? (yes/no): ")
if question[0].lower() == 'y':
newpass()
else:
print("Okay thank you.")
# properly terminate
exit(0)
You are missing an 's' in the line
if password in line**s**:
maybe the problem comes from there.

Python pickles not storing data

I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

Nothing happens for either input

I have a feeling I've made a silly mistake somewhere but at nearly 2am I just can't see it...
Here's the code in question. It is part of a function:
running = True
while (running):
playerName = input("Please enter your first name \n").title()
print ("You have entered '%s' as your name. Is this correct?"%playerName)
playerNameChoice = input("Enter 'Y' for Yes or 'N' for No.\n").upper()
if(playerNameChoice == "Y"):
break
#The following randomly selects Card 1 for the computer
randomComputerCard = random.choice(availableCards)
if randomComputerCard in (Queen,King,Jack,Ace):
randomComputerCard = 10
else:
randomComputerCard = randomComputerCard
randomComputerCard2 = random.choice(availableCards)
if randomComputerCard2 in (Queen,King,Jack,Ace):
randomComputerCard2 = 10
else:
randomComputerCard2 = randomComputerCard2
print ("%i"%randomComputerCard)
print ("%i"%randomComputerCard2)
print ("TEST OVER")
elif(playerNameChoice == "N"):
continue
During testing when I enter Y when prompted to enter either Y or N nothing happens, it just continues the loop when it should actually break. However when I enter N it does exactly what it's meant to and continues the loop. Sorry if this is a waste of a question, but I actually have no idea what I've done incorrectly.
Thanks in advance as always! :)
EDIT: The variable availableCards has already been defined.
You need to remove the 'break' at line 7. That's causing your code to exit prematurely.

Categories

Resources