learning python ...

hw hw at adminart.net
Mon May 24 23:53:27 EDT 2021


On 5/24/21 4:28 PM, Michael Torrie wrote:
> On 5/24/21 8:17 AM, hw wrote:
>> What does python actually do in the first example?  Does it overshadow a
>> variable or does it change one?  If it overshadows a variable, it would
>> be dubious, if it doesn't, it won't be dubious.
> 
> Are you referring to this?
> 
>        num = input("Enter a number: ")
>        num = int(num)

yes

> No it is not "overshadowing" a variable.  You cannot get back to the
> original string value for num.

So the other example that uses a second variable to avoid possible 
ambiguity could be considered as bloating because it keeps both 
variables around.

>> There are more alternatives:  Python might create a new variable with
>> the same name and forget about the old one.  Or it doesn't forget about
>> the old one and the old one becomes inaccessible (unless you have a
>> reference to it, if there is such a thing in python).  How do you call that?
> 
> Python variables are not memory boxes like in a compiled language.  They
> are names bound to objects, as Mr Simpson alluded to.

That seems like an important distinction.  I've always been thinking of 
variables that get something assigned to them, not as something that is 
being assigned to something.

> So in the first
> line, the name num is bound to a string.  In the second line, the name
> is re-bound to an int object.

I would think of it as assigning a string to a variable and then 
changing the content of the variable by assigning something else to the 
same variable.  When variables are typeless, it doesn't matter if a 
string or an integer is assigned to one (which is weird but can be very 
useful).

It seems much more practical to assign different strings to the same 
variable rather than assigning a different variable to each string, or 
to assign a string to a variable and then to assign an integer to it.

Isn't that what variables are for?

> Furthermore, if num had come from the
> global name scope, either of these lines would create a local name num
> that does shadow the name from the global scope.
> 
> Hope that helps.
> 
> 

Yes, I guess it will be interesting not to think of variables but of 
objects.


More information about the Python-list mailing list