Python Forum
Issues with storing variables outside of a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issues with storing variables outside of a function
#2
In general variables that are created inside a function are local to the function and cannot be read outside it.

In the smallest of programs, you could create the variable outside the function (making it a global). But this gets to be unwieldy as programs get larger.

Otherwise, your function should return the data you need, and the calling program can assign that data to variables that are in scope for that location. Something like:

def player_input():
    # do some processing that populates player1_mark and player2_mark
    return player1_mark, player2_mark

p1, p2 = player_input()
print(f"player 1 is: {p1}")
print(f"player 2 is: {p2}")
Reply


Messages In This Thread
RE: Issues with storing variables outside of a function - by bowlofred - Apr-29-2020, 11:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to print variables in function? samuelbachorik 3 918 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  User-defined function to reset variables? Mark17 3 1,661 May-25-2022, 07:22 PM
Last Post: Gribouillis
  Storing variables into one file for use in multiple Jupyter notebooks devansing 1 1,748 Feb-05-2022, 10:04 AM
Last Post: ibreeden
  Conjugate Gradient having issues with defining A (function to solve [A]{x} = {b} ) DimosG 2 2,837 Sep-21-2021, 08:32 PM
Last Post: 1968Edwards
  Storing whole functions in variables dedesssse 3 2,103 Jul-29-2021, 09:17 PM
Last Post: deanhystad
  Do I have to pass 85 variables to function? Milfredo 10 4,326 Sep-26-2020, 10:13 PM
Last Post: Milfredo
  subprogram issues: cannot unpack non-iterable function object error djwilson0495 13 6,017 Aug-20-2020, 05:53 PM
Last Post: deanhystad
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,500 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  Temporarily storing the value of a function Men 6 2,823 Jun-21-2020, 06:43 PM
Last Post: Men
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 3,049 Feb-09-2020, 02:05 PM
Last Post: new_to_python

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020