Python Forum
Global variables or local accessible
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Global variables or local accessible
#2
Hello,

indeed true, using global variables and the global keyword is considered bad style and should be prevented. Except that using global variables is in 99% of all cases unnecessary, including your case.

Fixing your programm is fairly simple: just pass the position as an argument to the function and make the function return the new position, so it is available in your main function. Passing and returning values to / from functions is one of the basics in Python. In case you don't know I suggest to read the corresponding cheapers in the Python tutorial at docs.python.org .
Generally speaking, using global variables is considered bad style, as it makes the state of a program hard to somewhat impossible to trace.

Couple of other comments:

call doesn't need to be global anyway, as it is used only within main.

Line 20 is unnecessary and can lead to an recursion error. When a function is finished, it return to the point in the code from where it was called. In you case main calls e.g. left, left may call stop. When stop is finished it returns to left which return to main.

Never use blank try... except, that's wrong in 99,9% of all cases. Errors need to be caught specifically. Using blank try... exceptwill catch any error, including programming and syntax error. This can lead to an unexpected behaviour and hard to trace bugs.

Line 111 will lead to an error, as quiet is not defined.

Regards, noisefloor
Reply


Messages In This Thread
Global variables or local accessible - by caslor - Jan-27-2023, 12:00 PM
RE: Global variables or local accessible - by noisefloor - Jan-27-2023, 12:19 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,255 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Trying to understand global variables 357mag 5 1,197 May-12-2023, 04:16 PM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 1,883 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  global variables HeinKurz 3 1,196 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  How to use global value or local value sabuzaki 4 1,210 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  Clarity on global variables JonWayn 2 991 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,828 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,703 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,364 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  from global space to local space Skaperen 4 2,383 Sep-08-2020, 04:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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