Python password system with lock after certain number of attempts - python

So I am trying to create a password system in Python, whereby after a certain number of incorrect attempts, the user will be blocked from accessing it for, say, 5 minutes. I am currently unsure how the values of the variables can be kept after rerunning the same file and then used in this manner. Could someone help me with this, as I am currently still new to Python?
Update:
After experimenting for a while with the code Jonas Wolff provided me I finalised my code to the following:
def password():
count = 0
currentTime = float(time.time())
passwordList = ["something", "password", "qwerty", "m42?Cd", "no"]
passwordNum = random.randint(0, 4)
password = passwordList[passwordNum]
with open("password.txt", "r") as file:
check = file.readline()
initialTime = file.readline()
if initialTime=="":
initialTime==0
if int(check)==1 and (currentTime-float(initialTime))<300:
print("You are still locked")
print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
quit()
print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
while count<5:
inp = input("Enter the Password: ")
if inp==password:
print("Access Granted")
print()
f = open("password.txt", "w")
f.write("0\n0")
f.close()
select()
elif (count+1)==5:
print("You have been locked")
print("Please try again in 5 minutes")
f = open("password.txt", "w")
f.write("1\n")
f.write(str(currentTime))
f.close()
quit()
else:
count+=1
print("Incorrect Password")
print("You have", 5-count, "tries left.")
continue
Thanks a lot for the help you have provided and the patience with which you answered my questions.

import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time
pswd = "something"
count = 0
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
numa = file_info.count("1")
count = numa
while True:
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
tima = file.readline()
inp = input("What is the password:")
if inp == pswd:
if tima == "":
tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed
if str(file_info[:5]) != "11111" or time.time() > float(tima):
YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
f = open("PhysxInit.txt", "w")
f.write("\n")
f.close()
break
else:
count += 1
f = open("PhysxInit.txt", "w")
f.write(("1"*count)+"\n"+str(tima))
if count == 5:
f.write(str(time.time()+60*5))
f.close()
#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()
does this work?
just make sure you have a text file called PhysxInit.txt
after running the program, and having guessed wrong a few times my txt file look like this.
11111
1536328469.9134998
it should look something like mine though the numbers may be diffrent.
To read a specific line as you requested you need to do:
with open("PhysxInit.txt", "r") as f:
for w,i in enumerate(f):
if w == #the number line you want:
# i is now the the line you want, this saves memory space if you open a big file

Related

In Python, How can I create a while loop using input + 'filename'

I am wanting to create a loop for my book reader so that when the user inputs a number other than 1-10, an error message comes up, and when they press 0 the program quits. However, an error message appears saying FileNotFoundError: No such file or directory: '11.txt'(etc)
import time
option = str(input('Which Book would you like to read? (1-10): '))
while option !=0:
number_of_words = 0
f=open(option + '.txt', encoding='utf-8')
file_contents=f.read()
lines = file_contents.split()
number_of_words += len(lines)
print('Word Count:',number_of_words)
time.sleep(2)
f=open(option + '.txt', encoding='utf-8')
for line in f:
print(line)
time.sleep(0)
else:
print("404 file not found")
print()
option=str(input('Which Book would you like to read?(1-10):'))
print("Goodbye")
Try this:
import time
while True:
try: # Wrap the input in a try except and try to convert it directly to an integer.
option=int(input('Which Book would you like to read? (1-10): '))
except:
print("Please only enter a number.")
continue
if option == 0:
print("Goodbye")
break
if option > 10:
print("Invalid book entered, try again, must be between 1 and 10.")
continue
with open(str(option) + '.txt', encoding='utf-8') as f: # Use a context manager to open files, it will make sure your files are closed after opening
file_contents=f.read()
number_of_words = len(file_contents.split())
print('Word Count:',number_of_words)
time.sleep(2)
for line in file_contents:
print(line)
Results:
Which Book would you like to read? (1-10): few
Please only enter a number.
Which Book would you like to read? (1-10): 121
Invalid book entered, try again, must be between 1 and 10.
Which Book would you like to read? (1-10): 0
Goodbye

How to use sys.exit() if input is equal to specific number

I am looking to correct this code so that when the user inputs 99999 then the code stops running, im also looking to make it so that if the user input is 999 it sets the total to 0
import sys
def money_earned():
total = int()
try: # try open the file
file = open("total.txt", "r")
data = file.readline()
total = int(data)
except: # if file does not exist
file = open("total.txt", "w+") # create file
total = 0
file.close() # close file for now
while True:
try:
pay_this_week = int(input("How much money did you earn this week? "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
pay_this_week_message = "You've earned £{0} this week!".format(pay_this_week)
total = pay_this_week + total
total_message = "You have earned £{0} in total!".format(total)
print(pay_this_week_message)
print(total_message)
if pay_this_week == "99999":
sys.exit()
file = open("total.txt", "w") # wipe the file and let us write to it
file.write(str(total)) # write the data
file.close() # close the file
money_earned()
So you're taking the input as a string and immediately converting it to an int, but you could actually convert it to an int later and check for some words in your input first.
Right now you have
pay_this_week = int(input("..."))
but if you change this to
input_from_user = input("...")
pay_this_week = int(input_from_user)
then we can add some more code inbetween
input_from_user = input("...")
if input_from_user == "done":
return # this will exit the function and so end execution
elif input_from_user == "reset":
total = 0 # reset the total
else:
pay_this_week = int(input_from_user)
this should have the desired effect

(Python) How to test if a string is contained in a file

I'm trying to create a username database and the code all runs how I want except for when I try to test if the file contains the entered text. For some reason it just runs past the elif statement and hits the else statement if it already exists in the text.
Here is the full code:
class username:
def add():
while(True):
file = open("usernames.txt", 'r+')
names = list(file.read())
entered = str(input("Username: "))
if len(entered) == 0:
print("Please enter a valid username\n")
continue
elif not(entered.isalpha):
print("Please enter a valid username\n")
continue
elif entered in file.read():
print("That name is already in use.",
"\nPlease enter a different username. \n")
continue
elif len(entered) < 4 or len(entered) > 12:
print("Please enter a username with 4-12 characters.\n")
continue
else:
print(entered)
file.close()
add = open("usernames.txt", 'a+')
plusnewline = entered + "\n"
add.write(plusnewline)
add.close()
break
def list():
file = open("usernames.txt","r+")
names = file.read()
print(names)
file.close()
username.add()
username.list()
edit: Answered by Shadow:
Changed:
names = list(file.read())
to:
names = file.read()
and changed:
elif entered in file.read():
to:
elif entered in names:
You can only call file.read once - after that it's already read.
Either use file.seek(0) to go back to the start of the file (which will allow you to read it again), or cache the contents in a variable so that you can reuse it (that is, refer to your names variable)

How do I allow only the latest inputs to be saved - Python

How do I implement a simple code that will only save the student's latest 3 scores? If the test is repeated later, the old score should be replaced.
Thank you.
This is the code that asks the user the questions and saves the results in the txt. files.
import random
import math
import operator as op
correct_answers = 0
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(username))
class_name = input("Are you in class 1, 2 or 3? ")
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} questions correct.".format(
username,
correct_answers,
num_questions,
))
class_name = class_name + ".txt" #creates a txt file called the class that the user entered earlier on in the quiz.
file = open(class_name , 'a') #These few lines open and then write the username and the marks of the student into the txt file.
name = (username)
file.write(str(username + " : " ))
file.write(str(correct_answers))
file.write('\n') #This puts each different entry on a different line.
file.close() #This closes the file once the infrmation has been written.
A much better solution would be to store the data in a different format that made everything easy. For example, if you used a shelve database that mapped each username to a deque of answers, the whole thing would be this simple:
with shelve.open(class_name) as db:
answers = db.get(username, collections.deque(maxlen=3))
answers.append(correct_answers)
db[username] = answers
But if you can't change the data format, and you need to just append new lines to the end of a human-readable text file, then the only want to find out if there are already 3 answers is to read through every line in the file to see how many are already there. For example:
past_answers = []
with open(class_name) as f:
for i, line in enumerate(f):
# rsplit(…,1) instead of split so users who call
# themselves 'I Rock : 99999' can't cheat the system
name, answers = line.rsplit(' : ', 1)
if name == username:
past_answers.append(i)
And if there were 3 past answers, you have to rewrite the file, skipping line #i. This is the really fun part; text files aren't random-access-editable, so the best you can do is either read it all into memory and write it back out, or copy it all to a temporary file and move it over the original. Like this:
excess_answers = set(past_answers[:-2])
if excess_answers:
with open(class_name) as fin, tempfile.NamedTemporaryFile() as fout:
for i, line in enumerate(fin):
if i not in excess_answers:
fout.write(line)
os.replace(fout.name, fin)
That part is untested. And it requires Python 3.3+; if you have an earlier version and are on Mac or Linux you can just use os.rename instead of replace, but if you're on Windows… you need to do some research, because it's ugly and no fun.
And now, you can finally just append the new answer, as you're already doing.

Use values saved to a file in order to compute mean/median/mode/etc

I have a program that saves a file that you can write values to. What I am trying to do is use the saved files to calculate my mean/median/mode and to be able to delete values. functions. I am able to add values to the file through the open("filename","a")...but how do I make it so that I am able to import the file values to calculate my other functions?
Sorry its so long, but if anyone can help I would really appreciate it, I am new to figuring out File IO a stuff.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
def main(filename):
print("Now what would you like to do?")
print("--------------------------------------------------------------------------------")
print("Press 1 if you would like to ADD a Value to your list")
print("Press 2 if you would like to DELETE a Value from your list according to its value")
print("Press 3 if you would like to DELETE a Value from your list according to its location")
print("Press 4 if you would like to DISPLAY your List")
print("Press 5 if you would like to COMPUTE MEAN for your list")
print("Press 6 if you would like to COMPUTE MEDIAN for you list")
print("Press 7 if you would like to COMPUTE MIDPOINT for you list")
print("Press 8 if you would like to COMPUTE MODE(S) for your list")
print("Press 9 if you would like to COMPUTE STANDARD DEVIATION for your list")
print("Press 10 if you would like to READ values from a FILE you have made")
print("Press 0 if you would like to EXIT")
print()
execute = int(input("which action would you like to do next?"))
if execute == 1:
add_Values(filename)
if execute == 2:
remove_Value_List(filename)
if execute == 3:
del_Value_Location(filename)
if execute == 4:
read_file(filename)
if execute == 5:
computing_Mean(filename)
if execute == 6:
computing_Median(filename)
if execute == 7:
computing_Midpoint(filename)
if execute == 8:
computing_Modes(filename)
if execute == 9:
computing_Standard_Dev(filename)
if execute == 10:
read_file(filename)
if execute == 0:
print()
print("That's too bad I was having so much fun...but okay...bye!")
if execute >= 12:
print("Sorry but that is not one of the options")
if execute <= -1:
print("Sorry but that is not one of the options")
def add_Values(filename):
fout = open(filename,"a")
again = 'y'
while again == 'y':
fout.write(input("Enter a number you want to write to the file:")+"\n")
print("Do you want to add another number?")
again = input("y = yes, anything else = no:")
fout.close()
print("The numbers have been saved to the file")
main(filename)
def remove_Value_List(filename):
fout = open(filename, "r")
fout.readlines()
remove = "y"
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = float(input("Which value should I remove?"))
try:
values.remove(number_list)
print("Here is the revised list:")
print()
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def del_Value_Location(filename):
remove = "y"
fout = open(filename,"r")
fout.readlines()
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = int(input("Which position should I remove?"))
try:
del values[number_list]
print("Here is the revised list:")
read_file_one(filename)
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += float(line.strip())
print ("Mean value is:" (summ/cnt))
def computing_Median(filename):
fin = open(filename,"r")
fin.readlines()
ordered = sorted(filename)
length = len(filename)
print("The median of this list is:")
print(float((ordered[length//2] + ordered[-(length+1)//2]))/2)
main(filename)
def computing_Midpoint(filename):
with open(filename,"r") as fout:
filename.sort(key=int)
minNum = min(float(filename))
maxNum = max(float(filename))
print("The midpoint of this list is:")
print((minNum + maxNum) / 2)
main(filename)
def computing_Modes(filename):
from collections import Counter
data = Counter(filename)
print("The Mode(s) of this list is/are:")
print(data.most_common(1))
main(filename)
def computing_Standard_Dev(filename):
mean = sum(filename)/len(filename)
for i in values:
total = 0
newDev = i - mean
squared = newDev**2
total = (total + squared)
divider = (total/(len(values)-1))
standardDev = divider**.5
print("The standard deviation is:")
print(standardDev)
main(filename)
def read_file(filename):
fin = open(filename, 'r')
L = fin.readlines()
for ix in range(len(L)):
L[ix]=L[ix].strip()
while "" in L:
L.remove("")
for ix in range(len(L)):
L[ix]=float(L[ix])
fin.close()
print(L)
main(filename)
main(filename)
There are lots of errors in your code which are very similar to each other so I will explain only one of those similar ones and you should fix others by examining fixed one.
For startes you are opening a file named filename. Using quotes around it makes it a string. You should use it like this:
def add_Values(filename):
fout = open(filename,"w")
But using with statement to open files is much more better because file is closed automatically even if exception is raised.
def add_Values(filename):
with open(filename) as fout:
#do smth
There is no file to work with in def del_Value_Location(filename): and some others. You should open your file in those as well.
To make calculations you need read your data from your file. Which can be achieved by using file.readlines()
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += int(line.strip())
print ("Mean value is: %.1f" % (summ/cnt))
If you want to change how many digits you want to see, you should change %.1f part.
With this you should fix your other computations by yourself.
About menu, you can do something like this to make it appear again without using a second function.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
#exclude this filename in main and use it as `main`s argument.
def main(filename):
print("Now what would you like to do?")
Ofcoure after this, you should change all main_two()s to main(filename).

Categories

Resources