how to make the user choose between options - python

I make password genrator using python then the teacher told to create a code that make the user choose what he want in the password
the password contains
1- lower case characters
2- upper case characters
3- numbers
4- punticuation marks
the teacher want me to make the user choose if he want punticution or not
if he dont want it have to be deleted from the password
i tried so hard but i got stuck
from msilib import change_sequence
import string
import random # I import this line to make the password unorgnaized
# this code below is all the characters we need for the password
s1 = list(string.ascii_lowercase)
s2 = list(string.ascii_uppercase)
s3 = list(string.digits)
s4 = list(string.punctuation)
# this code is for the user to put how much characters he need
characters_number = input("how many characters for the password?:")
# this while loop code is to make the user choose only 6 characters and up
while True:
try:
characters_number = int(characters_number)
if characters_number < 6 :
print("you need at least 6 characters") # if the user choose an letter or digits it will not allow him
characters_number = input("please enter the number again:")
else:
break # I break the loop here if the user write the correct data
except: #this code here if the user enter anything except numbers
print("please enter numbers only")
characters_number = input("how many characters for the password?:")
# the random and shuffle is to make the password unorgnized
random.shuffle(s1)
random.shuffle(s2)
random.shuffle(s3)
random.shuffle(s4)
# the password that will appear to the user it contains upper and lower letters, numbers and digit
# part1 here is for the letters I allocated 30% of the password for letters
# part2 here is for the digits and numbers I allocated 20% of the password for letters
part1 = round(characters_number * (30/100))
part2 = round(characters_number * (20/100))
password = []
for x in range(part1):
password.append(s1[x])
password.append(s2[x])
#the for loops here here is to create the password
for x in range(part2):
password.append(s3[x])
password.append(s4[x])
#this code here is to transform the password for list method to a string
password = "".join(password[0:])
print(password)

You can write a function like this:
def isUserNeedPunctuationMarks():
result = None
while True:
inp = input("Do you need punctuation marks in your password? (y/n)")
inp = inp.lower()
if inp == "y":
result = True
break
elif inp == "n":
result == False
break
else:
print("You must enter y or n")
return result
The above function will return True if the user needs punctuation marks, and False otherwise. User has to type y (for yes) or n(for no).
You can call isUserNeedPunctuationMarks() in the right place in your code. For example, removing punctuation marks from password string, you have to write a condition like this:
import re
if not isUserNeedPunctuationMarks():
password = re.sub(r'[^\w\s]', '', password) # This removes punctuation marks from a string using regex
Hope this helps :)

Related

Can I/How to jump back to a specific line of code using while & if-else together?

I've written my code to work fine, but if the user chooses to try a different output, I'd like to skip the introductory message. For example, if the user chooses to generate a different password, I'd prefer to return to line 11 (the request to enter a length requirement) rather than line 8. (which welcomes the user to the program).
import random
import string
import sys
another = True
while another:
8 print("Welcome to the Password Generator!")
# ask user for password length requirement
11 length = int(input("How many characters does your password require?: "))
# initialize character types
lower = string.ascii_lowercase
capitalize = string.ascii_uppercase
nums = string.digits
symbols = string.punctuation
# combine all char types
combine = lower + capitalize + nums + symbols
# randomize character types and add length requirement
randomization = random.sample(combine, length)
# construct the secure password
secure_pw = "".join(randomization)
# display password
print(secure_pw)
another = input("Would you like to generate a different secure password?: ")
while True:
if another == 'yes':
generate = True
break
elif another == 'no':
generate = False
sys.exit()
else:
another = input('Invalid response! Enter "yes" to continue or "no" to exit: ')

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'.

str.isdigit() doesn't seem to be working in python

I'm working on a password checker that checks if the string is a valid password. I have to check if there is at least eight characters, must consist of only letters and digits and the last two characters must be digits.
It all seems to work so far other than the password.isdigit(). sometimes the password comes out valid and sometimes it doesn't. Any suggestions?
# Gets the users password
password = input('Enter a string for password: ')
# Splices the last two characters of the password
lastTwo = password[-2:]
# Checks the password if it is less than 8 characters
while len(password) < 8:
print('The password you entered is too short.')
print()
password = input('Enter a string for password: ')
# Checks the password if it is composed of letters and numbers
while password.isalnum() == False:
print('Your password has special characters not allowed.')
print()
password = input('Enter a string for password: ')
# Checks the spice to verify they are digits
while lastTwo.isdigit() == False:
print('Your last two characters of your password must be digits.')
print()
password = input('Enter a string for password: ')
print('Your password is valid.')
There are a handful of issues with your provided code. Particularly, you only check the subsequent rules while len(password) < 8. If you give it a password of length 10, the rules are never checked. Additionally, you don't update the lastTwo with each new password attempted
One way to fix this would be to replace your several while statements with if...elif..elif...else... wrapped in an overall while statement, as follows:
# Gets the users password
password = input('Enter a string for password: ')
while True:
# Checks the password if it is less than 8 characters
if len(password) < 8:
print('The password you entered is too short.')
# Checks the password if it is composed of letters and numbers
elif not password.isalnum():
print('Your password has special characters not allowed.')
# Checks the spice to verify they are digits
elif not password[:-2].isdigit():
print('Your last two characters of your password must be digits.')
else:
# we only get here when all rules are True
break
print()
password = input('Enter a string for password: ')
print('Your password is valid.')
This should work as you intended it. But while we're at it, why not tell the user every rule their password has broken? From a UI point of view, it helps to keep the user informed.
If we store an information message alongside whether the relevant rule has been met, we can quickly work out all of the rules that have been broken, like so:
valid_password = False
while not valid_password:
# Get a password
password = input('\nEnter a string for password: ')
# applies all checks
checks = {
'- end in two digits': password[-2].isdigit(),
'- not contain any special characters': password.isalnum(),
'- be over 8 characters long': len(password) > 8
}
# if all values in the dictionary are true, the password is valid.
if all(checks.values()):
valid_password = True
# otherwise, return the rules violated
else:
print('This password is not valid. Passwords must:\n{}'.format(
'\n'.join([k for k, v in checks.items() if not v])))
print('Your password is valid.')
You never update your value of lastTwo inside your while loop. Thus imagine if a user first entered a password abc123. Then lastTwo would be calculated as 23.
Now your code would find that the password is too short and prompt the user for a new password. Suppose he enters abcdefgh. This now passes your first and second checks. Notice however that lastTwo is still 23, and thus your third check will incorrectly pass.
You should thus recalculate the value of lastTwo whenever you accept a new password or directly check like this:
while (password[-2:]).isdigit() == False:

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.

Regex password program

I'm working on an exercise problem from the regex chapter in 'Automate the boring stuff with Python' the question and my code is below. I got the regex working in the Python shell and I think its correct but I just can't get it to work within my function so that it returns the correct answer.
Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.
import re
def pwRegex():
print "Please enter a password"
user_pw = raw_input("> ")
#your_pw = str(user_pw)
passGex = re.compile(r'^(?=.*\d)(?=.*[A-Z])\w{8,15}$')
pass_w = passGex.search(user_pw)
if pass_w != '':
print "Well done"
else:
print "Try again"
pwRegex()
the output I get is "Try again" every time even when I'm entering a password that should pass the regex. I tried making the if statement pass_w == True: but then everything that I entered seemed to pass the regex even if incorrect.
Regex searching in python gives back a MatchObject, not a string. If it does not find the required pattern, it will return None. You should check for None, or, more pythonically, check for truthiness
# if pass_w != None: # => less pythonic
if pass_w:
print 'Well done'
else:
print 'Try again'
import re
print('Please set a new password: ')
def strongpassword():
while True:
password = input()
if lowcase.search(password) == None:
print('The entered password doesn\'t have a lower case character')
continue
if upcase.search(password) == None:
print('The entered password doesn\'t have an upper case character')
continue
if digit.search(password) == None:
print('The entered password doesn\'t have a digit')
continue
if space_8.search(password) == None:
print('The entered password should have atleast 8 characters and no space in between')
continue
else:
print('New Password is Valid and Saved')
break
lowcase = re.compile(r'[a-z]') # this regex searches for atleast one lower case alphabet
upcase = re.compile(r'[A-Z]') # this regex searches for atleast one upper case alphabet
digit = re.compile(r'(\d)') # this regex searches for atleast one digit
space_8 = re.compile(r'^[a-zA-Z0-9]{8,}$') # this regex searches for expressions without any space and atleast 8 characters
strongpassword()
I guess, it is not relevant anymore. However, I would like to suggest this:
import re
pasword = re.compile(r'''(
\d+ #have at lest one digit
.* # anything
[A-Z]+ # at least 1 capital
.*
[a-z]+ # at least one lower
.*
)''', re.VERBOSE)
# test
pasword.search('1##A!a').group()
def is_strong_password():
pas = input('Enter a password:')
if len(pas) < 8:
return False
else:
check = pasword.search(''.join(sorted(pas))).group() #sorted is important to be sure that user can write symbols in any order he/she wants
if (not check):
print('Not strong pasword')
return False
else:
print('Strong password')
return True
I was also working on the same exercise, I'm learning python as well. You can search() instead of findall(). i just used it just to test it out.
import re
print('Enter new password')
def strongPW():
while True:
pw = input()
lowercase = [] # lowercase
uppercase = [] # uppercase
digit = [] # number
if len(pw) < 8:
print('your password must have 8 characters or more')
break
# lowercase verification
pwRegex = re.compile(r'[a-z]')
lowercase = pwRegex.search(pw)
if lowercase == []:
print('Your password must have at least one lowercase')
break
# uppercase verification
uppercaseRegex = re.compile(r'[A-Z]')
uppercase = uppercaseRegex.findall(pw)
if uppercase == []:
print('Your password must have at least one uppercase')
break
# digit verification
DigitRegex = re.compile(r'[0-9]')
digit = DigitRegex.findall(pw)
if digit == []:
print('Your password must have at least one digit')
break
else:
print('Your password meets all requirements ')
break
strongPW()

Categories

Resources