password strength code help python - python

so i am writing code in python to tell you your password strength but it is not doing as i say and keeps saying invalid password password unless you use only numbers
hy=1
while(y==1):
passwordentered=str(input("plaese enter your proposed password "))
x=len(passwordentered)
numbers=passwordentered.count ("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
lowerletters=passwordentered.count ("a"and"b"and"c"and"d"and"e"and"f"and"g"and"h"and"i"and"j"and"k"and"l"and"m"and"n"and"o"and"p"and"q"and"r"and"s"and"t"and"u"and"v"and"w"and"x"and"z")
higherletters=passwordentered.count ("A"and"B"and"C"and"D"and"E"and"F"and"G"and"H"and"I"and"J"and"K"and"L"and"M"and"N"and"O"and"P"and"Q"and"R"and"S"and"T"and"U"and"V"and"W"and"X"and"Z")
if(numbers>0 and lowerletters==0 and higherletters==0):
david=9
elif(lowerletters>0 and numbers==0 and higherletters==0):
david=9
elif(higherletters>0 and numbers==0 and lowerletters==0):
david=9
elif(higherletters>0 and numbers>0 and lowerletters==0):
david=8
elif(higherletters>0 and lowerletters>0 and numbers==0):
david=8
elif(numbers>0 and lowerletters>0 and higherletters==0):
david=8
elif(numbers>0 and lowerletters>0 and higherletters>0):
david=7
elif(x>12 or x<6):
david=10
elif(lowerletters==0 and numbers==0 and higherletters==0):
david=10
if(david==10):
print("the password you entered was invalid\
why not try again.")
y=1
elif(david==9):
print("the password you entered is very weak,try to include numbers, lower case letters and upper case letters. why not have another go.")
y=1
elif(david==8):
print("your password is good but it could be better try to include numbers, lower case letters and upper case letters. why not have another go.")
y=1
elif(david==7):
print("your password is really good. thank you for using this program")
y=0
any help would be appriciated

First of all, Python is a very forgiving language, you can get away with a lot of stuff that you can't do in other languages, HOWEVER:
numbers=passwordentered.count("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
Will not work. Python will evaluate everything within the brackets as a boolean expression and this line of code essentially boils down to:
numbers=passwordentered.count("9")
The same goes for the other checks as well. To get what you actually wanted from this, you should use a loop of some sort. You can use something like this:
numbers = sum( ch.isdigit() for ch in passwordentered )
This will give you a count of how many digits are found within the password string. You can modify this to count the number of lowercase and uppercase letters too.
Finally, you should try to clean up your if statements, you could break them down a bit more neatly and make this more readable.

Those count functions won't work if written like that.
Try to replace this:
numbers=passwordentered.count ("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
lowerletters=passwordentered.count ("a"and"b"and"c"and"d"and"e"and"f"and"g"and"h"and"i"and"j"and"k"and"l"and"m"and"n"and"o"and"p"and"q"and"r"and"s"and"t"and"u"and"v"and"w"and"x"and"z")
higherletters=passwordentered.count ("A"and"B"and"C"and"D"and"E"and"F"and"G"and"H"and"I"and"J"and"K"and"L"and"M"and"N"and"O"and"P"and"Q"and"R"and"S"and"T"and"U"and"V"and"W"and"X"and"Z")
with the following:
numbers = sum(typ in "0123456789" for typ in passwordentered)
lowerletters = sum(typ in "abcdefghijklmnopqrstuvwxyz" for typ in passwordentered)
higherletters = sum(typ in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for typ in passwordentered)
or the following for a verbose approach:
numberlist = "0123456789"
Lletterlist = "abcdefghijklmnopqrstuvwxyz"
Hletterlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers=0
lowerletters=0
higherletters=0
for f in xrange(0, x):
if numberlist.find(passwordentered[f]) != -1:
numbers = numbers+1
if Lletterlist.find(passwordentered[f]) != -1:
lowerletters = lowerletters+1
if Hletterlist.find(passwordentered[f]) != -1:
higherletters = higherletters+1

Related

Python Nested List: How to print specific elements and append to each sublist

quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for i in range(len(quizes)):
grade = eval(input("Enter", quizes[i][0],"grade:"))
quizes[i].append(grade)
print(quizes[i])
Hey guys so I been working on this for the past week and can't solve this. I am trying to get my program to ask "Enter [person1] grade: " and so on and append a second element to each sublist which will be their grade and then print the contents of the entire list. Any help is appreciated
The problem is input takes 1 string as a parameter, you are passing 3 instead. So:
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
grade = eval(input(f"Enter {l[0]} grade:"))
l.append(grade)
print(l)
However, I respectfully don't understand the point of using eval here. Eval turns data into code. Using eval on user input creates a great security hole. In the above code, what if the user input quizes.clear()? The whole array will be emptied. What if he inputs something eviler?
Consider (assumes valid grades only contain numbers):
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
while True:
try:
grade = float(input(f"Enter {l[0]} grade:"))
except ValueError:
print("Please input a number.")
else:
l.append(grade)
break
print(quizes)
The main problem is that input() accepts only one argument as the input prompt, unlike print which can take any number of arguments - you're giving 3 parameters to the input function - "Enter", quizes[i][0], and "grade:".
You can try concatenating them - like input("Enter "+str(quizes[i][0])+" grade:") (the str() conversion is not needed if you know that all the quizes[i][0] will be strings already),
or even use string formatting - "Enter {} grade".format(quizes[i][0]) or f"Enter {quizes[i][0]} grade:"
This should be enough, but there are 2 more changes you can make to your code if you like -
Iterate over the nested lists directly (for sub_list in quizes:)
Using int() or float() to convert a returned input string containing a number will also work in place of eval
For example
for quiz in quizes:
grade = eval(input("Enter {} grade:".format(quiz[0])))
quiz.append(grade)
print(quiz)
EDIT: Python docs on string formatting The f"..." syntax works only for Python 3.6+
You need to change:
grade = eval(input("Enter", quizes[i][0],"grade:"))
to
grade = eval(input("Enter " + quizes[i][0] + " grade:"))
input does not behave as print does. You can't use commas to join text in any other function (except for a very small number of custom functions and modules), and you should stay away from them at if that's confusing for you to only use them sometimes.
With that change, does your code work now? You didn't tell us why it wasn't working the way you expected.
Now that I'm looking at it, what did yours do wrong?
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for quiz in quizes:
grade = eval(input("Enter " + quiz[0] + " grade:"))
quiz.append(grade)
print(quiz)
print(quizes)

How do I define the number variable in this function?

I don't really know anything about user defined functions and I am wondering how do I define the number variable in this function?
def getNumber(str,input,number):
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber(number)
Why do you even need parameters for your function. Try the below code.
You are clearly defining number in the function.
You are getting the input from the user.
I think that's all you are actually looking for.
Also your function has 3 parameters and you were passing only one as a number and that was not even defined, that's why you got the error. Even if you had defined the variable number, you still would have got the error as you had two more parameters in there which didn't make sense as you don't need them!
def getNumber():
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber()
In Python, this
def getNumber(str,input,number):
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber(number)
is very different to this
def getNumber(str,input,number):
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber(number)
When you run the first version, the third line containing if (number.isdigit() is not part of your function - it's not indented, so is actually outside the function and at the root of your module.
This means that when you run your module you are working on a variable (the number variable) which hasn't been declared and doesn't exist.
You can define any value to a variable by var_name = value, i.e. num = 4 or string = 'A string.
You want to scan the user input and verify there aren't any non-digit characters in the string (\D):
import re
def getNumber():
number= str(input("Give me a number!:"))
# re (regex module), check for characters in the alphabet
if re.search('\D',number) != None:
return False # or use re module to remove unwanted characters by using re.replace().
else:
if '.' in number:
return float(number)
else:
return int(number)
Note The way this is written, when the function is called it will ask the user for input. If you want to check whether an input is a number, without calling user input inside the function, give the function a parameter that it will check. i.e.
import re
def getNumber(input):
# re (regex module), check for characters in the alphabet
if re.search('\D',number) != None:
return False # or use re module to remove unwanted characters by using re.replace().
else:
if '.' in input:
return float(input)
else:
return int(input)
>>> getNumber('a3')
False
>>> getNumber('3')
3
Hope this helps. Be sure to check out the re module docs for more info.
Cheers!

How to set the symbol group list of lists to generate the random password using Python?

I am generating random password using random library following example 8 of this page. Here I am setting a default value for symbolgroups which contains all type characters in a single string. The code looks like this:
def get_random_string(length=20, symbolgroups="0123456789abcdefghijklmnopqrstuvwxyz!##$%^&*():<>/|}{[]`\`"):
if length is None:
length = CONF.password_length
r = random.SystemRandom()
password = [r.choice(s) for s in symbolgroups]
r.shuffle(password)
password = password[:length]
length -= len(password)
symbols = ''.join(symbolgroups)
password.extend([r.choice(symbols) for _i in xrange(length)])
r.shuffle(password)
return ''.join(password)
rand = get_random_string()
print(rand)
The code produces a random password, but I am being told that I am using symbolgroups incorrectly.
The code given in the question actually comes from example 8 on this page where it is also properly documented. There is nothing wrong with the code and it is also not bloated as we first believed in the comments. The only problem was that the OP misunderstood the use of symbolgroups. Here the idea was to guarantee that the final password contains one character of each character group defined in symbolgroups. If instead of the original, the default value for symbolgroups is changed into a list, the code should work as expected. For instance, we could group the list of characters into lower case letters, numbers, and others:
def get_random_string(length=20, symbolgroups=["0123456789","abcdefghijklmnopqrstuvwxyz","!##$%^&*():<>/|}{[]`\`"]):
if length is None:
length = CONF.password_length
r = random.SystemRandom()
password = [r.choice(s) for s in symbolgroups]
r.shuffle(password)
password = password[:length]
length -= len(password)
symbols = ''.join(symbolgroups)
password.extend([r.choice(symbols) for _i in xrange(length)])
r.shuffle(password)
return ''.join(password)
This gives really nice example results:
^9m0bj83u<h7j^i:^e!}

Python if statement: less than

Ok, can someone tell me how to make an if else statement with a character limit
i wrote a quick code to make you see what am trying to tell you
pass1 = input("What is you'r password: ")
pass2 = input("Rewrite you'r password: ")
what i tried:
if pass1 == <5:
print ("password is greater than 5")
else:
print ("password is lower than 5")
basically am trying to make a limit like in real website when you register (when you register there's a character limit example it cant be lower than 5 characters).
You need to test the length of the string with len function:
if len(pass1) < 5:
Perhaps you may have some confusion also with if statements and arithmetic operators. Check them here:
Control Flow
Comparissons

Serial Key Generation and Validation

I'm toying around with writing creating a serial code generator/validator, but I can't seem to get how to do a proper check.
Here's my generator code:
# Serial generator
# Create sequences from which random.choice can choose
Sequence_A = 'ABCDEF'
Sequence_B = 'UVWQYZ'
Sequence_C = 'NOPQRS'
Sequence_D = 'MARTIN'
import random
# Generate a series of random numbers and Letters to later concatenate into a pass code
First = str(random.randint(1,5))
Second = str(random.choice(Sequence_A))
Third = str(random.randint(6,9))
Fourth = str(random.choice(Sequence_B))
Fifth = str(random.randint(0,2))
Sixth = str(random.choice(Sequence_C))
Seventh = str(random.randint(7,8))
Eighth = str(random.choice(Sequence_D))
Ninth = str(random.randint(3,5))
serial = First+Second+Third+Fourth+Fifth+Sixth+Seventh+Eighth+Ninth
print serial
I'd like to make a universal check so that my validation code will accept any key generated by this.
My intuition was to create checks like this:
serial_check = raw_input("Please enter your serial code: ")
# create a control object for while loop
control = True
# Break up user input into list that can be analyzed individually
serial_list = list(serial_check)
while control:
if serial_list[0] == range(1,5):
pass
elif serial_list[0] != range(1,5):
control = False
if serial_list[1] == random.choice('ABCDEF'):
pass
elif serial_list[1] != random.choice('ABCDEF'):
control = False
# and so on until the final, where, if valid, I would print that the key is valid.
if control == False:
print "Invalid Serial Code"
I'm well aware that the second type of check won't work at all, but it's a place holder because I've got no idea how to check that.
But I thought the method for checking numbers would work, but it doesn't either.
The expression `range(1, 5)' creates a list of numbers from 1 to 4. So in your first test, you're asking whether the first character in your serial number is equal to that list:
"1" == [1, 2, 3, 4]
Probably not...
What you probably want to know is whether a digit is in the range (i.e. from 1 to 5, I assume, not 1 to 4).
Your other hurdle is that the first character of the serial is a string, not an integer, so you would want to take the int() of the first character. But that will raise an exception if it's not a digit. So you must first test to make sure it's a digit:
if serial_list[0].isdigit() and int(serial_list[0]) in range(1, 6):
Don't worry, if it's not a digit, Python won't even try to evaluate the part after and. This is called short-circuiting.
However, I would not recommend doing it this way. Instead, simply check to make sure it is at least "1" and no more than "5", like this:
if "1" <= serial_list <= "5":
You can do the same thing with each of your tests, varying only what you're checking.
Also, you don't need to convert the serial number to a list. serial_check is a string and accessing strings by index is perfectly acceptable.
And finally, there's this pattern going on in your code:
if thing == other:
pass
elif thing != other:
(do something)
First, because the conditions you are testing are logical opposites, you don't need elif thing != other -- you can just say else, which means "whatever wasn't matched by any if condition."
if thing == other:
pass
else:
(do something)
But if you're just going to pass when the condition is met, why not just test the opposite condition to begin with? You clearly know how to write it 'cause you were putting it in the elif. Put it right in the if instead!
if thing != other:
(do something)
Yes, each of your if statements can easily be cut in half. In the example I gave you for checking the character range, probably the easiest way to do it is using not:
if not ("1" <= serial_list <= "5"):
Regarding your python, I'm guessing that when your wrote this:
if serial_list[0] == range(1,5):
You probably meant this:
if 1 <= serial_list[0] <= 5:
And when you wrote this:
if serial_list[1] == random.choice('ABCDEF'):
You probably meant this:
if serial_list[1] in 'ABCDEF':
There are various other problems with your code, but I'm sure you'll improve it as you learn python.
At a higher level, you seem to be trying to build something like a software activation code generator/validator. You should know that just generating a string of pseudo-random characters and later checking that each is in range is an extremely weak form of validation. If you want to prevent forgeries, I would suggest learning about HMAC (if you're validating on a secure server) or public key cryptography (if you're validating on a user's computer) and incorporating that into your design. There are libraries available for python that can handle either approach.

Categories

Resources