while循环在Python中是否有局部变量?

时间:2015-06-10 17:24:23

标签: python

我试图像这样使用while语句:

    o = 0
    while o == 0:
        try:
            n = int(raw_input("Which number do you want to begin with?"))
            o = 1
        except:
            o = 0
            print "Please use a valid number."

但是,当我稍后尝试使用变量n时,它给出了“在赋值之前引用的局部变量'n''UnboundLocalError。这意味着n不能被识别为我正在使用的def中的变量,因为它只是存在于while语句中?这可能吗? 整个代码:

import time
from sys import argv
import os
os.system("cls")

print "Welcome to Number counter 2.0!"
a = True
def program():
    global a
    if a == False:
        os.system("cls")
        o = 0
        while o == 0:
            try:
                n = int(raw_input("Which number do you want to begin with?"))
                o = 1
            except:
                o = 0
                print "Please use a valid number."
if n == "/historyKeep false":
    if a == False:
        print "Command historyKeep is already set to false."
    else:
        a = False
        print "Command set successfully."
elif n == "/historyKeep true":
    if a == True:
        print "Command historyKeep is already set to true."
    else:
        a = True
        print "Command set successfully."
if n == "/historyKeep false":
    n = raw_input("Which number do you want to begin with?")    
elif n == "/historyKeep true":
    n = raw_input("Which number do you want to begin with?")    

d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
    print n
    time.sleep(d)
    n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
    os.system("cls")
    print "Exiting."
    time.sleep(0.5)
    os.system("cls")
    print "Exiting.."
    time.sleep(0.5)
    os.system("cls")
    print "Exiting..."
    time.sleep(0.5)
    os.system("cls")
    exit(0)
elif end_q == "r":
    program()

program()

3 个答案:

答案 0 :(得分:3)

您在开头设置a = True。然后,您测试a == False是否只设置n。但是你测试了n == "/history...。此时尚未设置n

在使用之前,您需要确保已分配n。仅仅在没有采取的分支中提及它是不够的。

答案 1 :(得分:1)

n未在您尝试使用它来解决此问题的范围中定义,在while循环之外定义它以及while循环所在的if语句:

global a
n = 0

然后,当您询问用户开始的号码时,该值将替换0,您应该好好去。而不是声明global a,为什么不只为program()函数创建一个输入参数?

答案 2 :(得分:0)

为了确保首先在循环之外声明n

n = None
while True:
    try:
        n = int(raw_input("Text..."))
        break
    except:
        print("Please enter a valid number!")

注意:通常,您可以使用break退出循环。这是因为你的方法需要一个额外的变量,它使用更多的内存(不多,但如果你继续这样做,它会叠加)。