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.