This is my final project for the python crash course, why does it say " name 'file_contents' is not defined" , its keeps showing me that error, can someone help me and tell me what i'm doing wrong | Coursera Community

This is my final project for the python crash course, why does it say " name 'file_contents' is not defined" , its keeps showing me that error, can someone help me and tell me what i'm doing wrong

  • 15 October 2020
  • 6 replies
  • 792 views

Badge +1

 


6 replies

Hello.

I have not taken this course. But from my basic understanding of Python, you’re calling the function calculate_frequencies() passing a variable named file_contents as its argument. What type of variable is this? Use of lower(), split() and isalpha() methods in function definition suggest it should be a string type variable. Was it defined / assigned any value earlier? Was any text file opened ant its contents read into the variable?

Badge

Hey All,

 

I’m too getting the same error

And the hints for you are exactly the same as previously - ask yourself (and answer) the questions from my previous post.

Badge

In most cases, this error is triggered when Python sees a variable name (Global or Local) and doesn't know what it's for. These errors can happen if you forget to initialize a variable , if you misspell a variable, or if you misspell a reserved word such as "True". Before you use the global variable in your function for reading, it must be first initialized somewhere: either outside of the function or inside it.

 

Badge

I’m having this problem too! I have observed that the Jupyter Notebook is the culprit:

  1. This problem occurs when the text file is not being uploaded.
  2. Even after restarting the kernel, the file would not upload because the server is not responding to the code run in the cell containing the upload widget.
  3. As the calculate_frequencies function has a parameter called “file_contents”, which itself is derived from the upload text file cell, “file_contents” is unknown to the machine.
Userlevel 1
Badge +3

Hi, @Rushildave . I may be late to the party but here is my shot. I believe you defined a function ‘calculate_frequencies’ which takes ‘file_contents’ as an argument. That is fine. You need to define ‘file_contents’ outside the function if you want to use it anywhere else outside the function (the whole global variable and local variable issue, see e.g @geraldwarp , @Mateusz Kita , @bluesyDan ). Whenever you get the error ‘variable not defined’  within a function call, check its scope-local or global. Currently, file_contents is a variable local to the function and no other outside method can access it. Another method to make variables available outside of the functions that generated them is to ‘return’ them from the function. I have been stuck by overlooking that! Good luck.

Reply