yasmikash
yasmikash

Reputation: 157

How I get a variable defined in for loop outside in the loop? -Python

When I run this Python code I get a NameError. But in this code I'm trying to get a variable defined in a for loop (get) to use in outside of the loop. How can I use this variable (get) outside in for loop?

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)

Upvotes: 1

Views: 436

Answers (2)

spilafis
spilafis

Reputation: 88

Just initialize the variable before the loop. Also the break command was out of the if. Try:

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)   

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361605

Indent the break more.

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

Also what if there are no matching lines? get won't have a value then. Make sure you skip the subsequent code if no lines matched.

Upvotes: 0

Related Questions