A string and an integer to appear in tuple (python 2.7)

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 12 20:43:54 EDT 2013


On 13 March 2013 00:21, Jiewei Huang <jiewei24 at gmail.com> wrote:
> Hi all,
>
> I'm currently stuck at this question on
>
> Writing a function len_str that takes a string as an argument and returns a pair consisting of the length of the string and the string itself.
>
> Example: len_str('Meaning of life') should return the tuple (15, 'Meaning of life').
>
>
> I can only think of this :
>
> len_str = ('welcome to life' )
>
> print (len(len_str,), len_str)
>
>
> However that not an correct answer I need to make a def len_str but I can't seen to get it right.

Perhaps an example will help. Let's say we have a variable called x
that we initialise with

x = 2

Here's a line of code that prints 2*x:

print(2 * x)

This will print out 4 but that's not what you want. Here's a function
that prints its argument multiplied by 2:

def double(y):
    print(2 * y)

Now we have a function and we can call it with

double(x)

so that it prints 4. Again, though, you didn't want to print it. You
wanted to *return* the value. So here's a function that *returns* 2
times its argument:

def double(x):
    return 2 * x

Now if we do

z = double(x)

z will have the value 4. You can check this with

print(z)

Try the code above and see if you can apply the same principles to your problem.


Oscar



More information about the Python-list mailing list