当我运行这个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)
答案 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
将没有值。如果没有匹配的行,请确保跳过后续代码。