2013-04-27 28 views
-2

幾年前,我在這裏找到了一個用於長度和重量轉換的轉換程序。我的一位朋友最近開始了一個他需要這段代碼的項目,但該項目要求他使用最新版本的Python。我答應過他,我會盡可能地幫助他,但是沒有用python編碼多年,我真的不能做太多。我希望你們能幫忙。每當我運行它,我得到以下兩個錯誤:在Python中製作轉換程序使用最新版本的python

Traceback (most recent call last): 
File "C:\Users\Tiberius\Documents\Konvertering.py", line 75, in <module> 
main() 
File "C:\Users\Tiberius\Documents\Konvertering.py", line 66, in main 
s = raw_input("konverter hvad? (ex: 10 meter til fod) ") 
NameError: global name 'raw_input' is not defined 

該文本是在丹麥btw。代碼如下位置:

units = {'kg':   ('vægt', 1.), 
'kilo':  ('vægt', 1.), 
'kilogram': ('vægt', 1.), 
'lbs':   ('vægt', 2.204), 
'pund':  ('vægt', 2.204), 
'ton':  ('vægt', 0.001), 
'gram':  ('vægt', 1000.), 
'ounce':  ('vægt', 35.27), 
'm':   ('afstand', 1.), 
'meter':  ('afstand', 1.), 
'kilometer': ('afstand', 0.001), 
'km':   ('afstand', 0.001), 
'centimeter': ('afstand', 100.), 
'cm':   ('afstand', 100.), 
'meter':  ('afstand', 1.), 
'mil':  ('afstand', 0.0006214), 
'furlong':  ('afstand', 0.004971), 
'league':  ('afstand', 0.0002071), 
'fod':  ('afstand', 3.281), 
'fod':  ('afstand', 3.281), 
'tomme':  ('afstand', 39.37)} 

def getUnit(unit_name): 
    if unit_name in units: 
     return units[unit_name] 
    else: 
     raise ValueError("ikke genkendt enhed '{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("enheder er af forskellige kategori ('{0}' and '{1}')".format(typeA, typeB)) 

def conversion(s): 
    """ 
    Fortag enhedskonvertering 

    Der accepteres en string i forment 
    "(tal) (enhedA) [til] (enhedB)" 

    Hvis enhed A og enhed B er af den samme type, vend tilbage med svaret . 
    """ 
    s = s.strip().lower().split() 
    if len(s) not in (3, 4): 
     raise ValueError("Argument string har et forkert antal ord (skal være mellem tre eller fire)") 
    try: 
     amt = float(s[0]) 
    except ValueError: 
     raise ValueError("argument string skal starte med et tal") 
    from_unit = s[1] 
    to_unit = s[-1] 
    return convert(amt, from_unit, to_unit) 

def tryAgain(): 
    s = raw_input('prøv igen? (Y/n)? ').strip().lower() 
    return 'yes'.startswith(s) 

def main(): 
    while True: 
     s = raw_input("konverter hvad? (ex: 10 meter til fod) ") 
     try: 
      print(": {0}".format(conversion(s))) 
     except ValueError as v: 
      print (v) 
     if not tryAgain(): 
      break 

if __name__=="__main__": 
    main() 
+1

看起來它正在從東西'<= 2.7.3'轉換成'3x',因爲它們除去'raw_input'。也許你可以嘗試使用python擁有的'2to3'模塊。 – 2013-04-27 20:23:21

回答

5

raw_input()更名爲input()在Python 3

3

2to3工具可以幫助你的Python 2的代碼轉換成Python就可以了3

相關問題