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
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
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")
Related
I'm a beginner trying to do a short learning exercise where I repeatedly prompt users for their name and save those names to guest_book.txt, each name in a new line. So far, while loops are always giving me trouble to get them working properly.
In this case, the program ends when I enter the first name, here's the code:
"""Prompt users for their names & store their responses"""
print("Enter 'q' to quit at any time.")
name = ''
while True:
if name.lower() != 'q':
"""Get and store name in guestbook text file"""
name = input("Can you tell me your name?\n")
with open('guest_book.txt', 'w') as guest:
guest.write(name.title().strip(), "\n")
"""Print greeting message with user's name"""
print(f"Well hello there, {name.title()}")
continue
else:
break
It runs perfectly when I omit the with open() block.
In a more pythonic way:
with open('guest_book.txt', 'w') as guest:
while True:
# Prompt users for their names & store their responses
name = input("Can you tell me your name?\n")
if name.lower() == 'q':
break
# Get and store name in guestbook text file
guest.write(f"{name.title().strip()}\n")
# Print greeting message with user's name
print(f"Well hello there, {name.title()}")
Can you tell me your name?
Louis
Well hello there, Louis
Can you tell me your name?
Paul
Well hello there, Paul
Can you tell me your name?
Alex
Well hello there, Alex
Can you tell me your name?
q
>>> %cat guest_book.txt
Louis
Paul
Alex
First try to read an error which was shown by Python.
TypeError: write() takes exactly one argument (2 given)
Next you answer a name after if state. I make some changes with your code and move open to begin of code (and thanks to Corralien for review):
print("Enter 'q' to quit at any time.")
with open('guest_book.txt', 'w') as file:
while True:
name = input("Can you tell me your name?").title().strip()
if name.lower() == 'q':
break
if name:
file.write('{}\n'.format(name))
print('Well hello there, {}'.format(name))
I am a total amateur when it comes to python and I have came across an issue:
if input() == existingUsername:
print('Sorry, that username is taken, please try again:')
However, I need to access exisingUsername before it is declared, because I've defined it at the bottom of my code. I know you can do this in javascript with the let variable, but how can I do it in python?:
let existingUsername;
//code
existingUsername = 'name'
You can't use a variable before declaring it.
You could however use an empty string:
existingUsername = ""
# .
# .
# the rest of your program
# .
# .
username = input()
if username == existingUsername:
print('Sorry, that username is taken, please try again:')
else:
# assign new username here
existingUsername = username
This is further to an issue I asked about on here yesterday What is the best way to validate user input against the contents of a list?). I got a good suggestion using a function like so:
getuser = input("Please enter your username :")
print("1. render_device")
print("2. audit_device")
askuser = input("Would you like to render_device or audit_device? : ")
def verify_input(sites_set):
get_site_name = input("Please enter the site name you'd like to render :")
if get_site_name in sites_set:
print('Proceed')
return
else:
print('Not in either list, please enter a valid site')
verify_input(sites_set)
if askuser == "1":
sites_2017 = ["bob", "joe", "charlie"]
sites_2018 = ["sarah", "kelly", "christine"]
verify_input(set(sites_2017 + sites_2018))
This works correctly within the function and when it is called. However, the issue is that I need get_site_name as a global variable since its input is referenced later in the script (not in a function). When I make get_site_name global, the function can reference it and works correctly when a valid site is input, but when an invalid site is input it just keeps looping the "Not in either list" error over and over, probably because the raw_input in the get_site_name variable isn't defined locally.
What would be the best way to remedy this?
What about:
def verify_input(sites_set):
while get_site_name not in sites_set:
get_site_name = input("Please enter the site name you'd like to render :")
print('Proceed')
return
I am new to programming and am wondering if this is possible. I am trying to create a password protected script, where the password is entered once and then required to progress the script the next time the script is opened. I am storing and encrypting the password in a file, and then checking to see if the file exists the next time the script is opened. The problem I am running into is checking to see if the passwords match, since the original password is in a function as a local variable.
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = encrypt(pw, 10) #encodes the string with a key in a seperate encrypt function
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
#I can not check pwCheck == pw since pw is a local var.
#progression of script here
else:
createFile()
I know that it is considered bad for to make a local variable global. Is there a way to restructure what I have so far to make this work? As I wrote this, I think I may have came up with a possible solution but I do not have time to test it now. Do I run the same encrypt function with the same key for pwCheck and then check if it is == to the first line of PW.txt? Is that correct and/or are there other solutions?
Thank you.
Using Windows, Python 3.4
Instead of "encrypt", perhaps use a 1-way hash.. Then, you can hash the subsequently entered password and check it versus the hash stored in the file... Something like:
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = sha.new(pw).digest
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
previous = open('PW.txt', 'r')
prevPass = previous.read()
hashed = sha.new(pwCheck).digest()
if (hashed==prevPass):
#progression of script here
else:
createFile()
I really hope that this is just an exercise, because if you care about security, you should be using some other authentication mechanism to gate access. Most obviously, unix permissions, and sudo to gate access.
Assuming it is an exercise only, simply have a function which checks the input against the file. Something like:
def doAuth():
isAuthed = getPassInput() == getPassFromFile()
if isAuthed:
return True
else:
raise HellNoException("Passwords differ")
I need help!!
I've been struggling with this problem and I cannot seem to solve it.
def itemName():
flag = True
while flag == True:
try:
name = input('What would You like to name it? \n')
Input = str(Input)
print(name)
if name.upper() == ('BOAT') or name.upper() == ('CASUALTY'):
flag = False
else:
raise Exception
except:
print('Boat or Casualty only')
return name
name = itemName()
print(name)
This code will not pass when run. This works in the normal python IDLE but not canopy. Also the print statement only outputs if the input is an integer. I'm stumped, any ideas?
This is python 3 code. Canopy uses Python 2.7
The input function differs between these versions.
In python 2.7, the equivalent is raw_input