Python Forum
When do you put variables inside vs outside a function?
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
When do you put variables inside vs outside a function?
#1
Check out this code from my interpreter:
$ python3
>>> first_list = [1,2,3,4,5,6]
>>> second_list = [101,202,303,404]
>>> first_list.reverse()
>>> print(first_list)
[6, 5, 4, 3, 2, 1]
>>> reverse(second_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'reverse' is not defined
>>> 
In the first line and second lines, I define two lists. Then I proceed to reverse the order of the first_list and second_list in two different ways. The first reversal succeeds whereas the second way is rejected.

Putting the variable inside the reverse function as a parameter in the second way is how I initially would naturally use it if I were to write a script (which I can clearly see now would be rejected by the Python interpreter).

The instructor in the Udemy course I am taking suggests putting the variable in front of the function separated by a dot. I understand that the computer dictates what works and what doesn’t. I just want to know why since my (faulty) approach comes so much more naturally.

How come variables sometimes have to go in front of the function when other times it can go inside a function as a parameter?

I suppose the much more important question I now have is this: When I am manipulating variables, how do I know when to put variables outside vs inside?
Reply


Messages In This Thread
When do you put variables inside vs outside a function? - by Drone4four - Jun-02-2018, 03:15 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  with open context inside of a recursive function billykid999 1 603 May-23-2023, 02:37 AM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 828 May-02-2023, 08:40 AM
Last Post: Gribouillis
  How to print variables in function? samuelbachorik 3 951 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  User-defined function to reset variables? Mark17 3 1,701 May-25-2022, 07:22 PM
Last Post: Gribouillis
  How to make global list inside function CHANKC 6 3,163 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Parameters aren't seen inside function Sancho_Pansa 8 2,982 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  Do I have to pass 85 variables to function? Milfredo 10 4,370 Sep-26-2020, 10:13 PM
Last Post: Milfredo
  Creating a variables inside FOR loop zazas321 5 4,156 Sep-16-2020, 04:42 PM
Last Post: Naheed
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,528 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  Issues with storing variables outside of a function cerulean747 7 3,770 Apr-30-2020, 08:46 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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