[Tutor] Declare empty string variable?

Gonçalo Rodrigues op73418@mail.telepac.pt
Sun Dec 29 07:33:02 2002


----- Original Message -----
From: "Volker Hoffmann" <volker@omega-fleet.dyndns.org>
To: "Python Tutor ML" <tutor@python.org>
Sent: Sunday, December 29, 2002 10:51 AM
Subject: [Tutor] Declare empty string variable?


> Hi,
>
> at first I just want to say hi. I've been reading on digests for a
> couple of months (rather irregularily though) as I didn't have much
> time for getting into python. Now I have some spare time and I'm gonna
> be starting of with a possible stupid question :-).
>
> I want to write a program that converts decimal numbers into binary
> format. That should be a fairly easy task, but not with my limited
> knowledge of python. Here's how my code looks so far:
>
> > ### Decimal to Binary Conversion
> > deci=input("Decimal? --> ")
> > dual= <--- declaration
> > ...
> > while deci>0:
> >     dual_tmp=deci%2
> >     dual=dual_tmp, dual <--- change dual here

Are you sure this is correct? From your description "dual" is supposed to be
a string, but on the right hand-side you have a tuple. So you should get an
error here.

> >     deci=deci/2
> > print "Binary is", dual
>
> Now I want the variable "dual" to be the output where the binary is
> being stored. However, since I assume that all variables have to be
> initialized in python I don't have any clue HOW to make dual a string
> variable that's being updated every time in the while-loop.
>
> Now, how do I have to declare "dual" to be a string and without any
> value at the beginning? Is there any way like in pascal where it's
> beging declared like this:
>
> > var
> >  dual:string;

The best thing is to switch into the Pythonic frame of mind. In Python a
variable is just a name (a tag, a label, what-you-will) that is bound (that
references) some Python object. Whenever Python sees something like

>>>myvariable = "a test"

It creates the name "myvariable" in the current namespace if it is not
already there and binds it to the Python object, a string in this case, "a
test". Next time you use myvariable in some expression Python just sticks in
"a test" automatically.

As you see from my description variables are created on the fly, so to
speak, no declarations are needed. So, to answer your question in a more
direct manner you just do

>>>dual = ""

and voilá, you now have a dual variable initialized to the empty string.

Just one last tidbit: variables are typeless, that is, they have no
associated types. As I said before they are just names. So you could also do

>>>dual = None

which looks more explicit, and then later do

>>>dual = "a test"

>
> Thanks in advance,
> - Volker

With my best regards,
G. Rodrigues

>
> --
> "Earth is the cradle of mankind,
>   but one cannot live in the cradle forever."
>    - Konstantin Tsiolkovsky