Repeating until done - python

So Ive got this code and I want to make it repeat itself until the user makes his username not start with a symbol or number.
name=name.capitalize()
print(name)
surname= input("surname")
surname=surname.capitalize()
print(surname)
password= input("password")
username= input("username")
first_char = username[0]
if first_char.isalpha():
print('done')
else: print('username must start with a letter')

I haven't tested this code, but it seems like all you need is a simple while loop like so:
surname = input("surname")
while not surname[0].isalpha():
print("surname must start with a letter")
surname = input("surname")

If you are using python 3.8, you can use the := operator for a nice way to write this:
while not (username := input("username: "))[0].isalpha():
print('username must start with a letter')
# do stuff
Otherwise your choices are going to be:
(a) Repeat a line of code
username = input("username: ")
while not username[0].isalpha():
print('username must start with a letter')
username = input("username: ")
# do stuff
or (b) Use an infinite look with a break:
while True:
username = input("username: ")
if username[0].isalpha():
break
print('username must start with a letter')
# do stuff

You are close:
name = input("Name:").capitalize()
print(name)
surname = input("Surname:").capitalize()
password = input("Password:")
username = input("Username:")
while not username[0].isalpha():
print('Done')
Alternative:
name, surname, password, username = input("Name:").capitalize(), input('Surname:').capitalize(), input('Password'), input('Username')
while not username[0].isalpha():
print('Username must start with a letter')
print('Done')

Related

Brand new to coding in python and coding in general

I am tinkering with some code online and stumbled upon this one :
import os
import time
#Must Access this to continue.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()
I am trying to make it so after the username and password has been implemented, that this sequence happens next:
def mainname():
while True:
Firstname = input("Enter First Name:")
Lastname = input("Enter Last Name:")
if Firstname == 'Cher, Madonna':
time.sleep(2)
print("May I have your autograph, please?")
else:
print("that's a nice name")
mainname()
But what happens is, after I put in the username and password it then loops back to inputting the username and password. How do I make it so after the username and password has been implemented, then it goes to the first name and last name sequence? Thank you very much for the help
The code that checks the password is in a while True: loop, so it will keep looping and asking for the password regardless.
You want to break out of the loop on success, so add a break after you successfully log in.
Right after you have confirmed that the password is correct just add break. This will end the while loop as the correct username and password is entered.

creating a login system with python

so i am new to python and trying to create a simple login system which registers users and login but i am having trouble in password and username validation following is the code (note that i have divided my code in different modules because i am thinking of implementing it in future:
register module
import re
def register():
with open('username.txt', mode='a')as user_file:
username = input('Enter Username : ')
user_file.write(f"{username}\n")
with open('password.txt', mode='a')as pass_file:
password = input('Enter Password: ')
pattern= re.compile(r'[a-zA-Z0-9##!$%^&*]{8,}')
if password==pattern.fullmatch(password):
pass_file.write(f'{password}\n')
else:
print("your password should be atleast 8 characters long!")
login module
def login() :
l_user = input('Username: ')
l_pass = input('Password: ')
with open('username.txt', mode='r')as user_file:
for users in user_file:
validate_u = user_file.readlines()
with open('password.txt', mode='r')as pass_file:
for passwords in pass_file:
validate_p = pass_file.readlines()
if l_user==validate_u and l_pass==validate_p:
print('hello')
else:
print('login failed')
finally main module
import Enigma_Register
import Enigma_login
print('1-Login\n2-Register')
choice = int(input("enter choice: "))
if choice == 1:
Enigma_login.login()
elif choice == 2:
Enigma_Register.register()
Enigma_login.login()
else:
print('Invalid Choice!')
For your login function, replace the last four lines with:
if l_user+"\n" in validate_u: #ReadLines() adds newlines
user_num = validate_u.index(l_user+"\n")
if l_pass+"\n" == validate_p[user_num]:
print("Password correct!")
else:
print("Password incorrect!")
else:
print("Cannot find your username!")
also, the for users in user_file and for passwords in pass_file are unnecessary: just put the readlines() method on its own, without a loop.
Additionally, replace the if password==pattern.fullmatch with if pattern.match(password).
I'd also suggest moving the file writes until after you've validated the password, otherwise "ghost usernames" with no passwords could appear, easily causing problems; or you could replace all of the code in your register() function after password = input("Enter password: ") with
pattern = re.compile( [YOUR REGEX HERE] )
while not pattern.match(password):
print("Your password is invalid.")
pass_file.write(f'{password}\n')
user_file.write(f'{username}\n')

Python get password and validate while loop

So i'm trying to ask for an input and then validate if the password is correct.
It will check if the input is blank, incorrect or correct. However, after the first initial blank input, if I enter a blank again the program breaks. How do I make it keep looping and validating correctly
def getUserName():
userName = ["Chan"]
userNameInput = [""]
userNameInput[0] = input("Username: ")
while userNameInput != userName:
if userNameInput[0] == "":
print("Username can not be blank. Please try again.")
userNameInput = input("Username: ")
elif userNameInput[0] == userName[0]:
print("Username is correct. Input password.")
else:
print("Username is not correct. Please try again.")
userNameInput = input("Username: ")
Why do you need lists to store the username and username input instead of just typical strings?
The reason the code fails with a string index out of range is that you set the userNameInput variable to a string instead of settings its first element to the string.
However, it would be preferable to just use strings instead of lists in the first place.
def getUserName():
userName = "Chan"
userNameInput = input("Username: ")
while userNameInput != userName:
if len(userNameInput) == 0:
print("Username can not be blank. Please try again.")
userNameInput = input("Username: ")
elif userNameInput == userName:
print("Username is correct. Input password.")
else:
print("Username is not correct. Please try again.")
userNameInput = input("Username: ")
Here is a solution using strings instead of lists that solves your issue.
Repetition in programming is a bad practice. So in my solution, I have eliminated all repetition parts from your code and
def getUserName():
userName = "Chan"
while True:
userNameInput = input('Username: ')
if not userNameInput:
print("Username can not be blank. Please try again.")
elif userNameInput != userName:
print("Username is not correct. Please try again.")
else:
print("Username is correct")
break;
Output:
C:\***\****>py getUserName.py
Username: sad
Username is not correct. Please try again.
Username:
Username can not be blank. Please try again.
Username: Chan
Username is correct
The problem is that you are comparing the array index 0 however on the second time you set userNameInput it is being set to a string and not an array.
The fix would look something like this:
def getUserName():
userName = ["Chan"]
userNameInput = [""]
userNameInput[0] = input("Username: ")
while userNameInput != userName:
if userNameInput[0] == "":
print("Username can not be blank. Please try again.")
userNameInput[0] = input("Username: ")
elif userNameInput[0] == userName[0]:
print("Username is correct. Input password.")
else:
print("Username is not correct. Please try again.")
userNameInput[0] = input("Username: ")

How do i fix this program so it makes the input work if the password is in the dictionary and key value pair

userlist = {"MMonroe": "SomeLikeItHot1962",
"NMandela": "Justice_27years",
"ALincoln": "Number_16"}
username = input("What is you username? (FLastname)")
if username in userlist:
passw = input("What is your password? :")
if passw in username:
passwnew = input("Enter password again:")
else:
newac = input("password is invalid, try again or would you like to create a new account(y/n)?")
if input == "y":
username = input("What is you username? (FLastname)")
passw = input("What is your password? :")
passwnew = input("Enter password again:")
else:
print("Try again later or create new account")
if passw != passwnew:
print("The password is invalid, try again")
else:
print("Welcome to the website")
Seems like you meant to check if the password for that user was incorrect. Don't use in for that
if passw != userlist[username]
Also, if input == "y" will never be true unless you overwrite the input() function with a string variable

My python login program won't compare separate lines in a text file to the persons inputs

I want my login program to take a username and password input from the user, and then check it to see if it is the same to the usernames and passwords as in the files. However, the code isn't working and I think I'm missing something:
def login():
with open("username.txt","r") as username:
usrn_read = username.read()
username.close()
with open("password.txt","r") as password:
passw_read = password.read()
password.close()
inp_usern = input("Username: ")
inp_passw = input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable.open("database.txt","a")
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def end():
print("Thankyou!")
def forward():
print("This would continue to quiz!")
login()
Any help would be appreciated!
Username file
bob12
alexi90
john08
UPDATE
With the code below it works, but only on the first line of the text file:
def login():
username = open("username.txt","r")
usrn_read = username.readline().replace('\n', '')
username.close()
password = open("password.txt","r")
passw_read = password.readline().replace('\n', '')
username.close()
inp_usern = input("Username: ")
inp_passw = input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable = open("database.txt","a")
variable.write("\n Login succesful for: "+inp_usern)
variable.write(" Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def forward():
print("This would continue to quiz!")
login()
And here are the files (first is username, second is password, and they are separate files):
bob12
alexi90
bob00
alexi00
Now that it can read the first line separately from the other lines of the file, how do I get it to read the other lines separately as well? Thank you!
One small observation: if you are opening your file with context manager, you dont have to worry abt closing it.Thats the beauty of it
with open("file1.txt", "r") as filename
Your actions
Get rid of those two file.close() statements
Going forward it is a good idea to dump the input files and the error messages you saw when you submit the question to SO.
Based on my investigation two things are happening:
The first more important one is the usage of input. When you use input, python actually tries to evaluate the inputted value. So you should have seen an error like this:
Username: ababababbaba
NameError: "name 'ababababbaba' is not defined"
To fix this, use raw_input instead and you should no longer have this problem. See this SO answer here for more details https://stackoverflow.com/a/4960216/4765841
The second potential problem depends on what the contents of the input file (username.txt and password.txt). If you have a new line character (\n) then when you read the line you would actually get 'myusername\n' which will not match the user's input of myusername. To fix this, you must strip the \n from the string before saving it to your usrn_read and passw_read variables.
This is what the whole thing should look like now:
def login():
with open("username.txt","r") as username:
usrn_read = username.read().strip("\n")
username.close()
with open("password.txt","r") as password:
passw_read = password.read().strip("\n")
password.close()
inp_usern = raw_input("Username: ")
inp_passw = raw_input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable.open("database.txt","a")
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def end():
print("Thankyou!")
def forward():
print("This would continue to quiz!")
login()
Addendum, this answer assumes that variable.open is valid. Otherwise I think you need to change that line to:
with open("database.txt","a") as variable:
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
i'm working on python 2.7
i used raw_input instead of input -> refer to this What's the difference between raw_input() and input() in python3.x?
also the variable "variable" needed to be assigned first
def login():
with open("username.txt","r") as username:
usrn_read = username.read()
username.close()
with open("password.txt","r") as password:
passw_read = password.read()
password.close()
inp_usern = raw_input("Username: ")
inp_passw = raw_input("Password: ")
if inp_usern==usrn_read and inp_passw==passw_read:
print("Succesful!")
variable = open("database.txt","a")
variable.write("Login succesful for: "+inp_usern)
variable.write("Password: "+inp_passw)
print("Your username and password is:")
print(inp_usern)
print(inp_passw)
forward()
else:
print("Not valid input. Please try again.")
inp_usern = []
inp_passw = []
login()
def end():
print("Thankyou!")
def forward():
print("This would continue to quiz!")
login()
Because the username/password does not equal the three lines of the file combined.
bob12
alexi90
john08
You need to split the file into separate parts: bob12, alexi90, john08, on the \n. Then, throw it away: .replace('\n', '').

Categories