How do I get a function's output characters to be automatically counted in python?
Question:
I am trying to print the number of characters that are present in the output my function gives. in this case I’m looking for 90 as "lowercase" 10 times is 90 characters. I’m not really sure what to try, please advise.
num=10
def func(word, add=5, freq=1):
print(word*(freq+add))
test=func("lowercase", num)
print(test, num)
count(test)
When I tried to use the "count" function, I got the below error:
traceback (most recent call last):
File "c:UsersTzvi AryehDocumentspython programs#optional Parameters Tutorial #1.py", line 18, in
count(test)
^^^^^
NameError: name ‘count’ is not defined. Did you mean: ’round’?"
Answers:
The easiest solution is to modify your function so that it return
s the output instead of print
ing it:
num=10
def func(word, add=5, freq=1):
return word*(freq+add)
test=func("lowercase", num)
print(test, num)
print(len(test))
With your original code, func
would directly print
the output and then return None
(meaning that test
becomes None
, which you can’t do anything with — when you try to print
it after having called your function, you’ll just see None
).
The above code return
s the string, which is then assigned to test
. The line print(test, num)
prints:
lowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercase 10
and the line print(len(test))
prints the len
(length) of test
:
99
I am trying to print the number of characters that are present in the output my function gives. in this case I’m looking for 90 as "lowercase" 10 times is 90 characters. I’m not really sure what to try, please advise.
num=10
def func(word, add=5, freq=1):
print(word*(freq+add))
test=func("lowercase", num)
print(test, num)
count(test)
When I tried to use the "count" function, I got the below error:
traceback (most recent call last):
File "c:UsersTzvi AryehDocumentspython programs#optional Parameters Tutorial #1.py", line 18, in
count(test)
^^^^^
NameError: name ‘count’ is not defined. Did you mean: ’round’?"
The easiest solution is to modify your function so that it return
s the output instead of print
ing it:
num=10
def func(word, add=5, freq=1):
return word*(freq+add)
test=func("lowercase", num)
print(test, num)
print(len(test))
With your original code, func
would directly print
the output and then return None
(meaning that test
becomes None
, which you can’t do anything with — when you try to print
it after having called your function, you’ll just see None
).
The above code return
s the string, which is then assigned to test
. The line print(test, num)
prints:
lowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercaselowercase 10
and the line print(len(test))
prints the len
(length) of test
:
99