我试图弄清楚如何根据输入打印磅或公斤的输出,这是我的代码:
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
elif answer == "pounds":
return amount / 1.45
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
最佳答案
当你想从Python中的函数返回多个数据项时,可以返回 tuple两个数据项:
return (amount * 2.2, "pounds")
或
return (amount / 2.2, "kilograms")
稍微修改你的函数:
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]
请注意,我还修复了您的磅->公斤例程:
$ 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
那些return 0
调用仍然会把事情搞砸:)我希望你应该删除它们。进一步的改进是将接口(interface)代码与转换例程分开;你的函数应该可能看起来更像这样:
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
这种分离使得您可以更轻松地在 Web 服务器软件、GUI、ncurses CLI 或普通旧终端 CLI 中重用功能。
关于python - 如何在Python中将磅转换为千克,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723919/