为什么我在这个脚本中得到一个NameError?

San*_*mar 0 python python-2.7

我正在从Wikibooks进行非程序员教程Python2.6的练习.

我有这个脚本:

#!/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."
Run Code Online (Sandbox Code Playgroud)

以下是shell中发生的事情:

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
Run Code Online (Sandbox Code Playgroud)

同样的事情发生在CR.

Ned*_*der 6

在Python 2中,input从用户获取一个字符串,并对其进行评估.因此,当您输入"S"时,它会尝试对其进行评估,查找名称"S",该名称不存在.

raw_input而不是input.

是的,这太疯狂了.它已在Python 3中修复,raw_input现在命名为input.