0

Take the following Perl code:

$a = 5;

if($a == 5)
{
    print $a;
    my $a = 8;
    print $a;
}

print $a;

This outputs 585 because my $a creates a new lexical variable that is scoped to the if block.

I want to do the same thing in Python, but this:

a = 5;
b = 9;

if a == 5:        
    print "inside function", b
    b = 'apple';

print b

outputs

inside function 9
apple

The variable b is overwritten inside the if. Is there any way to create a local variable b inside the if statement? I want to use the same variable name with local scope inside the if.

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
syam
  • 387
  • 4
  • 19
  • Python `if` blocks are in the same scope as their surroundings. If you want a new scope, extract and call a function. – jonrsharpe Jun 28 '16 at 16:29
  • Thanks @jonrsharpe for quick reply. but we cant use function every time insted of if rite? no explicit way to make it local like "my" or "local" vars in other langages? – syam Jun 28 '16 at 16:31
  • 1
    What? In general, you don't *need* a separate scope inside the `if`, but **if you do** you can create a new scope with a function. – jonrsharpe Jun 28 '16 at 16:32
  • @jonrsharpe, yes..I agree,.we dont need a seperate scope inside if. but in a rare condition where a user want to use a temporary variable inside the if block and need to name the temp var to same variable which is already used outside.. in this case since the namespace is global, he cant use the same var inside py. No option in this case apart from using a subroutine ? do he need to compormise in naming in if block ..Sorry if i didnt understood your previous explanation properly.. – syam Jun 28 '16 at 16:44
  • Yes, either use a different name or a different scope. How you do that is up to you. But an if block is not a separate scope. – jonrsharpe Jun 28 '16 at 16:47
  • Thanks @jonrsharpe for detailed replay. Very very helpful for me – syam Jun 28 '16 at 16:57
  • Possible duplicate of [Temporarily changing a variable's value in Python](http://stackoverflow.com/questions/23597692/temporarily-changing-a-variables-value-in-python) – tripleee Jun 29 '16 at 16:20

2 Answers2

1

The codes are not equivalent; in the Perl code, the my inside the if block creates an entirely new variable, which goes out of scope when the containing block ends.

You can do something similar with a context manager in Python, but the syntax will be much different.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

Is this what you're looking for?

a = 5
b = 9

def my_func(a):
    if a == 5:        
        b = 'apple'
        print("inside function: ", b)

my_func(a)
print("outside function: ", b)

> inside function: apple
> outside function: 9

b is a local variable inside the function my_func that is equal to apple, without affecting the global variable b that is equal to 9.

Jeff
  • 2,158
  • 1
  • 16
  • 29