Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: runeazn on March 03, 2012, 07:33:40 pm

Title: defining a function
Post by: runeazn on March 03, 2012, 07:33:40 pm
ok this is my code with temp fix :

def i_to_c(inches):"
    inches=inches * 2.54
    return inches

def lbs_to_kg(lbs):
    lbs=lbs * 0.45359237
    return lbs

height = i_to_c(height)
weight = lbs_to_kg(weight)"


my first one was :"
def i_to_c(inches):
    inches=inches * 2.54

def lbs_to_kg(lbs):
    lbs=lbs * 0.45359237

i_to_c(height)
lbs_to_kg(weight)"


why doesnt my first code work? it should do fine me thinks.
but it still prints the first definition of that variable
while the function should redefine the variable..
Title: Re: defining a function
Post by: ruler501 on March 03, 2012, 07:36:26 pm
because its working with a local variable and that wouldn't be able to change a global variable. If you made the names different it may work though im not sure. I havent worked with python for a while
Title: Re: defining a function
Post by: runeazn on March 03, 2012, 07:37:48 pm
the point of my first method was is to make it versatile,
can be used many more times in the code itself and keeps it short and simple.
Title: Re: defining a function
Post by: C0deH4cker on March 03, 2012, 08:34:02 pm
Just change it from

i_to_c(height)

to

height = i_to_c(height)



Works the same way but actually works. You may consider working with classes.

Btw, you can rewrite the two functions like so:

Code: ("Python") [Select]
def i_to_c(inches):
    return inches * 2.54

def lbs_to_kg(lbs):
    return lbs * 0.45359237


Or, even smaller:

Code: ("Python") [Select]
i_to_c=lambda(i):i*2.54
lbs_to_kg=lambda(lbs):lbs*0.45359237
Title: Re: defining a function
Post by: runeazn on March 06, 2012, 10:13:28 am
isnt this what i did?
with my new code?

and i dont think array will do much?