Noob question: Is all this typecasting normal?
Diez B. Roggisch
deets at nospam.web.de
Fri Jan 2 16:36:00 EST 2009
sprad schrieb:
> I've done a good bit of Perl, but I'm new to Python.
>
> I find myself doing a lot of typecasting (or whatever this thing I'm
> about to show you is called), and I'm wondering if it's normal, or if
> I'm missing an important idiom.
It is normal, although below you make things needlessly complicated.
Python is strongly typed, which is a good thing. It refuses to guess you
mean when you multiply a string with a number. Or how a number is to be
formatted when printed.
> For example:
>
> bet = raw_input("Enter your bet")
> if int(bet) == 0:
> # respond to a zero bet
You might better do
bet = int(raw_input("Enter your bet"))
because then you don't need to later on convert bet again and again.
But *one* conversion you need.
> Or later, I'll have an integer, and I end up doing something like
> this:
>
> print "You still have $" + str(money) + " remaining"
This is more concisely & with much better control over the output-format
(think e.g. digits of a fraction) using string-interpolation. See
http://docs.python.org/library/stdtypes.html#string-formatting-operations
for an overview.
In your case, a simple
print "You still have $%i remaining" % bet
does the trick.
Diez
More information about the Python-list
mailing list