Question

Noob question, but: Say you have a, which equals 90; and b, which equals 100; and you want to return "90 is less than 100" How do you get it to return (not print) "90 is less than 100" rather than "a is less than b"

I've tried using commas but that doesn't do it properly, it returns "(90, "is less than", 100)" I'm guessing you have to convert a and b to strings?

Was it helpful?

Solution

>>> a = 90
>>> b = 100
>>> '{0} is less than {1}'.format(*sorted([a, b]))
'90 is less than 100'

This is much simpler if you already know one is bigger than the other

'{0} is less than {1}'.format(a, b)

You don't need to convert any variables to string when using .format which is what makes it so great!

OTHER TIPS

def main():    
    a = 90
    b = 100
    msg = foo(a,b)
    print msg

def foo(a,b):

    if a < b:
        msg = "a = %d is less than b = %d " % (a,b)
        return (msg)
    elif a> b:
        msg = "b = %d is less than a = %d " % (b,a)
        return (msg)
    else:
        msg = "a = %d is eual to a = %d " % (a,b)
        return (msg) 


if __name__=="__main__": main()

You can either return a tuple like this:

def func():
    # do stuff
    return (90, 'is less than', 100)

Then you can get these by doing something like

value1, text, value2 = func()

value1 will be equal to a 90, text will be equal to 'is less than', and finnally, value2 will be equal to 100

That's one way of doing it. Here's another one returning a dictionnary.

def func():
    # do stuff
    return {'a': 90,
            'text': 'is less than',
            'b': 100}

Then you can use it as so:

ret = func()
print ret['a'] # prints 90
print ret['text'] # prints is less than
print ret['b'] # prints 100

There are many ways of doing something like this. You can even create a specific object for this. It depends on how you want to use your data

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top