0

I am trying to print the user input of a package name. I have the following code.

packageList = []
package = input("Enter name: ")
while package == '' :
    print("Package name cannot be blank")
    packagename = input("Enter name: ")
    packageList.append(packageName)

print ((packageName) + "added")

I'm not sure what I'm doing wrong. An error is being displayed: UnboundLocalError: local variable 'packageName' referenced before assignment

3
  • 2
    You never made a packageName variable. Perhaps you meant for package and packageName to be the same variable, and mixed up which name you were using. Commented May 14, 2014 at 1:41
  • 1
    Also, packageList.append(packageName) should definitely not be in that loop. Commented May 14, 2014 at 1:43
  • Thank you!!! That was so simple. I've been trying for ages! Commented May 14, 2014 at 1:45

2 Answers 2

1

Your code is giving you errors because you're mixing up the use of variables package and packageName, when it looks like you should be using the same variable in both places. The code in aj8uppal's answer corrects most of this (by replacing most references to both variables with packagename), but he never clearly describes that this is the problem (and he still leaves one reference to package in the while condition).

Here's some actually fixed code:

packageList = []
package = input("Enter name: ")

while package == '' :
    print("Package name cannot be blank")
    package = input("Enter name: ")               # assign to package variable here

packageList.append(package)                       # unindent, and use package again

print ((package) + "added")                       # use package rather than packageName
Sign up to request clarification or add additional context in comments.

Comments

0

Your packageList.append(packageName) should not be in the while loop. Your while loop just makes sure the input is not blank, so we don't want to append it.

What you are doing is not raising the error, so packageName doesn't exist. Therefore, you are printing an uncalled variable.

Also, you call package = input(...), but if there is an error, you call packagename = input(...). You probably want to change that.

Here is your edited code:

packageList = []
packagename = input("Enter name: ")
while package name == '' :
    print("Package name cannot be blank")
    packagename = input("Enter name: ")

packageList.append(packageName)
print ((packageName) + "added")

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.