2012-07-26 74 views
0

我在做練習Non-Programmers Tutorial For Python2.6Wikibooks爲什麼我在這個腳本中得到一個NameError?

我有這樣的腳本:

#!/usr/bin/env python 
#-*- coding:utf-8 -*- 

print("Program to calculate the area of square, rectangle and circle.") 

def areaOfSquare(): 
    side = input("What is the length of one side of the square? ") 
    area = side ** 2 
    return area 

def areaOfRectangle(): 
    width = input("What is the width of the rectangle? ") 
    height = input("What is the height of the rectangle? ") 
    area = 2*width+2*height 
    return area 

def areaOfCircle(): 
    radius = input("What is the radius of the circle? ") 
    area = 3.14 * radius ** 2 
    return area 

geometry = input("What do you wan to calculate the area of? [S/C/R] ") 

str(geometry) 

if geometry == "S": 
    areaOfSquare() 
elif geometry == "R": 
    areaOfRectangle() 
elif geometry == "C": 
    areaOfCircle() 
else: 
    print "Press S for square, C for circle and R for rectangle." 

這裏是殼發生了什麼:

prompt$ python script.py 
Program to calculate the area of square, rectangle and circle. 
What do you wan to calculate the area of? [S/C/R] S 
Traceback (most recent call last): 
    File "allarea.py", line 22, in <module> 
    geometry = input("What do you wan to calculate the area of? [S/C/R]") 
    File "<string>", line 1, in <module> 
NameError: name 'S' is not defined 

同樣的事情發生與CR

回答

6

在Python 2中,input從用戶處獲取一個字符串並對其進行評估。所以當你輸入「S」時,它會嘗試評估它,尋找不存在的名字「S」。使用代替input

是的,這太瘋狂了。它已在Python 3中修復,其中raw_input現在被命名爲input

+0

可能應該提到,由於'raw_input'返回一個字符串,不同'areaOf'函數中的其他輸入將需要'float(raw_input('question?'))'或者一些變體,如果輸入'到'raw_input'的變化無處不在。 – DSM 2012-07-26 01:39:23