菜鸟问题,但是:假设你有一个,等于 90;b,等于 100;你想返回“90 小于 100”你如何让它返回(不打印)“90 小于 100”而不是“a 小于 b”
我试过使用逗号,但这样做不正确,它返回“(90,”小于“,100)”我猜你必须将a和b转换为字符串?
>>> a = 90
>>> b = 100
>>> '{0} is less than {1}'.format(*sorted([a, b]))
'90 is less than 100'
如果您已经知道一个比另一个大,这会简单得多
'{0} is less than {1}'.format(a, b)
使用时您不需要将任何变量转换为字符串,.format
这就是它如此出色的原因!
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()
您可以像这样返回一个元组:
def func():
# do stuff
return (90, 'is less than', 100)
然后你可以通过做类似的事情来获得这些
value1, text, value2 = func()
value1 将等于 90,text 将等于“小于”,最后 value2 将等于 100
这是一种方法。这是另一个返回字典。
def func():
# do stuff
return {'a': 90,
'text': 'is less than',
'b': 100}
然后你可以这样使用它:
ret = func()
print ret['a'] # prints 90
print ret['text'] # prints is less than
print ret['b'] # prints 100
有很多方法可以做这样的事情。你甚至可以为此创建一个特定的对象。这取决于您希望如何使用您的数据