PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 19, 2022

[FIXED] How do I get a result (output) from a function? How can I use the result later?

 October 19, 2022     function, python, return     No comments   

Issue

Suppose I have a function like:

def foo():
    x = 'hello world'

How do I get the function to return x, in such a way that I can use it as the input for another function or use the variable within the body of a program? I tried using return and then using the x variable in another function, but I get a NameError that way.


For the specific case of communicating information between methods in the same class, it is often best to store the information in self. See Passing variables between methods in Python? for details.


Solution

def foo():
    x = 'hello world'
    return x  # return 'hello world' would do, too

foo()
print(x)   # NameError - x is not defined outside the function

y = foo()
print(y)   # this works

x = foo()
print(x)   # this also works, and it's a completely different x than that inside
           # foo()

z = bar(x) # of course, now you can use x as you want

z = bar(foo()) # but you don't have to


Answered By - Tim Pietzcker
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing