英文:
How do I get a function's output characters to be automatically counted in python?
问题
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:\Users\Tzvi Aryeh\Documents\python programs\#optional Parameters Tutorial #1.py", line 18, in <module>
count(test)
^^^^^
NameError: name 'count' is not defined. Did you mean: 'round'?
英文:
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:\Users\Tzvi Aryeh\Documents\python programs#optional Parameters Tutorial #1.py", line 18, in <module>
count(test)
^^^^^
NameError: name 'count' is not defined. Did you mean: 'round'?"
答案1
得分: 0
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论