1

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)
1
  • You don't need to anything extra. Maybe nothing ever gets assigned to it. Commented Feb 20, 2017 at 3:09

2 Answers 2

1

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)   
Sign up to request clarification or add additional context in comments.

2 Comments

It worked. But I've found some errors in my script. Anyway thanks :)
Great! Please don't forget to mark the answer as the right answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.