Home > OS >  Write a Python function that accepts a string and calculate the number of upper case letters and low
Write a Python function that accepts a string and calculate the number of upper case letters and low

Time:12-02

I have tried this solution. But I am not receiving any output. Can someone please point out my error.

def num_case(str):
    z=0
    j=0
    for i in str:
        if i.isupper():
            z=z 1
            return z
        elif i.islower():
            j=j 1
            return j
        else:
            pass
    
    
    
    print('upper case:', z)
    print('lowercase:', j)
    
num_case('The quick Brow Fox')

CodePudding user response:

You are returning your function inside your loop. So once if finds a uppercase or lowercase it will directly return from the function. Just remove the return lines.

CodePudding user response:

You should not put return statements inside the loop. The num_case function should look like this:

def num_case(str):                                   
    z = 0                                            
    j = 0                                            
    for i in str:                                    
        if i.isupper():                              
            z = z   1                                
        elif i.islower():                            
            j = j   1                                                                   
                                                 
    return (z, j)                                    
                                                 
                                                 
uppercase, lowercase = num_case('The quick Brow Fox')
                                                 
print("upper case:", uppercase)                      
print("lowercase:", lowercase)                       

CodePudding user response:

  • Don't use builtin names like str.

  • instead of returning the value inside the loop return or print after the loop.

  • No need to add else if you are just going to pass

  • try to use understandable variable names while writing the code.

def num_case(str_val):
    upper_count = 0
    lower_count = 0
    for val in str_val:
        if val.isupper():
            upper_count  = 1
        elif val.islower():
            lower_count  = 1

    print('upper case:', upper_count)
    print('lowercase:', lower_count)


num_case('The quick Brow Fox')
  • Related