变量未定义它表示想要的是什么时候没有定义?

时间:2014-09-29 02:58:22

标签: python

Traceback (most recent call last):
  File "/Users/mmg2220/Documents/gilliam.a2.v3.py", line 9, in <module>
    if want==1:
NameError: name 'want' is not defined
 
important = int(input("is it important? 1= yes, 2 = no")) 
if important == 1:
    Urgent= int(input("Is it Urgent? 1= yes, 2 = no")) #start of urgent
if Urgent == 1:#start of bestime 
    besttime= int(input("is it the best use of my time to do this myself? 1=yes, 2 = no"))

if important==2: #end of important
    want= int(input("Is it a want? 1= yes, 2 = no")) #start of want   
if want==1:
    print("@Someday/Maybe")

if want == 2:
    print ("trash") #end of want 

if Urgent== 2:
    action=int(input("Is it actionable? 1=yes, 2 = no")) #end of urgent start of action
if bestime== 1:
    minutes= int(input("Will it take more than 15 minutes? 1=yes, 2 = no"))#start of minutes

if besttime== 2:#end of besttime 
    print ("Delegate it")
    print ("Waitingfor")

if action== 1:
    besttime= int(input("is it the best use of my time to do this myself? 1=yes, 2 = no"))
if action== 2:
    reference = int(input("Ia it reference Material? 1=yes, 2=no"))
if reference== 1:
    print ("@file")
if reference== 2:
    print ("Trash")

2 个答案:

答案 0 :(得分:1)

我确定您只想want进行important==2测试。

在Python中,缩进决定了控制。只有当if语句的条件为真时,才会运行比前面的if语句更复杂的代码。代码缩减回与if语句相同的级别始终

在您的情况下,want仅在important==2时定义,而基于want的代码仅在important==2有意义,但您正在运行它无条件地,所以在其他任何情况下,你得到一个NameError

修复很简单:缩进代码,使其成为if应该控制它的一部分:

if important==2: #end of important
    want= int(input("Is it a want? 1= yes, 2 = no")) #start of want   
    if want==1:
        print("@Someday/Maybe")
    if want == 2:
        print ("trash") #end of want

您的代码中有许多其他问题。例如,您始终执行if Urgent==1:,而不是if important==1:的一部分。显然,您需要修复所有这些,而不仅仅是一个,以使您的代码正常工作。

答案 1 :(得分:0)

want仅在important == 2符合以下条件时定义:

if important==2: #end of important
    want= int(input("Is it a want? 1= yes, 2 = no")) #start of want  

作为一种解决方法,您始终可以在脚本开头使用虚拟数字定义需求,例如want=0作为第一行。每次使用变量调用条件时,如果变量尚未以某种方式初始化,则会出现错误。

相关问题