I need to determine if there are alphabetic and numeric characters in a string. My code for testing the alphabetic one seems to work fine, but numeric is only working if all of the characters are a digit, not if any.
The alphabetic code that works:
from curses.ascii import isalnum, isalpha, isdigit
password = input("Enter your password: ")
def contains_alphabetic():
for i in password:
if isalpha(i):
print("Valid")
return True
else:
print("Invalid")
return False
contains_alphabetic()
This returns "Valid" if at least one of the characters is alphabetic, and "Invalid" if none of them are, which is what I want.
def contains_numeric():
for j in password:
if isdigit(j):
print("Valid")
return True
else:
print("Invalid")
return False
contains_numeric()
This only returns "Valid" if all of the characters are numeric, not if at least one is. How do I fix this?
Also, I tried using is.numeric() instead of is.digit() and it wouldn’t even import.
>Solution :
As the comments have pointed out, both your contains_alphabetic and contains_numeric functions don’t do what you think they’re doing, because they terminate prematurely – during the very first iteration. You start a loop, inspect the current character (which will be the first character of the string during the first iteration of the loop), and immediately return something from the function based on that single character, which of course terminates the loop and the function.
Other suggestions: There’s no need to import things from curses. Strings already have isalpha and isdigit predicates available. Additionally, it’s probably a good idea to have your functions accept a string parameter to iterate over.
If the idea is to return True if any of the characters in a string satisfy a condition/predicate, and False otherwise (if none of the characters satisfy the condition), then the following would be a working implementation:
def contains_alpha(string):
for char in string:
if char.isalpha():
return True # return True as soon as we see a character that satisfies the condition
return False # Notice the indentation - we only return False if we managed to iterate over every character without returning True
Alternatively:
def contains_alpha(string):
found = False
for char in string:
if char.isalpha():
found = True
break
return found
Or:
def contains_alpha(string):
for char in string:
if char.isalpha():
break
else: # Notice indentation - special for-else syntax: If we didn't break out of the loop, execute the else
return False
return True
Or:
def contains_alpha(string):
return any(char.isalpha() for char in string)