No i'm not cursing in the title. i need to create a password processing program that checks a input on whether it meets certain criteria one of which is that it must contain one of the characters $#!%&*_.
this is what i currently have.
def pword():
global password
global lower
global upper
global integer
password = input("Please enter your password ")
length = len(password)
lower = sum([int(c.islower()) for c in password])
upper = sum([int(c.isupper()) for c in password])
integer = sum([int(c.isdigit()) for c in password])
def length():
global password
if len(password) < 8:
print("Your password is too short, please try again")
elif len(password) > 24:
print("Your password is too long, please try again")
def strength():
global lower
global upper
global integer
if (lower) < 2:
print("Please use a mixed case password with lower case letters")
elif (upper) < 2:
print("Please use a mixed case password with UPPER case letters")
elif (integer) < 2:
print("Please try adding numbers")
else:
print("Strength Assessed - Your password is ok")
This kind of thing will work:
required='$#!%&*_'
def has_required(input):
for char in required:
if input.contains(char):
return True
return False
has_required('Foo')
must_have = '$#!%&*_'
if not any(c in must_have for c in password):
print("Please try adding %s." % must_have)
any(c in must_have for c in password) will return True if any one of the characters in password is also in must_have, in other words, it will return True is the password is good. Because want to test for bad passwords, we put not in front of it to reverse the test. Thus the print statement is executed here only for bad passwords.
You can achieve this easily with a list comprehension + the any() built-in.
has_symbol = any([symbol in password for symbol in list('$#!%&*_')])
Or a little more broken up:
required_symbols = list('$#!%&*_')
has_symbol = any([symbol in password for symbol in required_symbols])
Related
I am sure the answer is right in front of my face but I can't seem to figure out how to fix the return on my first if statement when I input the right conditions.
create_password = input("Enter password here: ")
if len(create_password) > 6 and create_password.isdigit() > 0:
print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
print("Password must include a number")
else:
print("Your password sucks")
Let's say I enter elephant100, I am trying to get the prompt to be "Your account is ready!". But to my dismay, it prints "Password must include a number" and I cannot figure out why. My other conditions match the right input but that is the only one that does not work.
.isdigit() method returns True if all the characters are digits, otherwise False. Hence it returns False in this case since your string contains letters like e, l, p etc. So the statement print("Your account is ready!") will never be executed.
Turns out I needed to use isalnum(), isnumeric(), and isalpha() to fix my problem. Thank you Muhammed Jaseem for helping me figure it out! Here is my revised code.
if create_password.isnumeric() == True:
print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
print("Your account is ready!")
else:
print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")
I have been wondering this for a longer time
If I check for user input, I know how to check for strings.
But what if I want to check if the user has entered just integers or floats. I tried it with an "if name == int or float: block but of course that didn't work. Can you help me out?
How do I check for that? Here is my code. Of course the input I always converted to a string so I don't know how to do that.
print("Enter a name: ")
while True:
name = input()
if name != "":
print("Thank you for entering a name: ")
break
else:
print("Please enter a name: ")
I also tried this:
print("Enter a name: ")
while True:
name = input()
if type(name) != int:
print("Thats not a name!")
print("Now please enter a name without numbers")
elif type(name) != float:
print("Thats also not a name!")
print("Now please enter a name without numbers")
elif type(name) != "":
print("Thank you for entering your name!")
break
else:
print("Please enter a name: ")
For int you can use the isnumeric() method
"1".isnumeric() #True
For float, you should try if casting to float is possible
def isFloat(num):
try:
float(num)
return True
except ValueError:
return False
Now use both these methods :
print("Enter a name: ")
while True:
name = input()
if name.isnumeric() or isFloat(name):
print("Thats not a name!")
print("Now please enter a name without numbers")
elif type(name) != "":
print("Thank you for entering your name!")
break
else:
print("Please enter a name: ")
Output :
Enter a name:
1
Thats not a name!
Now please enter a name without numbers
1.2
Thats not a name!
Now please enter a name without numbers
abc
Thank you for entering your name!
Edit: This might help.
def hello(userinput):
if userinput.isdigit():
print("You entered a number. That's not valid!")
else:
print("You entered a valid name.")
Old Solution
print("Enter a name: ")
while True:
name = input()
if type(name) != int:
print("Thank you for entering a name: ")
break
else:
print("Please enter a name: ")
Also I can understand why you did that.
The previous code you created meant that if the user typed the class int. This will be impossible to type a class because input() only takes a string from the user's input.
To check if a variable is of a type, simply use if type(VARIABLE) == TYPE: where "VARIABLE" is your variable and TYPE is your type (such as int, float, str, etc.).
In your code, however, you may want to use str.isnumeric() as it will return True when there are numerical values in the string. To check if ANY characters are numeric, do if all([not char.isnumeric() for char in list(STRING)]): where "STRING" is your user's input. This checks if every character in the string is not numeric and returns True when this is the case.
A password must have at least eight characters.
• A password consists of only letters and digits.
• A password must contain at least two digits
you can refer to this code as your answer :
import re
def validate():
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
validate()
if you want to generate such passwords use this code:
import string
import random
letters =string.ascii_letters
digits = string.digits
comb = letters + digits
length = random.randint(6,98)
password = random.choices(digits,k = 2)
password+= random.choices(comb, k =length)
random.shuffle(password)
password = ''.join(password)
print(password)
I assumed the max length of a password is 100. you may want to change it.
When i do this in this way
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
if x[0].islower():
print("The first password letter must be uppercase")
else:
print("Password saved")
password = x
i getting
>The password must contain at least 9 letters
>Password saved
What should I do to make the program stop on:
>The password must contain at least 9 letters
Use elif between if and else:
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
elif x[0].islower():
print("The first password letter must be uppercase")
else:
print("Password saved")
password = x
elif is executed only when if wasn't executed, and elif's condition is true. You can also chain as many elifs as you want, in which case the first elif whose condition matches is executed.
Update: Since OP said in comments that he wants all errors to be shown at once, I would use something like this:
x = "Hello"
errors = []
if len(x) <= 9:
errors.append("The password must contain at least 9 letters")
if x[0].islower():
errors.append("The first password letter must be uppercase")
if errors:
print('\n'.join(errors))
else:
print("Password saved")
password = x
The problem is that you have two if filters in the code. I'm assuming you want the structure where both "The password must contain at least 9 letters" and "The first password letter must be uppercase"can be returned if both their conditions are met.
If, however, you don't need this capability, simply replace the second if with an elif and it should work.
If you need this capability, try something like:
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
if x[0].islower():
print("The first password letter must be uppercase")
if len(x) >= 9 and x[0].isupper():
print("Password saved")
password = x
This simply adds a third if statement testing that the previous conditions were fulfilled.
I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.
I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.
isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.