我如何在循环外部获得for循环中定义的变量? -蟒蛇

时间:2017-02-20 03:05:11

标签: python

当我运行这个Python代码时,我得到一个NameError。但是在这段代码中,我试图在for循环(get)中定义一个变量,以便在循环外部使用。如何在for循环中使用此变量(get)

file = open("f:/py/price.txt", "r")

valRange = 0
cal = 0
totalCst = 0
itmCnt = 0
while (valRange < 10):
     idNumber = int(input("Enter Id number: "))
     for line in file:
          if line.startswith(str(idNumber)):
               get = line.split("=")[1]
          break
     quantity = int(input("Enter qantity: "))
     cal = quantity * int(get)
     totalCst += cal
     itmCnt += quantity

print (totalCst)

2 个答案:

答案 0 :(得分:1)

只需在循环之前初始化变量。 break命令也在if之外。 尝试:

file = open("f:/py/price.txt", "r")

valRange = 0
cal = 0
totalCst = 0
itmCnt = 0
while (valRange < 10):
     idNumber = int(input("Enter Id number: "))
     get = 0
     for line in file:
          if line.startswith(str(idNumber)):
               get = line.split("=")[1]
               break
     quantity = int(input("Enter qantity: "))
     cal = quantity * int(get)
     totalCst += cal
     itmCnt += quantity

print (totalCst)   

答案 1 :(得分:0)

缩进break以上。

 for line in file:
      if line.startswith(str(idNumber)):
           get = line.split("=")[1]
           break

如果没有匹配的线路呢? get将没有值。如果没有匹配的行,请确保跳过后续代码。