DA_F
DA_F

Reputation: 63

Counting if the word entered is a capital letter in a loop in Python 3

I'm trying to that function that keeps prompting the user for words until they hit return. At that point, the program should return the number of upper-case words entered by the user.

What I have so far.

def upper():
    while True:
        x = input('Please enter word: ')
        if x.strip() == "":
            break
    print(len(x.split()))
upper()

How exactly would I count for capital letters each time it loops? I tried print(len(x.split())) but that only returns zero for the last iteration.

-------------------------------edit

def upper():
    while True:
        x = input('Please enter word: ')
        if x.strip() == "":
            break
    capitalLetters = 0
    for letter in x:
        if letter.isupper():
            capitalLetters += 1
    upper()

Upvotes: 0

Views: 608

Answers (3)

Keatinge
Keatinge

Reputation: 4341

This solution creates a list comprehension of the letters that are capital and then gets the length of that list

capitalLetters = len([letter for letter in x if letter.isupper()])
print(capitalLetters)

You could also use a regular for loop and loop through each letter and check if its capital, then increment a variable:

capitalLetters = 0
for letter in word:
    if letter.isupper():
        capitalLetters += 1

For your code

def upper():
    while True:
        x = input('Please enter word: ')
        if x.strip() == "":
            break
        capitalLetters = 0
        for letter in x:
            if letter.isupper():
                capitalLetters += 1
        print(capitalLetters)
upper()

Upvotes: 1

mhyst
mhyst

Reputation: 297

The idea is this:

count=0
countTotal=0
for c in x:
    if c >= 'A' and c <= 'Z':
        count++
countTotal += count

You need to make the count for each word entered, and then keep a countTotal variable to accummulate all the words' uppercases.

Upvotes: 1

a p
a p

Reputation: 3208

Here you go buddy

numUppers = lambda s: sum(map(lambda c: 65 <= ord(c) <= 90, s))

Upvotes: 2

Related Questions