2011-04-19 200 views
1

我試圖找出如何打印基於輸入斤或公斤的輸出,這裏是我的代碼:如何磅轉換爲公斤在Python

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 
+0

你的問題是? – 2011-04-19 23:29:32

+0

您應該嘗試使用代碼格式,以便閱讀。只需點擊{}按鈕即可全部選中 – 2011-04-19 23:29:55

+0

問題究竟是什麼? – 2011-04-19 23:30:29

回答

2

當你想返回多個數據項從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] 

請注意,我也修正了自己的pounds->公斤常規:

$ 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通話仍然會塞東西:)我希望你應該刪除這些文件。進一步的改進將把接口代碼與轉換例程分開;你的函數應該可能看起來更像是這樣的:

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服務器軟件,一個圖形用戶界面,一個ncurses的CLI或傳統的終端CLI可以更輕鬆地重複使用您的功能。

+0

真棒!謝謝 – WorkShouldntSuck 2011-04-20 00:26:32

+0

@工作,哦,是的,這種分離_also_可以更輕鬆地_write單元測試_爲您的函數。 :D強烈推薦。 – sarnold 2011-04-20 00:59:37

1

一個稍微複雜一些,但更加靈活的版本:

units = { 
    'kg':   ('weight', 1.), 
    'kilo':  ('weight', 1.), 
    'kilogram': ('weight', 1.), 
    'lb':   ('weight', 2.204), 
    'pound':  ('weight', 2.204), 
    'tonne':  ('weight', 0.001), 
    'carat':  ('weight', 5000.), 
    'gram':  ('weight', 1000.), 
    'dram':  ('weight', 564.4), 
    'ounce':  ('weight', 35.27), 
    'grain':  ('weight', 15430.), 
    'm':   ('distance', 1.), 
    'meter':  ('distance', 1.), 
    'kilometer': ('distance', 0.001), 
    'km':   ('distance', 0.001), 
    'centimeter': ('distance', 100.), 
    'cm':   ('distance', 100.), 
    'meter':  ('distance', 1.), 
    'mile':  ('distance', 0.0006214), 
    'chain':  ('distance', 0.04971), 
    'furlong':  ('distance', 0.004971), 
    'league':  ('distance', 0.0002071), 
    'foot':  ('distance', 3.281), 
    'feet':  ('distance', 3.281),  # irregular plural - must be explicitly specified! 
    'inch':  ('distance', 39.37) 
} 

def getUnit(unit_name): 
    if unit_name in units: 
     return units[unit_name] 
    # recognize regular plural forms 
    elif unit_name.endswith('es') and unit_name[:-2] in units: 
     return units[unit_name[:-2]] 
    elif unit_name.endswith('s') and unit_name[:-1] in units: 
     return units[unit_name[:-1]] 
    # not found? 
    else: 
     raise ValueError("Unrecognized unit '{0}'".format(unit_name)) 

def convert(amt, from_unit, to_unit): 
    typeA, numA = getUnit(from_unit) 
    typeB, numB = getUnit(to_unit) 

    if typeA==typeB: 
     return amt * numB/numA 
    else: 
     raise ValueError("Units are of different types ('{0}' and '{1}')".format(typeA, typeB)) 

def conversion(s): 
    """ 
    Do unit conversion 

    Accepts a string of the form 
     "(number) (unitA) [to] (unitB)" 

    If unitA and unitB are of the same unit-type, returns the converted value. 
    """ 
    s = s.strip().lower().split() 
    if len(s) not in (3, 4): 
     raise ValueError("Argument string has wrong number of words (should be three or four)") 
    try: 
     amt = float(s[0]) 
    except ValueError: 
     raise ValueError("Argument string must start with a number") 
    from_unit = s[1] 
    to_unit = s[-1] 
    return convert(amt, from_unit, to_unit) 

def tryAgain(): 
    s = raw_input('Try again (Y/n)? ').strip().lower() 
    return 'yes'.startswith(s) 

def main(): 
    while True: 
     s = raw_input("Convert what? (ex: 10 meters to feet) ") 
     try: 
      print(": {0}".format(conversion(s))) 
     except ValueError, v: 
      print v 
     if not tryAgain(): 
      break 

if __name__=="__main__": 
    main() 

這可以解決像「10噸至盎司」或「30個弗隆到腳」的問題。

建議進一步的添加:

  1. 添加納米作爲距離的單元(並對其進行測試)。

  2. 添加短噸和石塊作爲重量單位(並測試它們)。

  3. 以公升,品脫和桶爲單位(並測試它們)。

相關問題