how could i print the length of a parameter?.. like def length(word)
gives the output "word 4"?.. I have no clue of what to do?

def length():
len=length()

Dani AI

Generated

A few practical additions to what and already showed: accept any number of parameters, avoid common mistakes (like infinite recursion or shadowing built-ins), and make the function robust when callers pass non-sequence values (ints, None, custom objects).

The example below returns lengths so the result can be tested or formatted elsewhere; it also lets you choose a fallback for objects that don't implement __len__:

def param_lengths(*items, fallback=None):
    """
    Return list of (item, length or None).
    If an item has no length:
      - fallback=None -> length is None
      - fallback='str' -> use len(str(item))
      - fallback=callable -> call fallback(item) to compute a length
    """
    out = []
    for item in items:
        try:
            l = len(item)
        except TypeError:
            if fallback == 'str':
                l = len(str(item))
            elif callable(fallback):
                l = fallback(item)
            else:
                l = None
        out.append((item, l))
    return out

Use the returned tuples to print or log in whatever format you prefer — for modern Python, f-strings are concise; for portability use .format() or % if you must support very old interpreters.

Two quick cautions:

  • The snippet posted by (def length(): len = length()) both shadows the built-in name and recursively calls itself — that will crash. Don’t assign to len and be sure your function accepts an argument when you intend to process one.
  • len() works for sequences and collections; passing an int raises TypeError. If you want digit count, convert to string first or supply a custom fallback.

For reference on behavior and exceptions from len(), see the Python docs: len() documentation.

Recommended Answers

All 4 Replies

You need to study up on functions a little, for instance see:
http://www.daniweb.com/forums/post104853.html#post104853
Again, you can use a formatted string to show the result ...

def length(word):
    print( "%s %d" % (word, len(word)) )

# test the function
# here you use the string "python" as argument/parameter word
length("python")  # python 6

The nice thing about using % formatting is that it works with Python2 and Python3 versions. Look at %s as a placeholder for string word and %d as a placeholder for the integer result of len(word).

thx for the help but how could i print the length of whatever the parameters are?.. like length("tree", "computer") and it prints out the string the with length?... this is what i dnt get

thx for the help but how could i print the length of whatever the parameters are?.. like length("tree", "computer") and it prints out the string the with length?... this is what i dnt get

how could i print the length of whatever the parameters are

Well, if you tried the example given by vegaseat, it gave you the length of parameters passed to the function 'length'. If that isn't what you are looking for, perhaps just re-phrase your question a little.

If all you are looking for is to get the length of a string the len('your string') will do the trick.

prints out the string the with length

Just take a closer look at the example given by Vegaseat. That is exactly what his function did. You give it a string, it prints the string and the length of the string.

thx for the help but how could i print the length of whatever the parameters are?.. like length("tree", "computer") and it prints out the string the with length?... this is what i dnt get

That changes the original scope just a minor tad ...

def length(*args):
    for arg in args:
        print( "%s %d" % (arg, len(arg)) )

# test the function with a single argument/parameter
length("python")

print( '-'*15 )

# test the function with multiple arguments/parameters
length("hill", "cat", "mouse")

"""my result -->
python 6
---------------
hill 4
cat 3
mouse 5
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.