NameError: name 'f' is not defined - python

I am working to create a quiz on Python with different difficulty levels. I am trying to use functions so I can keep calling the most frequent part of the code, appending the questions into a list from an external text file.
However, I am running into a problem. When attempting to call my function I get the error:
NameError: name 'f' is not defined
I've tried everything I can think of but if anyone could provide any help, it would be greatly appreciated!
Here is the function:
def quiz(f):
f = open("quiz.txt", "r").read().split('\n')
for line in f:
f.append(questions)
f.close()
quiz(f)
print(questions)
The print(questions) bit is just a way for me to check if the lines have appended to the list.

When your code hits the line quiz(f), no f has been defined.
At that point in your code, only one thing has happened -- a function name quiz has been defined. That's the only identifier you can refer to at that point in your code.
You have declared function quiz to accept a parameter, but it makes no use of that parameter. The correct definition would be def quiz().

Related

Name error when name is defined? For class project

Thank you for taking time to read this. I have a project due for my Programming class by Friday. The project is basically analyzing the most popular songs around the world. The user will input W is they want to see the most popular genre worldwide and how many streams it has. My program consists of two python files, one that contains the top 10 song list, and the other where the user will input their options.
Here is my file for my top10songs:
def Mostpopularw(Pop):
Pop =='Pop with 10,882,755,219 streams worldwide'
return Pop
and the file for where the user will put input
if choice=='W':
print(top10songs.Mostpopularw(Pop))
the code runs fine but when I try to enter 'W; it prints out
NameError: name 'Pop' is not defined
but I dont understand how pop is not defined? Can anyone help me?
Thanks!
It is not very clear what you want your Mostpopularw function to do, so its hard for us to help you make it do that thing. The current code doesn't make much sense, as you're comparing a Pop argument with a constant string, and then throwing away the result of the comparison before returning the same Pop value.
It may be that you just want the function to return the string, in which case it shouldn't be an argument:
def Mostpopularw():
Pop = 'Pop with 10,882,755,219 streams worldwide' # note, one = sign here!
return Pop
Now the calling code doesn't need to pass in an argument for Pop, which was the error you were having (you were passing in something that didn't exist).

How to pass variables from File A to a function in a class in File B

I've been reading a lot of articles and websites, regarding classes and instances. But none have been able to provide me with a clear answer to this problem. How do you pass a variable, from one file, to a function, which is nested in a class, in another file?
On my database file, I have gotten the individual values from a given row. I need to pass these variables to a function on my Main file, which is situated in a class.
When running the code below I get the following error : TypeError: PrintData() missing 1 required positional argument: 'DOB'
def DisplayStudent(self):
txtStudent = self.txtStudent.get()
DisplayResults(txtStudent)
def PrintData(self, First, Last, Year, Tutor, DOB):
print(First, Last, Year, Tutor, DOB)
self.resultStudentFName.config(text = First)
And when running the code below this, I get a different error : NameError: name 'self' is not defined
def DisplayStudent(self):
txtStudent = self.txtStudent.get()
DisplayResults(txtStudent)
def PrintData(First, Last, Year, Tutor, DOB):
print(First, Last, Year, Tutor, DOB)
self.resultStudentFName.config(text = First)
Note: This line of code is used on the Database file, the one with no class. It has not been changed for either of the following two sections of code above.
from Main import MainPage as MP
MP.PrintData(First, Last, Year, Tutor, DOB)
And when I pass self as an argument to the PrintData line, it says NameError: name 'self' is not defined.
Any help with this code, along with any documentation relating to the use of classes, functions, modules and passing varibales between files would be greatly appreciated.
Many thanks,
DavalliTV
By the looks of it your top snipit works except you just need to initialize the class when you pull it in:
from Main import MainPage as MP
newMP = MP() # or pass in __init__ args as needed
newMP.PrintData(First, Last, Year, Tutor, DOB) # assuming these args have been previously defined
Your bottom snipit doesn't work because it is a staticmethod without "self" in its argument list (therefore you cannot extend self. within the method)
I've found out what the issue was! I wasn't passing through self. Such a small issue/error can cause so much frustration! For those that look at this post in the future, make sure you carefully read what the error says, and make sure that when using classes, self is passed through. Thank you to Andrew and PydPiper for your efforts, I probably could've addressed the question better, but I appreciate you guys having a go!

Having error message on creating a module in Python

I'm starting to learn Python and I find it really interesting. I am trying to create my own module and I ran into a bump. The code goes like this:
def break_words(sentence):
words = sentence.split(' ')
return words
def sort_words (words):
sort_word=sorted(words)
return sort_word
The second function has argument words fed in by the first, and I think it should work since it has been returned, but on running filename.sort_words(words) in Python, it gives an error message of NameError:global name 'words' is not defined. And it's requiring me to define words like words=filename.break_words(sentence) before it runs the second function.
What's wrong with my code?
You should try to explain yourself better in future, it's very confusing to read and probably the reason nobody replied.
This is what I think you want to know:
import filename
words = filename.break_words('some sentence goes here')
print filename.sort_words(words)
Have you tried that?
edit:
Variables in Python are always defined in scopes, so defining one variable in a function means that it is not defined anywhere outside the function.
'return' simply returns the value of that variable to the caller.

Got UnboundLocalError: Local Variable referenced before assignment, but it wasn't

I am completely stumped. I looked at other answers to this same question, but none seemed to give the slightest answer as to why I myself am getting this error. I have pretty much 2 of the exact same programs running the same code with the exception of some URL's and Product ID's that it reads from files. The programs are a little bit long, so I put them on Pastebin Here. I don't expect you to read all the code, the error occurs in the main function where I define PID and then try to use it later in the function. Why does one work perfectly fine and the other does not? As far as I can see they are the same in that part, but maybe I missed something! Any help is appreciated!
Thanks!
PS: The error I receive is:
UnboundLocalError: Local variable 'PID' referenced before assignment
Your findall('CRC-START(.*?)CRC-END', PIDFile.read(), re.S) on line 202 didn't find anything, PID didn't get declared, boom, UnboundLocalError.
This happens because python interpreter makes a preliminary pass on the code, marking encountered variables as local, but it does not (and cannot) check if code that declares them will actually be executed.
Minimal reproducible example of that effect would be this:
>>> def foo():
if 0:
a = 1
print a
>>> foo()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
foo()
File "<pyshell#4>", line 4, in foo
print a
UnboundLocalError: local variable 'a' referenced before assignment
(Rep not high enough to 'comment') Link doesn't work. Could you maybe provide the code excerpt?
This error occurs when you try to use a variable before it is initialized (or defined depending on your code) - when you try to use a variable outside of its scope. Make sure that your variable WILL be initialized by the reference point. I'm wondering if you put that in an if-statement that doesn't get entered...
First of all, it seems that you reassign a new list to PID every iteration of a for loop. In the end your PID will contain only the last result.
I think what you really want to do is assign an empty list to PID before the for loop. Maybe after output = open(outputFile, 'w') and then append results to PID every iteration. Then you will not get UnboundLocalError even if nothing is found in PID.txt.

python, dictionary and int error

I have a very frustrating python problem. In this code
fixedKeyStringInAVar = "SomeKey"
def myFunc(a, b):
global sleepTime
global fixedKeyStringInAVar
varMe=int("15")
sleepTime[fixedKeyStringInAVar] = varMe*60*1000
#more code
Now this works. BUT sometimes when I run this function I get
TypeError: 'int' object does not support item assignment
It is extremely annoying since I tried several test cases and could not reproduce the error, yet it happens very often when I run the full code. The code reads data from a db, access sites, etc. so its hard for me to go through the data since it reads from several sources and depends on 3rd party input that changes (websites).
What could this error be?
Don't use global keyword in a function unless you'd like to change binding of a global name.
Search for 'sleepTime =' in your code. You are binding an int object to the sleepTime name at some point in your program.
Your sleepTime is a global variable. It could be changed to be an int at some point in your program.
The item assignment is the "foo[bar] = baz" construction in your function.

Categories