calling functions for a password checker - python

this is my password checker code (whether it is valid or not)
I need to run the password checker for 5 times, until it's valid.
If it's valid, I have to break out of the loop.
The password should be more than 7 characters.
The password needs to include both numbers (at least two) and characters.
(If not, return False)
There should be no space.
If there is anything else than numbers and characters, I need to return False
I need to run my password_checker function in the for loop,
but I'm not so sure what to say after 'if'.
I have tried -
if a=False:
print(password_checker(i))
print(Invalid password)
but it didn't work.
Also, I don't understand how should I call my password_checker() in the for loop.
Finally, I need to put a break in my for loop
if the password in the input is valid.
But I'm not sure where is the appropriate part to place it
def password_checker(password):
a=True
num_Count = 0
if password.isalpha() == True:
print ("error! needs numbers")
a = False
if password.isnum() == True:
print ("error! needs characters")
a = False
if password.isspace() == True:
print ("error! no space allowed")
a = False
if len(password)<=8:
print ("error! needs more than 8 characters")
a = False
for i in range(0, 10):
num_Count += password.count(i)
if num_Count(password.count()) < 2:
print("error! needs at least 2 numbers")
a = False
password = str(input("Enter password: "))
for i in range(0,5):
if ____________________:
print(password_checker(i))
print("Invalid password")
else:
print(password_checker(i))
print("Valid password")
break
How should I correct my code in order to make my function work?

for i in range(0,5):
password = str(input("Enter password: "))
password_checker_result = password_checker(password)
if not password_checker_result:
print("Invalid password")
else:
print("Valid password")
break
This code will work for you, now let me explain:
The flow is as following:
This is done 5 times (is inside the for loop):
1) Request password from user.
2) Check if password is valid.
3) Print according to valid/not valid result.
The fact that you are using a for loop does not require you to actually use the iteration index (meaning 'i' in our case)

Related

break out of two loops without disturbing the if statements after it in python

I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')

How to single out a number and special character at the end of the password

Write a program that asks the user to enter a password (with the prompt "Password:"). It should then reward the user with "Congratulations, you're in!" if the password is between 8 and 20 characters long (inclusive), ends with a digit, and contains a period or comma. Otherwise, it should say "Wrong! This incident will be reported!"
I need to be able to have a number at the end and contain either a period or a comma. I am not sure on how to isolate these two parts of the password. What do I do to have the user asked to enter a password?
user_pass = str(input())
if (len(user_pass <= 8) and (len(user_pass >= 20)) and
print ("Congratulations, you're in!")
else:
print ('Wrong! This incident will be reported!')
Just add more conditions using and.
Python 3:
password = input("Password: ")
if (8 <= len(password) <= 20) and password[-1].isdecimal() and any(x in password for x in {'.', ','}):
print("Congratulations, you're in!")
else:
print("Wrong! This incident will be reported!")
Python 2:
password = raw_input("Password: ")
if (8 <= len(password) <= 20) and unicode(password[-1]).isdecimal() and any(x in password for x in {'.', ','}):
print("Congratulations, you're in!")
else:
print("Wrong! This incident will be reported!")
A hint:
def password_is_good(password):
return (
password_length_is_correct(password) and
password_ends_with_digit(password) and
password_contains_punctuation(password)
)
def password_length_is_correct(password):
# implement this, and the rest.
password = str(input())
if password_is_good(password):
# do something.
else:
# do something else.
You can access string elements by index, with negative indexes counting from the end; e.g. password[-1] would access the last character.
You can use the in operator to check for a character to be present in a string, like if 'c' in 'abcdef'.

Login system on Python

This is a really newbie question.
So, I am trying to code a login system in Python, where it asks for an username (only 1 username available), if the username typed in is incorrect, it says the username is invalid, if it is correct, it asks for a password, if the password is incorrect, it says incorrect password and proceeds to ask for the password once again, and if the password typed in is correct, it just says logged in.
What I've been able to do so far is:
a = 0
while a < 1:
print ('Username:')
name = input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
a = a + 1
password = input()
b = 0
while b < 1:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
b = b + 1
continue
else:
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
break
This works, although it does something I don't want if the user types in the incorrect password. If the user types in the incorrect password, I wanted the program to tell the user 'Incorrect password' and proceed to ask for it once again, but it doesn't do that, it just prints 'Incorrect password', and then it terminates. It works 100% on the part where it asks for the username, though.
It's a little thing I am missing. How can I fix this?
Thanks a lot!
The statement b = b + 1 is terminating your while loop every time the user enters an incorrect password. There is really no need for it.
You can alternatively just wrap your password prompt in a while loop:
while input("Enter password") != "1234":
print("Password incorrect")
There is no need for the + 1 when checking for the password. That just breaks you out of the loop.
Instead, try:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
continue
A much better solution, instead of using +1 and <1 to break out of loops is to use booleans.
Sample:
userCorrect = False
while not userCorrect:
print ('Username:')
name = raw_input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
userCorrect = True
password = raw_input()
passCorrect = False
while not passCorrect:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
print ('Password:')
password = raw_input()
else:
passCorrect = True
# Since password is correct, continue.
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
This loop (while b < 1:) terminates the moment an invalid password is entered.
Look at
> if password != '1234': #checks the password typed in
> print ('Password incorrect.')
> b = b + 1
> continue
The line of code b = b + 1 makes it such that while b < 1: becomes false, thus ending the loop and terminating your program.
As others have already pointed out, the problem lies is b = b + 1 breaking the condition while b < 1:, causing it not to ask for another password. Simple delete the line b = b + 1
Want to make it better?
Avoid the 'over-the-shoulder' attack with getpass() instead of input(). Your password input is masked as ****
ex.
from getpass import getpass
password = getpass()
Cryptify
Well, apart from sounding cool, this doesn't really stop somebody from modifying the code to skip past the password phase -but it can stop them from seeing the raw password in the code.
this post has a good example using passlib
This helps protect non-unique/sensitive passwords (like the password you use for 5x other things, or your mother's maiden name... lets not drag her into this)

Python GCSE homework help - password

For my homework I need to make a user registration system in python. I need to make a password section.
What I am meant to do?.
Here is my code, I can't work out whats wrong:
password = input("Please enter your password: ")
passwordl = len(password)
while passwordl <= 8:
print("password must be more than 8 characters - please try agian")
password = input("Please enter your password: ")
passworda = password.isalpha()
passwordi = password.isdigit()
while passworda != True or passwordi != True:
print("password needs to contain digits and characters - please re-enter")
password = input("Please enter your password: ")
The code is in a function btw.
Thanks
The functions isalpha() and isdigit() return true if all the members in the string are alphanumeric and digits, respectively.
What you need to do instead is to check if any characters in the string have the right properties, for example like this:
passworda = any([x.isalpha() for x in password])
passwordi = any([x.isdigit() for x in password])
Additionally, you need to redo all the checks (both length and character set checks) each time when the password is entered anew.
Instead of following
Password = input("Please enter your password")
In the last while loop with the checks over again you would be better just calling the password function as it's more efficient.

Python 3.x input variable

I want to get user input of a code that has to be 11 numbers long and must not contain any characters. Otherwise the question to enter will be repeated.
code=input("Please enter your code ")
while len((code)) !=11: #here should be something to nullify strings inout :)
code = input("Please enter your code and in numbers only ")
There is definitely a better solution for this, just can't think of any.
This might be what you're after
def validate(s):
for char in s: #iterate through string
if not char.isdigit(): # checks if character is not a number
return False # if it's not a number then return False
return True # if the string passes with no issues return True
def enter_code():
while True: #Will keep running until break is reached
code = input("Please enter your code: ") #get user input
# if the length of input and it passes the validate then print 'Your code is valid'
if len(code) == 11 and validate(code):
print('Your code is valid')
break #break out of loop if valid
# if code fails test then print 'Your code is invalid' and return to start of while loop
print('Your code is invalid')
if __name__ == '__main__':
enter_code()

Categories

Resources