[Tutor] declaring a blank interger

Hugo Arts hugo.yoshi at gmail.com
Thu Oct 6 10:03:53 CEST 2011


On Thu, Oct 6, 2011 at 7:09 AM, Mike Nickey <mnickey at gmail.com> wrote:
> Hey all,
> I'm sorry for such a silly question but I want to declare a blank integer
> for x.  What I have is a base for a program that I'm working on for fun.
> Yes, for fun.

1) no question is silly 2) Programming is fun, many people have it as
a hobby! That's not weird at all.

> The long term goal is to create a way to log items that are currently being
> done via pencil & paper and make this easier for me and my team.
> What I am running into though is how can I declare a variable to use that is
> blank at start but then gets populated later on.
> Here is what I have so far.
> Thanks in advance

The question you need to ask yourself is "why?" If the variable has no
value, why would you declare it at all? Why not just wait until you
have a value for it? It is common for languages such as C to declare
all your variables beforehand, but in python there is really no need
to do that.

For one, variables in python don't have a type. Values do, but
variables do not. So there is no need to tell python beforehand what
types your variables will have. You can easily get rid of both of the
variable declarations at the top of that program, and assign them when
you have a value for them:

def get_username():
    return raw_input("Enter your name: ")

def get_usernumber():
    return raw_input("Enter a number: ")

username = get_username()
x = get_usernumber()

Note that raw_input, as a function, returns a value of type str
(that's a string). But for a number, it would make more sense to have
a value with type int. So we should adapt our get_usernumber function
to convert our str value into an int value:

def get_usernumber():
    return int(raw_input("Enter a number: "))

very simple, right? Now, the next problem you will run into, is what
happens when the user doesn't actually enter a number? I suggest you
try it. the int() function won't be very happy about it and raise an
exception. You'll have to catch that exception, print out some error
message, and ask for another number, until the user gets it right. But
I'll leave that part up to you.

HTH,
Hugo


More information about the Tutor mailing list