Author Topic: defining a function  (Read 2534 times)

0 Members and 1 Guest are viewing this topic.

Offline runeazn

  • LV4 Regular (Next: 200)
  • ****
  • Posts: 191
  • Rating: +5/-3
    • View Profile
defining a function
« 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..

Offline ruler501

  • Meep
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2475
  • Rating: +66/-9
  • Crazy Programmer
    • View Profile
Re: defining a function
« Reply #1 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
I currently don't do much, but I am a developer for a game you should totally try out called AssaultCube Reloaded download here https://assaultcuber.codeplex.com/
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCM/CS/M/S d- s++: a---- C++ UL++ P+ L++ E---- W++ N o? K- w-- o? !M V?
PS+ PE+ Y+ PGP++ t 5? X R tv-- b+++ DI+ D+ G++ e- h! !r y

Offline runeazn

  • LV4 Regular (Next: 200)
  • ****
  • Posts: 191
  • Rating: +5/-3
    • View Profile
Re: defining a function
« Reply #2 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.

Offline C0deH4cker

  • LV5 Advanced (Next: 300)
  • *****
  • Posts: 258
  • Rating: +11/-1
    • View Profile
    • iNinjas Forum/Repo
Re: defining a function
« Reply #3 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

Offline runeazn

  • LV4 Regular (Next: 200)
  • ****
  • Posts: 191
  • Rating: +5/-3
    • View Profile
Re: defining a function
« Reply #4 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?