0

I was to print the contents of a variable, despite the fact that the variable exists inside a def. This is what my code looks like:

def count_words():
    var_one = "hello world"

print count_words.var_one

The above does not work. I get the following error:

AttributeError: 'function' object has no attribute 'hello'

How do I get around this?

semiflex
  • 1,176
  • 3
  • 25
  • 44

3 Answers3

2

You need to return something:

def count_words():
    var_one = "hello world"
    return var_one

print(count_words())

Now the print statement is calling a function and printing what value is returned.

Nick H
  • 1,081
  • 8
  • 13
1

Nick's answer is probably what you want. As a side note, you might want to use a class and access its attribute as so:

class CountWords():
    var_one = "hello world"  # this is the attribute

count_words = CountWords()  # instantiate the class
print(count_words.var_one)  # access the class' attribute
Yisus
  • 415
  • 3
  • 14
1

If you want to print he contents of a variable, you need to make sure the variable exits and you can access. According to your code piece, you cant do what you want because both of the conditions are not satisfied. The code written in a file and the code after executing aren't the same concepts. The code written in a file is like a cookbook, and when the computer executes the code, it is as the cook is cooking something according to the cookbook. You cant tough the ingredient(print the variable) without the cook is cooking(the variable doesn't exit in the running environment, only exits in the file). And you cant tough the ingredient if the cook doesn't allow you to tough it(you don't have the accessibility to print the variable). A function is like a recipe, it tells you how to do some cooking, but it only remains in the paper(file) until you do the cooking following the recipe. Then you can print the variable according to answer

Community
  • 1
  • 1
EvanL00
  • 370
  • 3
  • 13