I’m doing exercises form Non-Programmers Tutorial For Python2.6 from Wikibooks.
I have this script:
#!/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."
Here is what happened in 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
Same thing happens with C and R.
In Python 2,
inputtakes a string from the user, and evaluates it. So when you enter “S”, it tries to evaluate it, looking for the name “S”, which doesn’t exist.Use
raw_inputinstead ofinput.Yes, this was crazy. It’s fixed in Python 3, where
raw_inputis now namedinput.