Python Amateur - 'Greeting program' - 'Referenced before assignment error' - python

Like I said in my previous question, I'm a python amateur. I've made a couple silly mistakes. I'm attempting to make a highly simple greeting program using Python 3.4 however I have encountered an error. The error I have is:
UnboundLocalError: local variable 'lastNameFunction' referenced before assignment
Here's my code (I know I probably don't need to post it all, but there isn't much of it):
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()
I'd appreciate any help and advice! Please take into consideration I am really new to this stuff. I'm also not quite sure on having a function inside of a function, but I thought it would be a fix so that the 'firstName' was available when entering the 'lastName'.
Thanks in advance! :)

You need to move the lastNameFunction declaration somewhere before you call it using lastNameFunction(), e.g.:
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
if __name__ == '__main__':
main()
You can also move it outside the main function, but you will then need to pass the firstName in using the function arguments:
def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
def main():
...
lastNameFunction(firstName)
...

Move your lastNameFunction to somewhere before the call. Ideally, you would place this above the main function.
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...

The problem is you called lastNameFunction() before you defined it in the while loop. Try defining the function outside the while loop.

The organisation of the whole program seems a little bit off.
Imports usually go at the top of the module.
Functions defined in functions are usually just for closures, which you a) don't need here and b) might be a bit advanced for your current experience level.
Recursive calls like your calling main() from within main() are wrong. When you adopt that style of control flow instead of a loop, you will eventually run into limitations of recursive calls (→ RuntimeError). You already have the necessary loop, so simply leaving out the elif branch already asks the user again for the first name.
running isn't used anywhere, so you can remove it and just use while True:.
I would move asking the user for ”anything” + the question if the input was correct into its own function:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()

Related

I am trying to update my program to have some return values to make it more testable. Why is the one named other not returned usable in main?

I receive a NameError: name 'other' is not defined. Could someone give me an example and reasoning to point me in the right direction to help me out (so i don't screw up when adding return values to the rest of my program). I thought i understood them that's why I know i need help to get a better understanding. I almost forgot to mention i am entering a number to trigger the else clause when i get the error message regarding main code.
def yes_no(y_n):
other = 'invalid response'
if y_n == 'n':
index_person(address_dict)
elif y_n == 'y':
add_person()
else:
return other
def main():
#other = 'Invalid response'
while True:
#Hmmm..would the user like to add a new person the the address book or index it?
#Loop the address program until break.
try:
user_answer = input('Would you like to add a new person to the address book? y/n \n - ')
yes_no(user_answer)
if user_answer not in ['y','n']:
print(other)

How to perform three different operations and import the module to another python script?

My aim:
To create a python Modules with 3 functions:
Sample input1: bob
output:
Yes it is a palindrome
No. of vowels:1
Frequency of letters:b-2,o-1
=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
ch = input("Enter a character: ")
if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
In a new file I am giving :
import test
def main():
while True:
word = input("enter a word")
test.isPalindrome(word))
test.count_the_vowels(word))
if __name__ == "__main__":
main()
If I call my module in another file, it automatically does all the functions. But I want to give input(name) in this new module and check the output for it.But this is asking input again since name is present before def function in the other file. How to overcome this?
I am new to coding.Please be as elaborate as possible.Thanks in advance.
If you're question is "how to ask for the name only once and pass it to both function", the answer is simple: in your main.py script (or test.py or however you named it), add this:
import yourmodule # where you defined your functions
def main():
while True:
word = input("enter a word (ctrl+C to quit) > ")
yourmodule.isPalindrome(word)
yourmodule.count_the_vowels(word)
# etc
if __name__ == "__main__":
main()
Now note that your assignment doesn't say you have to do this - it says:
Import the module in another python script and test the functions by passing appropriate inputs.
Here, "passing appropriate inputs" can also be understood as having a harcoded list of words and calling your functions with those names... IOW, a unit test.
After trying several times to explain in the comments here is a brief example. so make a file with your functions. then in your other file import your funcs file then ask user for name and pass it to the funcs. This is just an example of how to define functions in one file and then call them from another. you probably want to look at your funcs as they should probably return values rather then just print stuff otherwise your calling file wont be able to validate the function since it will receive nothing back.
MyFuncs.py
def hello(name):
print(f"hello {name}")
def goodbye(name):
print(f"goodbye {name}")
stackoverflow.py
import MyFuncs
name = input("Name: ")
MyFuncs.hello(name)
MyFuncs.goodbye(name)
**OUTPUT: **when running the stackoverflow.py script
Name: Chris
hello Chris
goodbye Chris

How to use a function's if statement to use info from another function?

So I'm designing a sign-in AI, and I want it to work so that the admin name is Shawn. Here is my issue:
The program starts with the interface -
def interface():
username = input('Hello traveler, what is your name? ')
lowerUsername = username.lower()
print()
print()
if lowerUsername == 'megan':
print()
print('So you are the one Shawn has told me so much about? You are looking beautiful today my dear ☺️🌷')
elif lowerUsername == 'shawn':
OfficialSignInEdit()
So you can see at the end that if the user inputs that their name is 'shawn' at sign-in, it calls on the OfficialSignInEdit function, which is the admin sign in. It looks like this:
def OfficialSignInEdit():
print()
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again 🙂')
else:
print()
res1 = input('Incorrect password, try again? (Yes/No)')
lowres1 = res1.lower()
if lowres1 == 'yes':
print()
print()
OfficialSignIn()
elif lowres1 == 'no':
print()
print()
interface()
So I have pinpointed the source of my issue to be right here in this particular line:
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again 🙂')
this (just for your reference) is the PossInputs function:
def PossInputs(x, y):
term = x
question = input(y)
lowQuestion = question.lower()
words = lowQuestion.split()
if term in words:
print()
print (correct)
else:
print()
print (incorrect)
So what I want to happen is, when 'shawn' is entered as a name, the program will jump to the OfficialSignInEdit Function, and ask the question 'What street did you grow up on?'. Then IF the user enters the answer 'perio', the program will print 'correct', and then print the message 'Greetings Master Shawn, it is a pleasure to see you again'. I tried to say that IF PossInputs == correct (and I did define correct = 'correct', and incorrect = 'incorrect' outside all functions) then this would happen, but instead it prints 'correct', and then 'Incorrect password, try again? (Yes/No)', so how can I make a conditional statement that says that if the user answers 'perio', then it will print the welcome message?
Just for thoroughness sake, I also tried
if PossInputs('perio', 'What street did you grow up on?: ') == True
also without success...
anyways anything you can give me is extremely appreciated, if you have any questions or you would like to to clarify something about the written code, I would be more than happy to get back with you as soon as I can.
Thanks!

Records and field syntax error

I am new to programming. I am currently taking python in school right now and I ran into a error and I figure it out. I keep getting a syntax error and I am not sure if it is typo on the instructor or myself.
def main():
num_emps=int(input("How many employee records? "))
empfile=open("employee.txt","w")
for count in range(1,num_emps+1):
print("Enter data for employee#",count,sep='')
name=input("Name: ")
id_num=input("ID Number: ")
dept=input("Department: ")
empfile=write.(name+"\n")
empfile=write.(id_num+"\n")
empfile=write.(dept+"\n")
print()
empfile.close
print("Employee records written to disk")
main()
I keep getting the error at
empfile=write.(name+"\n")
or is it supposed to be
empfile.write(name+"\n")
Thanks for the help
Use empfile.write() instead of empfile=write.()
Corrected and optimized version:
def main():
# indentation was missing in your question:
num_emps = int(input("How many employee records? "))
empfile = open("employee.txt","w")
for count in range(num_emps): # range from 0 to num_emps-1
print("Enter data for employee #{}:".format(count)) # use str.format(...)
name = input("Name: ")
id_num = input("ID Number: ")
dept = input("Department: ")
empfile.write(name + "\n")
empfile.write(id_num + "\n")
empfile.write(dept + "\n")
# alternative using Python 3's print function:
# print(name, file=empfile) # line-break already included
print()
empfile.close() # to call the function, you need brackets () !
print("Employee records written to disk")
main()
Also, there's not really a need to write a main() function in your example. You could have put the code directly into the file.
And if you want a proper main() function, use this construct to call it:
if __name__ == "__main__":
main()
else:
print("You tried to import this module, but it should have been run directly!")
It is used to determine whether a script was invoked directly or imported by another script.

Having trouble in python 3.0 with this code

I've been having trouble with this little program, it skips over the if == "otc": part completely, I've tried stuff to fix it but I just can't get it to work.
print("Hello, what is your name?")
name = input()
if name == "OTC":
print("get out otc!")
elif():
print("Hello! " + name
If you want to check if input has otc you can convert it into uppercase and check but if you want case sensitivity don't use upper()
Modification:
name = input("Hello, what is your name?")
if name.upper() == "OTC":
print("get out otc!")
else:
print("Hello! " + name)
output:
Hello, what is your name?"otc"
get out otc!
Hello, what is your name?"barny"
Hello! barny
Changes in your code:
There is no need for print since the same thing can be done using input function
There is no need for elif since there is only one condition check so use else
elif is a statement and not a function so remove the ()

Categories