Check to see if capital letters exist in string [duplicate] - python

This question already has answers here:
How to test if a string has capital letters
(3 answers)
Closed 2 years ago.
I was supposed to write a program that verifies a username. The username must consist of at least 8-15 letters, no alphanumeric values. So, you can only have numbers and letters. You can't have numbers at the beginning or the end. And, You MUST have at least one capital and lower case letter and at least one number. I got how to do everything but how to get the program to check to see if it contains any capital letters. I tried to do the " if not in " but no luck. This is what I have so far.
username = input("please enter a name: ")
for i in username:
while len(username) < 8 or len(username) > 15:
print("Password is too long or too short")
username = input("please enter a name: ")
j = 31
while j < 47:
j += 1
while chr(j) in i:
print("No alphanumeric values allowed.")
username = input("please enter a name: ")
k = 57
while k < 64:
k += 1
while chr(k) in i:
print("No alphanumeric values allowed.")
username = input("please enter a name: ")
l = 47
while l < 57:
l += 1
while chr(l) in username[0]:
print("you cannot have a number in the beggining")
username = input("please enter a name: ")
while chr(l) in username[-1]:
print("you cannot have a number in the end")
username = input("please enter a name: ")

You can use any with a generator to test if the string has a capital letter
testString = "abjKcf"
print(any(x.isupper() for x in testString)) #true
Good Solution
As for addressing a solution to your problem, welcome to the world of generator expressions and assertions
while True:
testString = input()
try:
assert 8 <= len(testString) <= 15, "String must be between 8 and 15 characters"
assert all(x.isalnum() for x in testString), "String must be alphanumeric"
assert any(x.isupper() for x in testString), "String must contain one capital"
assert any(x.islower() for x in testString), "String must contain one lowercase"
assert any(x.isdigit() for x in testString), "String must contain one digit"
assert testString[0].isdigit() == False, "No numbers at start"
assert testString[-1].isdigit() == False, "No numbers at end"
break #if we haven't hit any errors then the username fits the criterion
except Exception as e:
print(e)
Really ugly solution (as requested)
Basically you set up some booleans and try to disprove them by looping through every character and checking if it meets some conditions
while True:
testString = input()
allAlphaNumeric = True
oneCapital = False
oneLowerCase = False
oneDigit = False
for letter in testString:
if not letter.isalnum():
oneAlphaNumeric = False
if letter.isupper():
oneCapital = True
if letter.islower():
oneLowerCase = True
if letter.isdigit():
oneDigit = True
numberAtStart = testString[0].isdigit()
numberAtEnd = testString[-1].isdigit()
if allAlphaNumeric and oneCapital and oneLowerCase and oneDigit and not numberAtEnd and not numberAtStart:
break
if not 8 <= len(testString) <= 15:
print("String must be between 8 and 15 characters")
if not allAlphaNumeric:
print("Your string must be alphanumeric!")
if not oneCapital:
print("Your string must contain at least one capital letter")
if not oneLowerCase:
print("Your string must contain atleast one lowercase letter")
if not oneDigit:
print("Your string must contain atleast one digit")
if numberAtStart:
print("You cannot have a number at the start")
if numberAtEnd:
print("You cannot have a number at the end")

Related

How to write Pseudocode for Random Password Generator created using Python?

I need to write a pseudocode for the random password generator below. How do I write a pseudocode Do help me out. Thank you.
import random
import string
print('hello, Welcome to Password generator!')
l = False
while not l:
length = int(input('\nEnter the length of password: '))
if length < 8 :
print('You password length is too short(must be more than 8 character)')
print(length, "is the length of your password")
elif length > 16:
print('You password length is too long(must be less than 17 character)')
print(length, "is the length of your password")
else:
print('You password length looks good')
break
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
all = lower + upper + num + symbols
temp = random.sample(all,length)
password = "".join(temp)
print(password)
is this good enough?
IMPORT random
IMPORT string
OUTPUT('hello, Welcome to Password generator!')
SET l TO False
WHILE not l:
SET length TO int(INPUT('\nEnter the length of password: '))
IF length < 8 :
OUTPUT('You password length is too short(must be more than 8 character)')
OUTPUT(length, "is the length of your password")
ELSEIF length > 16:
OUTPUT('You password length is too long(must be less than 17 character)')
OUTPUT(length, "is the length of your password")
ELSE:
OUTPUT('You password length looks good')
break
SET lower TO string.ascii_lowercase
SET upper TO string.ascii_uppercase
SET num TO string.digits
SET symbols TO string.punctuation
SET all TO lower + upper + num + symbols
SET temp TO random.sample(all,length)
SET password TO "".join(temp)
OUTPUT(password)
or this one :
DECLARE length<-int(input('\nEnterthelengthofpassword:')) : INTEGER
import random
import string
OUTPUT 'hello, Welcome to Password generator!'
l<-False
WHILE not l DO
INPUT length<-int(input('\nEnterthelengthofpassword:'))
IF length < 8
THEN
OUTPUT 'You password length is too short(must be more than 8 character'
OUTPUT length, "is the length of your password"
ENDIF
elif length > 16: //You will need to change this to CASE OF
OUTPUT 'You password length is too long(must be less than 17 character'
OUTPUT length, "is the length of your password"
ELSE
OUTPUT 'You password length looks good'
break //This might be better as a repeat loop
ENDWHILE
lower<-string.ascii_lowercase
upper<-string.ascii_uppercase
num<-string.digits
symbols<-string.punctuation
all<-lower + upper + num + symbols
temp<-random.sample(all,length)
password<-"".join(temp)
OUTPUT password
Process finished with exit code 0
Pseudocode is kind of code, and is meant to show the steps of a specific algorithm. For this algorithm, it might look like this.
output "Welcome"
l := false
while l is not true do
length := int value of input("Enter length of password: ")
if length < 8 do
output "Your password is too short"
else if length > 16 do
output "Your password is too long"
else do
output "Password length looks good"
break from loop
endif
endwhile
lower := array of lowercase letters
upper := array of uppercase letters
numbers := array of digit characters
symbols := array of punctuation characters
all := lower combined with upper combined with numbers combined with symbols
temp := random sample of all, with length len
password := join "" with temp
output password
For more reading on pseudocode, look at this link: https://en.wikipedia.org/wiki/Pseudocode

How to limit the type of characters input python

How can I limit the number of characters and type of characters that can be inputted.
s = input('What is your number)
a number can only be 9 digits so it should be limited to 9 digits and only numbers
x = input('what is your email address)
an email address can contain a minimum of 8 characters and a maximum of 60 characters and also must contain an # symbol.
How would I go about doing this?
In fact, my dear friend, you cannot limit input function, but you can achieve what you want by this way:
def isnumber(s):
if s.isdigit() and len(s) <= 9:
return True
else:
print('you should input number and length less than 9')
return False
def main():
s = input('What is your number')
while not isnumber(s):
s = input('What is your number')
print("your number is", s)
if __name__ == "__main__":
main()

Python Password Checker Help Debugging

So in my computer programming class we've been tasked with making the generic password strength checker, mine works and checks the length correctly but for whatever reason the 2nd part doesn't work properly and I can't figure out why.
password = input("Please enter a password between 6 - 12 characters long: ")
while len(password) in range(6, 13) == False:
if len(password) < 6:
print("Password too low!")
password = input("Please enter a password between 6 - 12 characters long: ")
elif len(password) > 12:
print("Password too high!")
password = input("Please enter a password between 6 - 12 characters long: ")
Upper = 0
Lower = 0
Numerical = 0
for char in password:
if char == char.isupper():
Upper = Upper + 1
elif char == char.islower():
Lower = Lower + 1
elif char == char.isnumeric():
Numerical = Numerical + 1
Strength = int(Upper + Lower + Numerical)
if Strength == 1:
print("Password is weak!")
elif Strength == 2:
print("Password is medium!")
elif Strength == 3:
print("Password is strong!")
Any help would be greatly appreciated, I browsed other similar problems but with something specific it's kind of difficult.
EDIT: Removing the parenthesis from my while loop will do nothing, it works the same anyway. The in range part makes no difference, I still get the error:
Traceback (most recent call last):
File "C:\Users\Owen\Desktop\Password Checker.py", line 21, in
for char in password():
There are a lot of little issues you can fix with this section of code so I can't really tell you what is producing the improper output.
1) as Ken stated:
len(password) != range(6, 12) will always return true. This is because you are comparing an int to a list.
range(6, 12) gives you [6, 7, 8, 9, 10, 11] so the length of the password can never be equal to that statement. However, if you use len(password) in range(6, 12) the length of the password is compared to each value in the list until there is a match (if there is one). One more thing, using range(a, b) only includes numbers from a to b-1. So you really want:len(password) in range(6, 13)
2) The logic of the while loop should change with changes from my first point.
If len(password) in range(6, 13) evaluates to True, then the while statement won't loop and you will move on to the next section. You can delete the else section and change your elif to else.
3) You can get rid of LengthLow and LengthHigh since you aren't using them anywhere.
4) password is a string so you can't call it with the () operator. Your for loop should be for char in password:
5) Use char.isupper(), char.islower(), or char.isnumeric() to check if they are numeric values
6) You don't need to store Upper, Lower, and Numerical separately since you are just adding them together at the end anyways. You can actually accomplish this with a one liner if you are familiar with list comprehensions
strength = sum([1 if c.isupper() or c.islower() or c.isnumeric else 0 for c in password])
Although, it seems to me that this is all the same as c.isalnum() for alphanumeric. So write,
strength = sum([1 if c.isalnum() else 0 for c in password])
7) I don't know anything about password strength calculation, but I think special characters should be considered as well. In that case c.isalnum() won't be the magic all in one that it is in your current code.
There may be more bugs that I haven't noticed, but that should definitely get you on your way to fixing the problem.
ero1ca's answer explains many of the issues.
As for the last part of the code not working, that is because you loop through every char in the password, and increment based on what that character is. With a mandated length > 3, your conditional statements at the end wont cover the password!
below is a revised version of the code.
password = input("Please enter a password between 6 - 12 characters long: ")
while not len(password) in range(6, 13):
if len(password) < 6:
print ("Password too low!")
else:
print ("Password to high!")
password = input("Please enter a password between 6 - 12 characters long: ")
Upper = 0
Lower = 0
Numerical = 0
if any(x.isupper() for x in password):
Upper = 1
if any(x.islower() for x in password):
Lower = 1
if any(x.isdigit() for x in password):
Numerical = 1
Strength =int(Upper + Lower + Numerical)
if Strength == 1:
print ("Password is weak!")
elif Strength == 2:
print ("Password is medium!")
else:
print ("Password is strong!")
Use raw_input instead of input() for python 2.7
Edit Holy Necro! My mistake lads!

ISBN Checker - validating user input

So, my task is to validate the user's input for each of the ISBN 10 digits that they input. I need to make sure that 1) the user input isn't blank, 2) the user input is only an integer (which I've done), and 3) that they only enter ONE digit.
Sorry, I have seen a few similar questions on this, but I wanted to keep the try-except statement (if possible) so the similar questions weren't too helpful.
How can I go about validating against blank inputs and that only one digit is entered?
Here is the code:
print("You will be asked to enter an ISBN-10 Number. Please enter it digit by digit.")
ISBN10NumberList = []
ISBN10NumberAdder = 0
for count in range (10):
validInput1 = True
if (count <= 8):
while validInput1 != False:
try:
ISBN10NumberList.append(int(input("Please enter the ISBN digit: ")))
validInput1 = False
except ValueError:
print("That is not a valid input! Please enter a integer only.")
elif (count == 9):
CheckDigit10 = input("Please enter the ISBN digit: ")
print("")
if CheckDigit10 == "X" or CheckDigit10 == "x":
CheckDigit10 = 10
for count in range (0, 9):
ISBN10NumberAdder += int(ISBN10NumberList[count]) * (10 - count)
CheckDigit10 = int(CheckDigit10)
CheckingCheckDigit = 11-(ISBN10NumberAdder % 11)
if (CheckDigit10 == CheckingCheckDigit):
print("This is a valid ISBN!")
else:
print("This is not a valid ISBN!")
So yes - you are making life hard for yourself and your user - here is a simpler implementation where the user can enter the ISBN in one fell swoop. I factored out some things into functions to make things a little cleaner
In the main loop, the user will be repeatedly prompted for an ISBN until they enter a valid one
def verify_check(isbn_str):
last = isbn_str[-1] # Last character
if last == 'X':
check = 10
else:
check = int(last)
# This part was fine in your original:
adder = 0
for count in range(9):
adder += int(isbn_str[count]) * (10 - count)
if adder % 11 != check:
raise ValueError("Checksum failed")
def verify_isbn10(isbn_str):
if len(isbn_str) != 10:
raise ValueError("ISBN must be 10 digits long")
# Check that the first nine chars are digits
for char in isbn_str[:-1]:
if not char.isdigit():
raise ValueError("ISBN must contain digits or X")
# Special case for the last char
if not (isbn_str[-1].isdigit or isbn_str[-1] == "X"):
raise ValueError("ISBN must contain digits or X")
verify_check(isbn_str)
# Main code:
while 1:
try:
isbn_str = raw_input("Enter ISBN: ")
verify_isbn(isbn_str)
break
except ValueError as e:
print "Whoops:", e
# At this point, isbn_str contains a valid ISBN
If you want to use Kevin's suggestion and try your hand at regexes, you can use something like the following replacement for verify_isbn10. Note that it doesn't explain to the user exactly what was wrong.
import re
isbn_re = re.compile(r"""
^ #Start of string
[0-9]{9} # Match exactly 9 digits
[0-9X] # Match a digit or X for the check digit
$ # Match end of string
""", re.VERBOSE)
def verify_isbn10(isbn_str):
m = isbn_re.match(isbn_str)
if m is None: #User didn't enter a valid ISBN
raise ValueError("Not a valid ISBN")
verify_check(isbn_str)

Asking for 10-digit numbers

I am testing that the user input is of length 10 and only contains numbers. At the moment, my code is:
while True:
number = input("Enter number: ")
try:
if len(number) != 10:
print ("Enter 10 digits\n")
continue
except ValueError:
print ("Enter only numbers\n")
continue
else:
break
The program will ask for user input, then test that it is of 10 length and only contains integers.
Currently, user input is read as a string so that if it began with a '0', then this would be included in len(), if you know what I mean? For example, if I inputted '0123456789', this would be seen to have a length of 10 and not 9 because it begins with '0'.
Also, I wanted to ensure that if the user entered 10 letters, this would be declined because only numbers are allowed.
Any help would be greatly appreciated.
Thank you.
At no point in your code do you actually check that the input is an integer..
You could do something like this:
while True:
number = input("Enter number: ")
if not number.isdigit(): # check if a string contains a number with .isdigit()
print ("Enter only numbers\n")
continue
elif len(number) != 10:
print ("Enter 10 digits\n")
continue
else:
break
Info on str.isdigit():
Type: method_descriptor
String Form:<method 'isdigit' of 'str' objects>
Namespace: Python builtin
Docstring:
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
while True:
number = input("Enter number: ")
try:
number = int(number)
except ValueError:
print ("Enter only numbers")
else:
if 10 > number//10**9 > 0 :
print ("Enter 10 digits")
continue
else:
break
You can checking for an error while casting to a number (integer)
try:
if len(number) != 10 and int(number):
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue
Note that the flaw in len(number) is that the nine firsts digit could be 0.
To ensure that is a valid number beetwen 1000000000 and 999999999 you can do the following:
import math
while True:
try:
if math.floor(math.log10(int(number)))+1 == 10:
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue

Categories