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
Your function is not returning anything, so the function implicitly returns
None
. That's why you are seeingNone
. You need to usereturn upper
to return the value; note that return statement is outside thefor
loop.else: pass
is redundant.sys.argv[1]
is already a string, sostr
in front ofsys.argv[1]
is redundant.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>