Home > Mobile >  I wrote a code for a function that calculate the number of upper case letters and lower case letters
I wrote a code for a function that calculate the number of upper case letters and lower case letters

Time:06-19

**a = input('str?: ')

def uplow(a):
    up = 0
    low = 0
    for i in a:
        if i in a.upper():
            up = up   1
        if i in a.lower():
            low = low   1
    print('upper case letters: ',up)
    print('lower case letters: ',low)

uplow(a)**

But I'm not sure is it the best way I could write this code or not; Please tell me if you know better and shorter code for this function. Also if you have suggestion for my tags tell me.

CodePudding user response:

You can just use the isupper() function to check if a character is uppercase

def uplow(a):
    upper = 0
    lower = 0
    for char in a:
        if char.isupper():
            upper  = 1
        else:
            lower  = 1
    print('upper case letters: ',up)
    print('lower case letters: ',low)

CodePudding user response:

You can do it by summing a generator expression:

def uplow(a):
    upper = sum(1 for i in a if i.isupper())
    lower = len(a)-upper
    return upper, lower

CodePudding user response:

There's probably a better way using the method isupper(). The code will look like:

def uplow(a):
    upper = 0
    lower = 0
    for letter in a:
        if letter.isupper():
            upper  = 1
        else:
            lower  = 1
  • Related