[Tutor] using a variable inside function, provided the variable is assigned a value after the function definition

Cameron Simpson cs at cskk.id.au
Sun Sep 19 18:14:44 EDT 2021


On 19Sep2021 12:41, Manprit Singh <manpritsinghece at gmail.com> wrote:
>Consider an example given below :
>def sumofnumber(x):
>    return x+b
>
>b = 3
>a = 4
>ans = sumofnumber(a)
>print(ans)   gives the answer = 7 which is the sum of 4 & 3 .
>the formal parameter x receives the value of  variable a which is 4 and the
>function returns x+ b , which is 4 +3  = 7 , because 3 is the value of
>variable b .
>Here the variable b which is assigned a value 3 after or below the function
>definition sumofnumber, is used inside the same function.
>
>My question is :
>A variable which is assigned a value below or after  the function
>definition , can be used inside that function definition or not ? is it a
>good practise ?

This is just a normal example of having some global state in a global 
variable. Generally globals are... discouraged. It is usually better to 
pass state as an formal parameter - that way you functions are "pure" - 
they do not rely on or change anything outside then, and have no side 
effects. They're easier to test, too, because you do not need to 
maintain the external state when you set up the test.

Where "b" is initialised is kind of beside then point. It _is_ typical 
to at least initialise it before the function definition if only so that 
someone reading the code has seen that initialisation before they try to 
figure out how the function works.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list