How do I get code to repeat its inputs - python

Basically, I want this code to keep asking me for the inputs until I close the page. Just started learning Python today so sorry if this is written really bad. Written in Python 3.5, and saves the passwords you enter into it in a text document so you can remember them.
website = input("Enter what website the password is for ")
username = input("Enter your username ")
password = input("Enter your password ")
textfile = open("usernames.txt", "a")
textfile.write(website+" ")
textfile.write(username+" ")
textfile.write(password+"\n")
textfile.close()

Simple way is,
while True:
<Your Code.....>
Infinite loop.

Related

Assistance with a Login System & Printing a Text File

I have a program that asks the user for a username and password, then checks a text file to see if that username/password are in there. Then it is supposed to print the contents of the text file to screen. A couple of issues:
It ALWAYS takes two attempts to successfully log in, even if the username/password are correct.
On successful login, the contents of the text file are not printed.
Would very much appreciate some guidance on why these things are happening, and how they can be resolved!
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
fileRead=open('accounts.txt','r')
fileContents = fileRead.read()
flag=False
while True:
line=fileRead.readline()
lineLength=len(line)
if lineLength==0:
break
lineItem=line.split()
if username.strip()==lineItem[0] and password.strip()==lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print(fileContents)
flag=True
break
if flag==False:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
I would try something like this.
def print_file_contents(file_name):
with open(file_name) as f:
for line in f:
print(line)
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
file = 'accounts.txt'
flag = False
for line in open(file).readlines():
lineItem=line.split()
if username.strip() == lineItem[0] and password.strip() == lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print_file_contents(file)
flag=True
break
if not flag:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
However I haven't really modified what the code does, and I suspect the issue comes with how the text file is formatted.
I also assume this is a project and not actual passwords stored in a .txt file which wouldn't be a great idea.

Python If Statement question login system easy

The first thing to do is write "1" and then enter username and password. After that, the max number of account is 1 and you can then use the "2" to login.
First time asking a question so I am sorry if this is like a dumb question or something. My code is as following:
https://imgur.com/a/dAaYf2u - NEW LINK
Code:
print("Type 1 for Create user. Type 2 for login")
Choice = input("Number here: ")
if Choice == ("1"):
print("Welcome to the Create a user interface")
Username = input("Username: ")
Password = input("Password: ")
if Password.count("!") > 0:
print("Not valid - no special characters!")
else:
file = open("account.txt", "w")
file.write(Username)
file.write("\n")
file.write(Password)
file.close()
elif Choice == ("2"):
print("Welcome, please type your Username and Password")
Loginu = input("Write username here: ")
Loginp = input("Write password here: ")
file = open("account.txt", "r")
first_line = file.readline()
if Loginu == first_line:
print("you're logged in")
else:
print("fail")
It's very basic and so on. What I don't understand is why the if Loginu == first_line can't read the first_line variable... It just jumps directly to else:
I hope it helps and I know my code is very basic lol.
My advice:
follow pep8, use meaningful names for variables
split your code into functions
use infinite loop for your "menu"
even better use some package that helps with building such applications (click?) rather then reinvent the wheel
Read your file with with open(...) as f: context manager
It's probably good idea to read whole file and build dictionary instead of depending on the login to be exactly identical with first line
use strip() to remove white characters (like newline)
check that line you are looking at is not empty
if you've opened file without context manager for writting, you need to close it before opening it again for reading
use debugger to check what's exactly result of readline

Program not working correctly (using Python) - Login Program

This is my code:
users = []
users.append([username, password])
usersFile = open("users.txt","w+")
for users in users:
usersFile.write("%s" % users)
usersFile.close()
def loginFunction():
userEntry = ""
foundName = 0
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
lines = usersFile.readlines()
usersLen = len(users)
for index in range (0, usersLen-1):
if userEntry == users[index, 0]:
foundName = 1
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == users[index, 1]:
print "Username and passwords are correct"
else:
print "incorrect"
userEntry = ""
if foundName == 0:
print "Username not recognised"
userEntry = ""
I have produced a program that registers the username and password of a user. I have checked the files and it saves the username and password successfully but when I try to login using the correct username that I know is in the file as a list, it still always comes up "Username not recognised". Any ideas as to why this might be?
It looks like you're writing out the user/passwords, as lists, as single lines in the file. Then when you read it back, each pair is read back as one string. readlines() doesn't automatically convert text back to a list object. If you want to do that, you might use Pickle instead. Pickle should let you save the entire users list of lists object all at once.
Also to be pythonic your for loop should iterate over the list directly. If you need the current index, use for i, user in enumerate(users). Using range(len(users)) is suboptimal in python. You can then use user[0] to get the username and user[1] for the password.
I've made a few changes to your program. Firstly, I've changed it to use the modern print function instead of the print statement. The print function is available in Python 2.6 and later. It's more powerful than the old print statement, and IMHO it's a good idea to start using it in preparation for Python 3 (which doesn't have the print statement).
To simplify reading & writing the username & password data we can use the standard csv module. It's not strictly necessary for this simple task, but it means we don't have to worry about the messy details of parsing the name and password strings. Eg, if the strings contain spaces or quotes, the csv will handle them correctly. Note that in Python 2 CSV files must be opened in binary mode, but in Python 3 they must be opened in text mode. This is rather annoying when you're trying to write code that runs correctly on both versions.
The easy way to look up a password given the username is to use a dictionary with the username as the key and the password as the value. This is much more efficient than scanning through a list row by row looking for a match.
Of course, in a real program we would never store passwords as plain text. That's extremely insecure! The usual procedure is to store a hashed version of the password, using a strong cryptographic hash function applied a very large number of times to make it a time-consuming operation. For further info please see PBKDF2, scrypt, and bcrypt.
Also, it's bad practice to let a potential attacker know that a username is valid but that the password they submitted is invalid. That allows them to easily build a list of valid usernames. Instead, you should always ask for the password, even if the username is invalid.
from __future__ import print_function
import csv
users = [
['Alice', 'aardvark'],
['Bob', 'bobcat'],
['Steve', 'swordfish'],
]
# Save the users list to a CSV file
users_filename = "users.txt"
with open(users_filename, "wb") as f:
writer = csv.writer(f)
writer.writerows(users)
def login_function():
# Load the usernames & passwords into a dictionary
with open(users_filename, "rb") as f:
users = dict(csv.reader(f))
# Give the user 3 chances to login
for i in range(2, -1, -1):
user_entry = raw_input("Enter your username: ")
password_entry = raw_input("Enter your password: ")
if user_entry in users and password_entry == users[user_entry]:
print("Username and password are correct")
return True
else:
print("Username and password are invalid")
print(i, "login attempts remaining")
print("Login failed")
return False
print(login_function())
demo
Enter your username: Alan
Enter your password: runner
Username and password are invalid
2 login attempts remaining
Enter your username: Alice
Enter your password: aardvark
Username and password are correct
True

Python prints None despite not being inside function

So I'm still relatively new to Python programming and so at the moment I'm just trying to create a simple password program. If the use has opened the program before, then it will skip the create a password bit. I have done this by creating a file which will contain the number of times the file has been opened. If the number is less than 1 then it will ask for the new password.
This bit works fine, I just have the problem that when running the following code, "None" is printed. I understand the whole function return bit but the code I'm using isn't in a function so I'm not sure why it is happening. Would really appreciate help in fixing this!
fo = open("openNo.txt", "r")
openNo = fo.read()
if int(openNo)<1:
pw = input(print("Please enter a password: ")) #creating a new password
pwCheck = pw
else:
pwCheck = input(print("Please enter your password: ")) #using an existing password
fo.close()
if pwCheck == "password":
print("Welcome!")
else:
print("access denied")
You are doing that, in fact: you are passing the result of print to input. There's no need to do that.
pw = input("Please enter a password: ")
print("Please enter a password: ") returns none so you are seeing none when you run the code

fault in readline() or condition

I am getting a problem in my code. I created a program which creates an account, saves username and password in a .txt file. Then asks for login and it checks whether the username and password is corrent or not. But everytime the else condition is executing. And i am getting output "You don' have any account". Please help. Thanks in advance.
# MyProgram: Account Verification
print "\ncreate account:\n"
f = open("data.txt",'w+')
def create():
user_name = raw_input("Enter username >> ")
password = raw_input("Enter password >> ")
confirm = raw_input("Enter password to confirm >> ")
if password == confirm:
f.write(user_name+"\n"+password)
f.close()
print "Account created"
else:
print "\nPassword not matched\n\n Enter details again:\n"
create()
create()
new = open("data.txt")
un = new.readline()
pw = new.readline()
new.close()
def login():
print "\nLogin:\n"
name = raw_input("Enter username >> ")
if name == un:
pas = raw_input("Enter password >> ")
if pas == pw:
print "Welcome!"
else:
print "Wrong password"
login()
else:
print "You don't have any account"
login()
readline includes the newline character at the end of the line, so you're probably comparing e.g. "hunter2\n" to "hunter2". Try stripping the whitespace off first.
un = new.readline().strip()
pw = new.readline().strip()
Alternatively, it may be preferable to store/retrieve your usernames and passwords in some way other than writing strings to and reading strings from a plain text file. For very lightweight applications, simple serialization like the pickle or json libraries might suffice; but anything really serious would benefit from a proper database. With any of these, you probably won't need to worry about the behavior of readline() at all.

Categories