Just started python and racking my brains on this but can't seem to get it right.
print('Enter correct username and password combo to continue')
count=0
password=Hytu76E
username=bank_admin
while password!='Hytu76E' and username!='bank_admin' and count<4:
username=input('Enter username: ') and password=input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
else:
print('Access denied. Try again.')
count-=1
syntax error, can't assign to operator on line 6 username=input.
Fixed the code to achieve what you are trying to do:
print('Enter correct username and password combo to continue')
count=0
while count < 3:
username = input('Enter username: ')
password = input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
break
else:
print('Access denied. Try again.')
count += 1
Changes that have been made:
Removed the definition of username and password since it is redundant and can be omitted
Changed the while statement to count 3 iterations of count
Validation of the credentials only in the if statement and not in the while
Changed the decreasing of count to increasing (from count -= to count +=)
break the loop when the right credentials are entered
here try this (I try to change your code as less as possible so that you can identify the same logic yourself)
print('Enter correct username and password combo to continue')
count = 0
# "" or '' because you are assigning a value string into it
password = ""
username = ""
# looping will continue when wrong input for three times and ask again...
while password!='Hytu76E' and username!='bank_admin' and count < 3:
# you are collecting user input from CLI separately (you can not assign and operator to such operation as per your code ;)
username = input("Enter username: ")
password = input("Enter password: ")
if password=='Hytu76E' and username=='bank_admin':
# if match, grand and break
print('Access granted')
break
else:
print('Access denied. Try again.')
count+=1 # as per gbse, in the comments, you will need the + to count up
issues in your code:
# you are assigning string value, what for? this would make the loop hit positive the first time
password=Hytu76E # string assignment error in syntax, anyway
username=bank_admin # string assignment error in syntax, anyway
# you can not assigning and operator in the input because of no if condition in this line, also you should compare the values of the input
username=input('Enter username: ') and password=input('Enter password: ')
# if code is ok, then move outside the loop in the case when the user enters the first time good answers
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
else:
print('Access denied. Try again.')
# you are decremented the counter which would never leave teh loop at 4, you should add one on each iteration so count+=1 (count = count + 1)
count-=1
I think this is what you're looking for: Accept username and password and verify it against a particular one mentioned in the code, with a max try limit of 3
print('Enter correct username and password combo to continue')
count=1
while count<4:
username=input('Enter username: ')
password=input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
count=5
else:
print('Access denied. Try again.')
count+=1
Firstly you can remove the initial definition you gave to password and username at the start as well as changing the while loop to become while count<4
So it would look like:
print('enter the correct username and password combo to continue')
count = 0
while count<4:
If we had kept it how it was previously it would be unnecessary and clutter your program more.
To fix your syntax error you need to remove the and placed inbetween username and password, so the middle will look more like this:
username = input('Enter username: ')
password = input('Enter password: ')
Then at the end you want to change count-=1 to count+=1, because if it takes one away every time it will never hit 4 and your loop will be infinite, which is not what you are trying to achieve.
Here is the entire fix:
print('Enter correct username and password combo to continue')
count=0
while count<4:
username=input('Enter username: ')
password=input('Enter password: ')
if password=='Hytu76E' and username=='bank_admin':
print('Access granted')
count=5
else:
print('Access denied. Try again.')
count+=1
Here is a list of changes I have made:
Removed the password and username definition in lines 3 and 4
Changed your while loop to become while<4
Removed the and inbetween username=input and password=input
Added count=5 after if statement so that the loop ends
You can use for loop:
#!/usr/bin/python3
for _ in range(3):
usr = input("Enter username: ")
psw = input("Enter password: ")
if usr == "bank_admin" and psw == "Hytu76E":
print("Access Granted!")
break
else:
print("Access Denied!")
print("Try Again!")
else:
print("No more attemps!")
I mean the idea behind this:
password=Hytu76E
username=bank_admin
while password!='Hytu76E' and username!='bank_admin' and count<4:
seems to be that you get into the loop. But why so complicated? You could also just start a loop that runs 3 times:
for i in range(3):
[do something]
And in terms of what the [do something] could be. Well first of all you need to check the user input:
username=input('Enter username: ') and password=input('Enter password: ')
So the idea is good but what you do is you request 2 inputs in the same statement and then COMPARE them with an AND statement. So no wonder the interpreter gets confused here. What you probably wanted to do instead is just write them on two separate lines:
username=input('Enter username: ')
password=input('Enter password: ')
if you really want to/need to do it on one line you could use:
username, password = input(), input()
Then you'd need to insert "[Your Name][ENTER]" "[Your Password][ENTER]", but although it would work I'd not recommend it as it's probably nothing but confusing to both you and the potential user.
Next up you'd need your condition as it's no longer part of the loop:
if username == [username] and password == [password]:
print('Access granted')
break
else:
print('Access denied. Try again.')
Here break skips the rest of the loop once the condition is met. If you want to be fancy you can also add a condition to check whether it's the last try:
else:
if i < 2:
print('Access denied. Try again.')
else:
print('Access denied. IP was added to the log')
Not sure you want this, but you can split the inputs of Username and Password:
count = 1
while count < 4:
username = input('Enter username: ')
if username == 'Sdfh123':
print('OK! Enter your Password:')
count = 5
else:
print('Access DENIED. Try Again:')
count+=1
count = 1
while count < 4:
password = input('Enter Password: ')
if password == 'swordfish':
print('ACCESS GRANTED!')
count = 5
else:
print('Access DENIED. Try Again:')
count+=1
user = 'Mike'
pw = '1234'
print('Please enter your username and password: ')
username = ""
password = ""
count = 0
while username != user and password != pw and count < 3:
username = input('Username: ')
password = input('password: ')
if username == user and password == pw:
print('Welcome',username)
else:
print('Denied, Please try again') count = count + 1
Related
while True:
print('enter username: ')
username = input()
if username.lower() != 'joe':
print("imposter!")
continue
print(f'Hello {username.capitalize()}')
print('enter password: ')
password = input()
tries = 0
if password != 'Water':
tries += 1
continue
if tries == 3:
print("3 strikes, you're out")
quit()
else:
break
print("access granted")
Trying to make a username and password prompt. I am trying to give infinite tries to username entries, and only 3 chances for a correct password. When you type in the correct user name and password everything works fine. BUT when typing in the incorrect password, it loops back up to enter username, and the 'tries' counter does not work. python noob trying to learn using Automate The Boring Things in Python
You could try restructuring your code like the below:
import sys
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
else:
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
sys.exit()
print("Access granted")
You reset tries = 0 within the loop.
I am writing a login function where the user enters their username and if it's wrong it loops back and asks them to enter it again. Same thing for their password.
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print ('wrong username, please key in your username again')
continue
else:
print('key in your password')
password = input()
if password != '1234':
print('wrong password, key again')
else:
print('access granted')
How can I ask the user to re-enter their password if they type it wrong their first try? Right now this code loops all the way back to asking the user to enter their username if they enter the wrong password.
You'll just need either an inner while loop, or write a helper function to get user input:
def user_input(prompt, target_response):
while True:
user_response = input(prompt + "\n > ")
if user_response != target_response:
print("Incorrect input! Please try again!")
continue
return user_response
Then you can reuse this function to get the username:
username = user_input("Kindly key in your username", "tom")
password = user_input("Please enter your password", "1234")
Just write two separate while loops and break out of each when you get the desired result:
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print('wrong username, please key in your username again')
else:
break
print('key in your password')
while True:
password = input()
if password != '1234':
print('wrong password, key again')
else:
break
print('access granted')
I don't think we can jump to arbitary positions inside a loop in Python. We could do that in older languages like C and C++ using goto, but this practice is generally frowned upon as it makes the code harder to read and understand. For this reason most of the newer languages don't provide goto.
Your code has another logical error as well. You are not breaking out of the loop even if you input the correct credentials and it will run infinitely, asking you for the credentials again and again.
One thing that you could do is to break up your code into 2 parts, like this:
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print ('wrong username, please key in your username again')
else:
break
while True:
print('key in your password')
password = input()
if password != '1234':
print('wrong password, key again')
else:
print('access granted')
break
Also as #blorgon pointed out, since you are repeating the same kind of action twice, i.e taking input and checking whether it is correct, you could turn that into a function to keep your code DRY.
Just like you used a while for the whole situation, you can put in a while loop just for the password part,
print('kindly key in your username')
while True:
username = input()
if username != 'tom':
print ('wrong username, please key in your username again')
continue
else:
print('key in your password')
while True:
password = input()
if password != '1234':
print('wrong password, key again')
continue
else:
print('access granted')
break
Additionally, you can avoid the if conditionals by directly using the conditions in the while loop, instead of while True.
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)
I was wondering if anyone would help. I am new to python. I am trying to create a basic login script for a game, that will write a username and password to a text file. When logging in, it will read from that text file and compare the entry made by the user. The code is below:
def Register():
print("Hello! You need to register an account before you can begin")
username = input("Please enter a username: ")
password = input("Now please enter a password: ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print("You will now need to login")
Login()
def Login():
print("Please enter your details to log in")
username1 = input("Please enter your username: ")
password1 = input("Please enter your password: ")
file = open("Login.txt","r")
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
print(username,password)
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
#file.close()
user=input("Are you already a user? ")
if user == "Yes":
Login()
elif user =="No":
Register()
print("Welcome to our game")
I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry. This is the output I keep getting:
Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>>
Does anyone have an idea on how to only display the entry you have entered?
Thanks
Like Sharku said, put the print(username,password) in your if below. Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
As said by sytech, you could use the break and else clauses of the for loop:
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
break
else:
print("incorrect")
Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:
print(username,password)
If you don't want it to print all values in the file remove this line of code.
Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.
You could do something like this:
if username1 == username and password1 == password:
print("Hello",username)
break
else:
continue
This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.
However, your code doesn't take into consideration if a user doesn't exist.
import os.path
if not os.path.exists('register.txt'):
file = open('register.txt', 'w')
file.close()
def register():
username = input('Enter username: ')
if username in open('register.txt', 'r').read():
print('Username already exists')
exit()
password = input('Enter password: ')
c_password = input('Enter confirm password: ')
if password != c_password:
print('Sorry password not match')
exit()
handle = open('register.txt', 'a')
handle.write(username)
handle.write(' ')
handle.write(password)
handle.write('\n')
handle.close()
print('User was successfully registered')
exit()
def login():
username = input('Enter username: ')
password = input('Enter password: ')
get_data = open('register.txt', 'r').readlines()
users_data = []
for user in get_data:
users_data.append(user.split())
total_user = len(users_data)
increment = 0
login_success = 0
while increment < total_user:
usernames = users_data[increment][0]
passwords = users_data[increment][1]
if username == usernames and password == passwords:
login_success = 1
increment += 1
if login_success == 1:
print('Welcome ' + username)
else:
print('invalid username & password')
question = input('Do you have an account?/yes/no')
if question == 'yes':
login()
else:
register()
The premise of this code is to ask for a name, with a maximum of 3 attempts.
password = 'correct'
attempts = 3
password = input ('Guess the password: ')
while password != 'correct' and attempts >= 2:
input ('Try again: ')
attempts = attempts-1
if password == 'correct': #Where the problems begin
print ('Well done')
I can only enter the right password for the first attempt to return 'well done.' On the other two attempts, it will return as 'try again.' How can I get it to return well done, if entered on any of the attempts?
If you want to try again, then you need to capture that value.
password = input ('Try again: ')
Otherwise, the while loop never stops.
Additionally, Python has while-else, which could help you debug the issue
while password != 'correct' and attempts >= 2:
password = input ('Try again: ')
attempts = attempts-1
else:
print('while loop done')
if password == 'correct': #Where the problems begin
print ('Well done')
Or
attempts = 3
password = input('Enter pass: ')
while attempts > 0:
if password == 'correct':
break
password = input ('Try again: ')
attempts = attempts-1
if attempts > 0 and password == 'correct':
print ('Well done')
attempts = 3
while attempts > 1:
password = input("Guess password")
if password == "correct" and attempts > 2:
print("Well done")
break
else:
print("try again")
attempts = attempts - 1
This is a fun way to do it, instead of using a counter, you can create a list with three elements and the while test makes sure there are still elements left:
password,wrong,right = 'nice',['Wrong']*3,['you got it!']
while len(wrong)>0 and len(right)>0:
right.pop() if input('guess:')==password else wrong.pop()