2 Replies - 181 Views - Last Post: 13 May 2014 - 08:55 AM Rate Topic: -----

#1 MaverocK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 21-February 14

How to print a variable inside a function?

Posted 12 May 2014 - 09:42 PM

def cici(a, x, b, m):

    result = (a*x+B)/>/>/>%m

    ayy = []

    return (ayy.append(result))

print(ayy)




The code above does not work. Python says ayy is not defined.

1- ) How can I access/print the variable "ayy" inside the function?
2- ) Why does the code above not work?

Many thanks :)

This post has been edited by MaverocK: 12 May 2014 - 09:46 PM


Is This A Good Question/Topic? 0
  • +

Replies To: How to print a variable inside a function?

#2 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7649
  • View blog
  • Posts: 12,905
  • Joined: 19-March 11

Re: How to print a variable inside a function?

Posted 12 May 2014 - 10:08 PM

In this case, the problem is that you're trying to print the value of ayy outside of the scope in which it is declared. The value you create is returned as a value, without its name attached. When you call a function you have to capture and name the result:

If I define this function:

def sum(p,q):
  s = p+q
  return s



the result of running it is not "s", it's the sum of p and q. I can name that result s if I want, or I can name it "Howard".

>>> s = sum(4,5)
>>> s
9
>>>howard = sum("how", "ard")
>>>howard
'howard'



You've got a more annoying problem to deal with, though, and that is that the append() function does not return the result of appending something to a list. Instead, it performs that operation and then returns None. In the case of your function, the next thing that happens is that ayy goes out of scope and disappears forever.

You could repair this by modifying the function as follows:

def cici(a, x, b, m):
    result = (a*x+B)/>%m
    ayy = []
    ayy.append(result)
    return ayy



or you could use a slightly different approach:

def cici(a, x, b, m):
    result = (a*x+B)/>%m
    ayy = []
    return ayy +[result]



In the former case, you perform the operation and then return the modified array. In the latter case, you force result to be a list, and then you return the result of adding that list onto ayy

However, you'll notice that you could just as easily do

def cici(a, x, b, m):
    result = (a*x+B)/>%m
    return [result]



since the only effect of all this fussing around is to create a list containing just result as its value.
Was This Post Helpful? 1
  • +
  • -

#3 MaverocK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 21-February 14

Re: How to print a variable inside a function?

Posted 13 May 2014 - 08:55 AM

Oh understood. Thank you very much for a clear explanation. :smile2:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1