0

I'm trying to write a program that has a function that takes in a string and prints the number of capital letters in the first line, then prints the sum of their indices in the second line.

Here is what I came up with but I am getting errors. Anybody knows what I can fix on this code to make it run?

import sys

def string(s):
    a={"UPPER":0}
    for b in s:
        if b.isupper():
           a["UPPER"]+=1
        
    print ("No. of Upper case characters : ", a["UPPER"])               
    
    ind = [idx for idx in range(len(val)) if val[idx].isupper()]      
    
    Sum=sum(ind)
    print(Sum)
    
val = input("")
string(sys.argv[1])
Rahul K P
  • 15,740
  • 4
  • 35
  • 52

1 Answers1

1

The issue with your code is val is declared outside the scope of function.

You can rewrite your function like this.

def string(s): 
    ind = [idx for idx, i in enumerate(s) if i.isupper()]
    print(f"Sum of index of upper case character : {sum(ind)}")
    print(f"No. of Upper case characters : {len(ind)}")

Execution:

In [1]: string('Hello World')
Sum of index of upper case character : 6
No. of Upper case characters : 2
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • I didn't try very hard to understand the code, I just noticed the same typo you did (and voted to close on that basis). However, if the most important part is using `enumerate`, then perhaps it would be better to consider this question as a duplicate. The most applicable canonical I can think of is https://stackoverflow.com/questions/522563. – Karl Knechtel Oct 09 '22 at 06:03
  • @KarlKnechtel Marked the question to close it. – Rahul K P Oct 09 '22 at 06:05