Python: NameError 名称“[input]”未定义

3

我正在尝试制作一个简单的工具,用于将英寸转换为厘米,但现在卡在了如何接受用户输入(“y”或“n”)以决定是否进行另一次转换或终止程序上。这是我的代码:

import time

def intro():
    print "Welcome! This program will convert inches to centimeters for you.\n"
    convert()

def convert():
    input_cm = input(("Inches: "))
    inches_conv = input_cm * 2.54
    print "Centimeters: %f\n" % inches_conv
    time.sleep(3)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        convert()
    elif restart == 'n':
        end_fast()
    else:
        print "I didn't quite understand that answer. Terminating."
        end_slow()

def end_fast():
    print "This program will close in 5 seconds."
    time.sleep(5)

def end_slow():
    print "This program will close in 30 seconds."
    time.sleep(30)

intro()

结果如下:

追溯(最近的调用): 文件“C:\Users\Sam\Programming\Python\the hard way\ex5.4.py”,第29行, intro() 文件“C:\Users\Sam\Programming\Python\the hard way\ex5.4.py”,第5行, intro() 文件“C:\Users\Sam\Programming\Python\the hard way\ex5.4.py”,第12行, restart = str(input("您是否希望进行另一次转换?[y]是或[n]否?\n")) 文件“”,第1行, NameError: name 'y' is not defined

需要帮助请告知。


1
使用 raw_input 而不是 input - Ashwini Chaudhary
@AshwiniChaudhary 那是一个答案,顺便说一下 :) - alecxe
那确实解决了问题,Ashwini。非常感谢! - ClutchHunter
我做了,只是如果我没记错的话,它是在时间限制之内完成的。我已经将其加为书签,以便回来接受它 :-) - ClutchHunter
1个回答

6

不要使用input,尝试使用raw_input代替:

替换为:

restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))

关于:

restart = raw_input("Do you wish to make another conversion? [y]Yes or [n]no: ")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接