<p>当您想从Python中的函数返回多个数据项时,可以返回一个包含两个数据项的<a href="http://docs.python.org/library/stdtypes.html#typesseq" rel="nofollow">tuple</a>:</p>
<pre><code>return (amount * 2.2, "pounds")
</code></pre>
<p>或者</p>
<pre><code>return (amount / 2.2, "kilograms")
</code></pre>
<p>稍微修改您的函数:</p>
<pre><code>def conversion():
amount = input("Please specify the amount: ")
if type(amount) is int:
print "derp"
answer = raw_input("Please choose between converting FROM kilograms/pounds: ")
if answer == "kilograms":
return (amount * 2.2, "pounds")
elif answer == "pounds":
return (amount / 2.2, "kilograms")
else:
print "Please choose between kilograms and pounds."
restart = raw_input("Try again? ")
if restart == "yes":
conversion()
return 0
elif restart == "y":
conversion()
return 0
else:
print "Okay, bye."
return
finalresult = conversion()
print "the final result is: ", finalresult[0], finalresult[1]
</code></pre>
<p>请注意,我还修正了您的体重-公斤例行程序:</p>
<pre><code>$ python /tmp/convert.py
Please specify the amount: 10
derp
Please choose between converting FROM kilograms/pounds: kilograms
the final result is: 22.0 pounds
$ python /tmp/convert.py
Please specify the amount: 22
derp
Please choose between converting FROM kilograms/pounds: pounds
the final result is: 10.0 kilograms
</code></pre>
<p>那些<code>return 0</code>调用仍然会把事情搞砸:)我希望您应该删除它们。进一步的改进是将接口代码与转换例程分离;您的函数应该更像这样:</p>
<pre><code>def from_kilograms(kilos):
return kilos * 2.2
def from_pounds(pounds):
return pounds / 2.2
def conversation():
while true:
ans = raw_input("kg or lb: ")
num = raw_input("mass: ")
if ans == "kg"
print from_kilograms(int(num)), " pounds"
elsif ans == "lb"
print from_pounds(int(num)), " kilograms"
else
print "bye!"
return
</code></pre>
<p>这种分离使得在web服务器软件、GUI、ncurses CLI或普通的旧终端CLI中重用功能更加容易。</p>