Each of the following Python functions is supposed to check whether its argument has any lowercase letters.
For each function, describe what it actually does when called with a string argument. If it does not correctly check for lowercase letters, give an example argument that produces incorrect results, and describe why the result is incorrect.
# 1
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
# 2
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
# 3
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
# 4
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
# 5
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
<i title="Previous: Reading Assignment"></i>
1. For the first function, the function takes the string s and first passes it to the for loop, which checks if all elements in the string are lowercase. The function returns True if positive and False when negative
2. This is just like the first function except that this function first converts the given input to a string
3. The third function takes the given string, checks if it is in lowercase and passes the results (true or false) to the flag variable which the function returns
4. The fourth function takes a string, it then sets the flag variable as false, we then use the islower() function and Boolean variable to check if every letter is in lowercase or not.
5. The last function takes a string, we iterate through the string using the for loop, it makes use of the if, not else statements to check if each letter is in lowercase or not and then returns the results
Comments
Leave a comment