I am trying to learn Python. I have browsed through a few tutorials and tried to follow them until they get too complex and I try to find another one to give a different perspective. I am currently trying (and very much enjoying) the very basic "How to Think Like A Computer Scientist" found on openbookproject.net. At the end of each chapter are a few "homework" assignments. I am hung up on one regarding functions. The assignment is: " Fill in the body of the function definition for cat_n_times so that it will print the string, s, n times:"

def cat_n_times(s, n):
    <fill in your code here>

I'm not realclear on how to do this and my attempts resulted in a myriad of errors trying to print variables only defined inside the function and one result that I think was the memory address of cat_n_times. I'm not so much looking for an answer as to why that is the answer. Thanks in advance for helping an old dog learn a new trick (or a whole bag full of them as far as programming goes)

Python makes that easy ...

def cat_n_times(s, n):
    """print string s n times"""
    print s * n

s = 'hello '
n = 3
cat_n_times(s, n)

"""
my result -->
hello hello hello 
"""

Somewhat more traditional ...

def cat_n_times(s, n):
    """print string s n times"""
    for count in range(n):
        print s,

s = 'hello'
n = 3
cat_n_times(s, n)

"""
my result -->
hello hello hello 
"""

Note that the comma adds a space.

Thanks. Easy for you guys is not so much for us newbies. I think I was trying to make it more complicated than it needed to be and also to assign 's' and 'n' inside the function. Thanks again.

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.