NameError:未定义名称'pets'。蟒蛇

时间:2016-04-28 16:13:27

标签: python nameerror

这是我正在使用的代码,但每次我尝试运行它时,我都会在终端中收到此错误:

Traceback (most recent call last):
  File "ex11.py", line 16, in <module>
    if pets == "y":
NameError: name 'pets' is not defined

我的代码:

print "So, how are you doing today?"
emotion = raw_input()

if "Good" in emotion:
    print "Cool! I love when people are \"good\"! It makes me feel all fuzzy inside. ^-^"
    print "Do you have any pets? y/n."
    pets = raw_input()

if pets == "y":
    print "Awesome! I have always wanted a pet! What kind do you have? What does it look like?"
    pet_type = raw_input()

1 个答案:

答案 0 :(得分:3)

您的问题是如果"Good"不在emotion中,则pets未定义。因此,首先定义它:

print "So, how are you doing today?"
emotion = raw_input()
pets = "n" #here

if "Good" in emotion:
    print "Cool! I love when people are \"good\"! It makes me feel all fuzzy inside. ^-^"
    print "Do you have any pets? y/n."
    pets = raw_input()

if pets == "y":
    print "Awesome! I have always wanted a pet! What kind do you have? What does it look like?"
    pet_type = raw_input()