***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Global Variables and Global Constants

    When a variable is created by an assignment statement that is written outside all the functions in a program file, the variable is global. A global variable can be accessed by any statement in the program file, including the statements in any function.

    Example:

    #Create a global variable.

     number = 0

    def main():

    show_number()

    def show_number():

    print('The number you entered is', number)

    # Call the main function.

    main()

    An additional step is required if you want a statement in a function to assign a value to a global variable.

    Example:

    Most programmers agree to restrict the use of global variables, or not use them at all. The reasons are as follows:

    • Global variables make debugging difficult. Any statement in a program file can change the value of a global variable. In a program with thousands of lines of code, it can be difficult to track down the statement which is changing to wrong value in global variable.

    • Functions that use global variables are usually dependent on those variables. To use such a function in a different program, most likely you will have to redesign it so it does not rely on the global variable.

    • Global variables make a program hard to understand. A global variable can be modified by any statement in the program. If you are to understand any part of the program that uses a global variable, you have to be aware of all the other parts of the program that access the global variable.


    Ø  Global Constants

    A global constant is a global name that references a value that cannot be changed. Because a global constant’s value cannot be changed during the program’s execution, the potential hazards that are associated with the use of global variables are avoided.

    Although the Python language does not allow you to create true global constants, you can simulate them with global variables. If you do not declare a global variable with the global key word inside a function, then you cannot change the variable’s assignment inside that function.