Why is my password programme code not working? - python

The code will only let me guess once . Can someone please tell me what is wrong with my code?
Challenge:
Write a program that sets a password as ‘Gain Access ’ and asks the
user to enter the password and keeps asking until the correct password
is entered and then says ‘Accepted’. The program should count how many
attempts the user has taken and tell them after they have been
accepted.
enter code here
password = 'Gain access'
count = 0
input = input("Enter the password: \n")
while input != password:
print("Incorrect password! Please try again: \n")
count = count + 1
print("You have now got your password wrong " + str(count) + " times. \n")
if(count < 5):
print("Access denied, please contact security to reset your password.")
break
else:
print("Accepted, welcome back.")
print("You had " + str(count) + " attempts until you got your password right.")

You should always include the language you're programming in like simonwo mentioned already.
Looks like Python to me though. I suppose this line input = input("Enter the password: \n") needs to go after while input != password:, as well. Otherwise you can only enter the password once and then it directly executes all 5 loops. But you should NOT assign input because this is the function you want to obtain the input from.
Do something like user_input = input("Enter the password: \n"). So your code should look something like this:
...
user_input = input("Enter the password: \n")
while user_input != password:
print("Incorrect password! Please try again: \n")
user_input = input("Enter the password: \n")
... Your existing code here
But note that this way the user won't get notified if they entered the correct password with their first try. You could insert a check after the first reading of the user input and if it matches the desired password print your welcome phrase.

Related

how to assign multiple string values to a variable in python

I am new to python, just start learning :P
I am trying to create a password protected program, but I am stuck in assigning multiple string values to single variable.
can anyone help me solving this problem,
If you guys have better idea for this "login type" program please guide me !
I want to assign all different possible synonyms assign to one variable so it become easy for user to enter!!!
(my English :P)
#Code 1
User_Name = "Allex_Benzz", "allex benzz", "allex_benzz", "Allex Benzz"
User_Input = input("Please Input Your User Name...!\n")
if User_Input == User_Name:
User_Password = "0011"
User_Input_Password = input("Please Enter Your Password...!\n")
if User_Input_Password == User_Password:
print("Welcome Allex Benzz")
else:
print("Your Password Is Incorrect..!")
else:
print("No Users Found")
Result Code 1
Please Input Your User Name...!
allex benzz #(User Input)
No Users Found
#Python login
#Code 2
User_Name = "Allex_Benzz"
User_Name = "allex benzz"
User_Name = "allex_benzz"
User_Name = "Allex Benzz"
User_Input = input("Please Input Your User Name...!\n")
if User_Input == User_Name:
User_Password = "0011"
User_Input_Password = input("Please Enter Your Password...!\n")
if User_Input_Password == User_Password:
print("Welcome Allex Benzz")
else:
print("Your Password Is Incorrect..!")
else:
print("No Users Found")
#Result Code 2
#In this case its is only working if I use Allex Benzz because User_Name is setted to Allex Benzz
Please Input Your User Name...!
allex benzz #User_Input
No Users Found
#working Result for Code 2
Please Input Your User Name...!
Allex Benzz #User_Input
Please Enter Your Password...!
0011 #User_Password
Welcome Allex Benzz
In this code:
User_Name = "Allex_Benzz", "allex benzz", "allex_benzz", "Allex Benzz"
User_Input = input("Please Input Your User Name...!\n")
if User_Input == User_Name:
# ...
User_Name is a tuple of multiple strings, and User_Input is a single string. A single string will never be equal to (==) a tuple, but it can be in a tuple. Change the if check to:
if User_Input in User_Name:
and it should work the way you intend.

Ending the program without the rest - need support

I have wrote this simple login and registartion program:
import os
from os import path
def start():
startup = input ('are you an existing user? y/n : ')
if startup == "y":
print ("Lets login then")
login()
if startup == "n":
print ("Lets make you an account")
new_account()
else:
print ("That is an invalid input, please try again")
start()
def new_account():
new_username = input ('what do you want your username to be? ')
print ('okay...')
new_pass = input ('your new password... ')
checker_pass = input ('retype it... ')
if new_pass == checker_pass:
print ('you have entered correct passwords')
print ('Now please login ')
print (' ')
print ('..................................')
print (' ')
saveFile = open( new_username + '.txt','w')
saveFile.write(new_pass)
saveFile.close()
login()
else:
print ('you have done something wrong. Please start again')
new_account()
def login():
print (' ')
print ('..................................')
print ("")
user_name = input ('enter username: ')
file_check = path.exists(user_name + '.txt')
if file_check == False:
print ("That username dosent exist, please start again")
start()
if file_check == True:
Pass_check = open(user_name + '.txt' , 'r').read()
password = input ('enter your password: ')
if Pass_check != password:
print('That didnt quite match. Please start again')
start()
elif Pass_check == password:
print ('Welcome to your account.')
start()
once i have entered a valid username or password it then says:
That is an invalid input, please try again
are you an existing user? y/n :
this is part of the program but isnt supposed to occur once you have been welcomed to your account.
has anyone got a soulution so that once you recieve "welcome to your account" nothing else happens.
i would like it done so that the program dosent fully stop as im looking to put this code into another program.
thanks fin.
THE OUTPUT:
are you an existing user? y/n : y
Lets login then
..................................
enter username: finndude
enter your password: test
Welcome to your account.
That is an invalid input, please try again
are you an existing user? y/n :
i dont want the last two lines to appear
Add a boolean flag value to the start() function that says whether to display the line or not. When calling from login() pass True, when calling recursively from start() then pass False.

User input validation will not stick

I first want to thank anyone and everyone in advance for taking the time to help a scrub like me and appreciate your time in giving me a helping hand. So I am attempting to make a simple user creation script. Asking the user for their first and last name, concatenated the user's first letter of their first name with their last and concatenating it with a random number to create their user name. I then will prompt the user to create a password and have the password be a minimum of 6 characters long. After that, I ask the user to verify their password. I've been going crazy because when the program reaches the password verification step, it doesn't check for the 6 characters or verify that the passwords are the same and continues to the rest of the program.
This is a snippet of the password part:
# Ask the user for a password that's at least 6 characters long
while True:
password = input("Enter a password for this account: ")
# Verify that the user's input is 6 characters long
if len(password) < 6:
print("Your password must be at least 6 characters long! ")
# Has the user verify the password
password = input("Please verify your password by typing it in again: ")
if password == password:
print("Thank you for confirming your password")
else:
print("Nope your password did not match")
And after all of that, I am having the "user" login with the new information that was generated. Using the username generated in the first part and using the password they input in the second and checking. The same thing, it skips the check and continues with the program. I am going insane because I've spent a couple of hours just learning some basics as I am a beginner with python.
Here is the full code:
def main():
print("You do the typin, I will take care of the rest!")
#User will be prompted to input their first and last name
firstname = input("Please give me your first name. ")
lastname = input("Thank you, now please give me your last name. ")
# The first and last name will be concatenated and the first letter of the
# users name will be attatched to their last name.
username = firstname[0] + lastname[:7]
# Now to generate the random number from 100-999 to attach to the new
# username
import random
from random import randint
print("Welcome", username + str(random.randint(100,999)))
import re
def sub():
# Ask the user for a password that's at least 6 charcaters long
while True:
password = input("Enter a password for this account: ")
# Verify that the users input is 6 charcters long
if len(password) < 6:
print("Your password must be at least 6 charcaters long! ")
# Has the user verify the password
password = input("Please verify your password by typing it in again: ")
if password == password:
print("Thank you for confirming your password")
else:
print("Nope your password did not match")
# Now the user must login using the generated username from above
username = input("Enter your generated username! ")
if username == username:
print("Correct!")
else:
print("I have never seen you before!")
password = input("Now enter your accounts password: ")
if password == password:
print("You are now logged in!")
else:
print("FAIL")
break
main()
sub()
So, there are many errors in your code. The first one is, there's nothing that stops the program from progressing if the password is less than 6 characters. Second, password == password will ALWAYS return true, because you're checking a var against itself. I re-wrote a bit of your code to try to help clarify your problem. I hope this helps! I also split the code into a few functions + added getpass (https://docs.python.org/3/library/getpass.html)
from getpass import getpass # You can use this module to hide the password the user inputs
from random import randint
def generate_username():
# Basic username generation, same thing you did
print("You do the typin, I will take care of the rest!")
firstname = input("Please give me your first name. ")
lastname = input("Thank you, now please give me your last name. ")
username = firstname[0] + lastname[:7] + str(randint(1, 99))
# You can't concatenate strings and ints, so I convert the number to a string first
print(f"Your username is: {username}") # f-strings (https://realpython.com/python-f-strings/)
return username
def generate_password():
while True:
password = getpass("Enter a password for this account: ")
confirm_password = getpass("Enter your password again: ") # Ask the user to enter the password a second time to confirm
if password != confirm_password: # Check if the user entered the same password
print("Passwords dont match!")
elif len(password) < 6: # Check the length
print("Your password must be at least 6 charcaters long! ")
else: # If everythings all good
print("Password is valid!")
return password # Break the loop and return password value
def login(username, password):
# Used to login a user
while True:
entered_username = input("Enter your username: ")
entered_password = getpass("Enter your password: ")
if username == entered_username and password == entered_password:
# Confirm if username and password are correct, then exit the loop (or do something else)
print("Login successful!")
break
else:
print("Login failed, please confirm your username and password")
username = generate_username()
password = generate_password()
login(username, password)

Loging and saving to csv

I'm making login/signing section for my code. I have 2 issues with it. I need help:
First question Yes or No functions well until other character entered. While loop is not accepted for some reason. How to get back to beginning until Y or N entered?
I would like to store dict with usernames and passwords as CSV file sorted in two columns not rows. How to do it.
Thanks
Here is the code....
# CREATING START DICTIONARY
users = {"guest": "guestpass", "admin": "adpass"}
status = input("\rAre you a registered user? Y / N? ").upper()
while status != "Y" and status != "N":
print ("Please enter Y or N")
# NEW USER
if status == "N":
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print("Login name already exist! Please, choose another one.\n")
else:
createPass = input("Create password: ")
retypePass = input("Retype password: ")
while True:
if createPass != retypePass:
print("\nPassword error!\n")
else:
users.update({createLogin : createPass})
print("\nNew user created! Welcome to ARR!\n")
break
import csv
writer = csv.writer(open('UsersFile.csv', 'wb'))
for key, value in users.items():
writer.writerow([createLogin, createPass])
# LOGIN EXISTING/NEW USER
elif status == "Y":
while True:
loginName = input("Enter login name: ").lower()
if loginName not in users:
print("User doesn't exist! Please enter existing name or sign-in.")
print("----------------------------------------------------------")
else:
passw = input("Enter password: ")
# LOGIN MATCHES PASSWORD
if loginName in users and passw != users.get(loginName):
print("Wrong password! Please enter username and password again!")
else:
print("Login successful!\n")
break
1) In your y/n while loop you are missing a tab to indent the print statement.
2) https://docs.python.org/2/library/csv.html
Some issues I see so far:
Indentation. print ("Please enter Y or N") should be indented relative to the while statement on the previous line.
Also, the statement if createLogin in users and the following else statement should probably be indented one more level, if they are meant to be within the if status == 'N' statement.
Import statement. Generally, things like import csv would be at the top of the file. Try moving it there and see if it helps.

Stop a while loop from running a certain amount of times

I've been searching around nearly all morning looking for a piece of code that can help me here but its hard to find one that is similar!
I have to create a bank system that asks the user to input a username and password.
If these are entered 3 times the system shuts down.
So far, i have got my program to know if the password/username is correct or not.
Now i just need to figure out how to make it run and stop after 3 incorrect attempts.
Really appreciate any help given on this one! Thanks
Code:
username = "bank_admin"
password = "Hytu76E"
usernameGuess = raw_input("Please enter your username: ")
passwordGuess = raw_input("Please enter the password: ")
while (username != usernameGuess or password != passwordGuess):
print ("Please try again.")
usernameGuess = raw_input("Please enter your username: ")
passwordGuess = raw_input("Please enter your password: ")
print ("Password accepted. Access Authorized.")
You can add a counter to see how many times they guessed the wrong password. Then use that as another condition in your while loop.
incorrectGuesses = 0
correct = False
while (not correct and incorrectGuesses < 4):
usernameGuess = raw_input("Please enter your username: ")
passwordGuess = raw_input("Please enter your password: ")
correct = ((username == usernameGuess) and (password == passwordGuess))
if not correct:
print ("Please try again.")
incorrectGuesses += 1

Categories

Resources