Reputation: 23
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
Upvotes: 0
Views: 96
Reputation: 19264
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")
Upvotes: 0
Reputation: 104712
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
Upvotes: 1