Why is my program not detecting uppercase characters? - python

I am asking the user to input a password. The program then determines if the password is valid if it meets certain criteria.
Here is the section in question.
for i in range(0, len(password)):
if(password[i].isdigit()==True):
isNum+=1
elif (password[i].isalpha()==True):
isLetter+=1
elif (password[i].isupper()==True):
isUpper+=1
My program detects numbers and letters just fine, but it doesn't detect uppercase letters. If I put in the password 1234Foxes, it will say that there are 4 letters, 4 numbers, and 8 total characters, but it states that there are 0 uppercase letters.

If isupper is true, isalpha must have been true since an uppercase letter is necessarily alphabetic. Since you're using elif, the conditions are exclusive, and the checks stop once the isalpha check is true.
Just don't use elif there if you want both checks to run:
for character in password:
if(character.isdigit()):
isNum += 1
elif (character.isalpha()):
isLetter += 1
if (character.isupper()):
isUpper += 1
I also got rid of the need to index password by iterating the String directly, and the redundant == True

your logic is correct, but, you need to check if a char is upper before if it is alpha. It's because every upper char is alpha, so, the last elif will never be reached. So, change your code position to this:
for i in range(0, len(password)):
if(password[i].isdigit()==True):
isNum+=1
# isupper() first from isalpha()
elif (password[i].isupper()==True):
isUpper+=1
elif (password[i].isalpha()==True):
isLetter+=1
And, another tip: you can go through every char of string without using indexing, like this:
for char in password:
if (char.isdigit()):
isNum += 1
elif (char.isupper()):
isUpper += 1
elif (char.isalpha()):
isLetter += 1
Since isdigit(), isalpha() and isupper() returns True or False, you don't need to check if it is True or False (no need the == operator), just put it into if statement.

Related

.lower() Returning True when presented with 0

I am attempting to complete a task of ensuring all characters in a string meet the following conditions:
Divisible by 4
Contains "A1" in the string
String only contains Uppercase and Numbers
For most strings the function works; however, I am returning a false False when a 0 is presented.
The problem is localized to the for loop (for character in string:) as shown by the output.
def valid_product_code(string):
if len(string) % 4 == 0:
print("String is divisible by 4")
if "A1" in string:
print("A1 is contained within string")
for character in string:
print(character)
if character == character.lower():
print("Character is a Lowercase")
return False
elif character == ("!"or "." or "," or ":"):
print("Character is punct")
return False
else:
return True
else:
return False
else:
return False
print(valid_product_code("0O3LG6EWN7AA1NI596LCVBRZ"))
The output of the code is as follows:
String is divisible by 4
A1 is contained within string
0
Character is a Lowercase
False
What you are doing is un-pythonic. Instead of using if character == character.lower():, use .islower().
.islower() returns True when there are no uppercase letters in the string and there is at least one lowercase letter. That's not the same thing as all characters being letters.
you need to use if character.islower(): not if character == character.lower(): because '0'.lower()=='0' so that if statement (if character == character.lower():) will always return true if your string contain any digit
The short answer is '0'.lower() == '0'. Instead of checking for bad characters (such as lower-case letters or punctuation), you should describe in Python what it means to be a good character.
In this case, being a good character simply means
'A' <= character <= 'Z' or '0' <= character <= '9'

isupper() and isdigit() not working together

I am trying to create a simple passwprd application and I want to check if my password meets some requierments. I want it to have both an uppercase letter and a digit somewhere. I am storing each letter of the password in a list using a for loop and I then check if each element in the list is uppercase. But when I, in the if statement that checks if the letter is uppercase, add a new if statemnt checking if one of the characters is a digit the if statement doesn’t return anything.
def check_password():
characters = []
if len(password_entry.get()) >= 8:
for i in range (len(password_entry.get())):
characters.append(password_entry.get()[i])
if characters[i].isupper():
if characters[i].isdigit():
register_user()
print("password valid")
else:
password_not_valid_upper()
else:
password_not_valid_length()
You're checking that the character is uppercase, and if it is you're then checking if it's a digit. It can't be both so you're always falling through to the else password_not_valid_upper().

How to find out if a specific digit is in the middle of an integer value?

Homework question is asking me to write a program that would output True if an integer is odd and has the number "0" in the middle of it. I figured out how to get it to print True if a number is odd but can't figure out how to detect if the number 0 is in the middle.
I've figured out the first condition which would be detecting if it's odd.
input:
def is_cyclops(n):
if len(str (n)) % 2 != 0:
return True
return False
print (is_cyclops(11011))
output:
True
I want to know how to get the code to detect the number 0 in the middle.
I'll provide a response in the form of an algorithm:
Convert the number to a string
Detect whether the string has an even or odd number of characters (because even numbered strings don't have a single "middle" character)
Look at the middle character which is character # (len(str)/2)-0.5
That's your middle character
This code will work for an input n.
n = str(n)
if(len(n)%2==0): #Checks if even
if(n[len(n)/2]==0): #Checks for presence of 0
return True
else:
if(n[len(n+1)/2]==0): #Checks for presence of 0
return True

Check python function determine isogram from codewars

An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
Here is my code:
def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
else:
return True
And when I tried to run the test code Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) It failed, but I thought I did convert everything into lowercase. Can someone help?
Try this:
def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
return True
In your code when is_isogram("moose") is called, it will see that the first character's ('m') count is not greater than 1. So it will return True. Once it hits the return statement, it will stop the execution for the rest string. So you should really write return True only after for-loop to make sure that the function checks for the whole string.
If however, at any point, it finds a character's count to be greater than 1, then it will simply return False and stop executing because there's no point of checking any more when one point is found where condition does not hold.
How about using sets? Casting the string into a set will drop the duplicate characters, causing isograms to return as True, as the length of the set won't differ from the length of the original string:
def is_isogram(s):
s = s.lower()
return len(set(s)) == len(s)
print is_isogram("Dermatoglyphics")
print is_isogram("aba")
print is_isogram("moOse")
print is_isogram("")
This outputs:
True
False
False
True
Try this :
def is_isogram(s):
string = s.lower()
if len(s) == len(set(string)):
return True
return False
Try this out:
def is_isogram(string):
return len(string) == len(set(string.lower()))
"Implement a function that determines whether a string that contains only letters is an isogram."
By using sets, you can create unique elements. So if there are any repeating numbers, it will only select one. By calling len() on these strings, you can compare the length to the original.
Sorry if I explained it poorly. I am working on this.
let us define an isogram well:
according to wikipedia An Isogram is a word in which no letter occurs more than once.
check here for more about an isogram
just remind letter
I write this code and it works for me :
def is_isogram(argument):
print(len(argument))
if isinstance(argument,str):
valeur=argument.lower()
if not argument:
return False
else:
for char in valeur:
if valeur.count(char)>1 or not char.isalpha():
return False
return True
else:
raise TypeError("need a string ")
NB: the hidden test is the fact that you must check if the char in the string is a alpha character a-z, when i add this it pass all the hiddens tests
up vote if this help
I reckon this might not be the best solution in terms of maximizing memory space and time. This answer is just for intuition purposes using a dictionary and two for loops:
def is_isogram(string):
#your code here
#create an empty dictionary
m={}
#loop through the string and check for repeating characters
for char in string:
#make all characters lower case to ignore case variations
char = char.lower()
if char in m:
m[char] += 1
else:
m[char] = 1
#loop through dictionary and get value counts.
for j, v in m.items():
#if there is a letter/character with a count > 1 return False
if v > 1:
return False
#Notice the scope of the "return True" command. It is outside.
return True

Having trouble learning how to look at individual characters in a string checking for case or digit

I am trying to write a simple password checker for homework assignment, looking for at least one capital, one lower case, one digit, and it needs to be 6 or more chars.
I have searched and searched on here and elsewhere, but either what I read doesn't match our instruction, or the replies are more advanced than myself. Any help I get will be cited as a comment in my assignment.
This is just the part of my code which checks for caps, it only looks at the whole string, not the individual characters and I can't seem to find the solution.
passwd = input('enter password: ') ## we are actually using (sys.agrv)
## but I am using this for testing
character = passwd[0:]
lcase_bad = False
for character in passwd:
if not character.islower() > 1:
lcase_bad = True
if lcase_bad:
print('Password must include lowercase letters ')
else:
print('password accepted')
for character in passwd:
Here you're iterating through each letter of the input.
When you do if not character.islower() > 1:, it will always be True. .islower() returns either True or False, depending on if the string is a capital letter or not. not False == 1, because boolean is a subclass of int. not True == 0. Both are not greater than one.
You can just do something like:
capital = False
lowercase = False
number = False
if len(passwd) < 6:
print 'That was not more than 6 characters'
else:
for character in passwd:
if character.islower():
lowercase = True
elif character.isupper():
capital = True
elif character.isdigit():
number = True
if capital and lowercase and number:
break
else:
print 'That did not have a capital letter, lowercase letter, and a digit'
Of course this is useful if you want to tell the person what the password didn't have. However, you can also just do one test instead.
Just check for all those conditions one after another:
mystring = input("enter password: ")
if any(c.isupper() for c in mystring) \ # There is an uppercase letter
and any(c.islower() for c in mystring) \ # There is a lowercase letter
and any(c.isdigit() for c in mystring) \ # There is a number
and len(mystring) > 5: # The length is 6 or greater
# string passed all tests
else:
# One or more tests failed--input is bad.
You've almost got it! If you remove the > 1 from your code (which won't really do anything useful), you get this:
lcase_bad = False
for character in passwd:
if not character.islower():
lcase_bad = True
It just happens that this will test to see if the entire string is made of lowercase letters. If it is, lcase_bad will remain False; otherwise, it will become True. It should not be an extreme leap of faith to see that if you flip the False and True around and call it lcase_good, you can see whether at least one character is lowercase.
As iCodez notes, you can also rewrite it using any with a generator comprehension. It reads fairly easily:
if any(character.islower() for character in passwd):
However, you probably haven't gotten to generator comprehensions, so it might be best to stay with a for loop for clarity's sake.

Categories