Reputation: 293
learning python and working with some basic string methods.
I have this program which finds the index of the first lowercase char in a string:
def find_lower(word):
i = 0
while not isupper(word[i]):
i = i+1
return i
however, when I run this code, I get the error
builtins.NameError: name 'isupper' is not defined
Do I need to import a module or something for isupper()
to work?
Upvotes: 1
Views: 4880
Reputation: 21609
You are using isupper
incorrectly. It is not a built in standalone function. It is a method of str
. The documentation is here.
For any function that you are unsure of you can consult the python documentation. It is well indexed by google so a google search is a good place to begin when you want to understand how to use a function.
Once that is out of the way, your find_lower
has a few more issues. It actually finds the index of the first upper case letter due to a logic error.
while not word[i].isupper():
Continues to loop if the character is not upper case and stops if it is. So you need to remove the not
.
def find_lower(word):
i = 0
while word[i].isupper():
i = i+1
return i
print(find_lower('ABcDE')) # prints 2
The next error is that if there are no lowercase characters it walks off the end of the string and throws an exception
>print(find_lower('ABCDE'))
Traceback (most recent call last):
File "./myisupper.py", line 11, in <module>
print(find_lower('ABCDE'))
File "./myisupper.py", line 5, in find_lower
while word[i].isupper():
IndexError: string index out of range
To fix this you need to limit the number of iterations to the length of the string, this is left as an exercise to fix.
Upvotes: 4
Reputation: 4992
isupper is a method of string. so, you should use it on a string
For example,
a = "Hello"
#You can check upper on this as follows
print(a.isupper())
In your case, change the following
while not isupper(word[i]):
to
while not word[i].isupper():
print("Your x here")
Upvotes: 3
Reputation: 311508
isupper
is a method of string, and should be called by that object: word[i].isupper()
.
Upvotes: 2
Reputation: 5334
it should be like
def find_lower(word):
i = 0
while not word[i].isupper():
i = i+1
return i
Upvotes: 1