Home > Net >  Python-sys.argv code for finding number of upper case letters in a string
Python-sys.argv code for finding number of upper case letters in a string

Time:11-21

I wrote a code below in sys.argv library in Python to find the number of upper case letters. This code returns None in input - ApplE is HoT. Any help would be appreciated.

import sys
def c_upper(s):
    upper = 0
    for char in s:
        if char.isupper():
            upper  = 1
        else:
            pass

s = str(sys.argv[1])
print(c_upper(s))

c_upper(s)

CodePudding user response:

Try the following:

# foo.py
import sys
def c_upper(s):
    upper = 0
    for char in s:
        if char.isupper():
            upper  = 1
    return upper

print(c_upper(sys.argv[1]))

Run:

python3 foo.py 'ApplE is HoT' # 4
  1. Your function is not returning anything, so the function implicitly returns None. That's why you are seeing None. You need to use return upper to return the value; note that return statement is outside the for loop.

  2. else: pass is redundant.

  3. sys.argv[1] is already a string, so str in front of sys.argv[1] is redundant.

  4. Once you learn list- or generator- comprehension, you will see the following will be an easier option:

    def c_upper(s):
        return sum(c.isupper() for c in s)
    

CodePudding user response:

Your variable s is unable to retrieve the text so correct it.

import sys
def c_upper(s):
    upper = 0
    for char in s:
        if char.isupper():
            upper  = 1
        else:
            pass
    return upper
s = 'ApplE is HoT'
print(c_upper(s))

c_upper(s)
print(s)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related