![]() |
Variables
OK, i am making a simple program in python, all was going well until the variables didnt work. The actual code is a bit to long to post and it is very messy, so i made this example of what error i am getting.
:
#defining the variableYou see basically, i have declared a variable, i then have made a funtion that should change that variable, i then call that funtion and print the variable. Basically, the msg variable stays as "Hello" and doesnt change. I think it is something to do with Global variables etc. but im not sure how to correct it, i tried return msg but it doesn't work. I have searched google (maybe i am searching for the wrong words?) and i checked the python documentation but i cannot find the answer to my question. How can i fix it so that it prints the variable from the function? :confused: |
You have a function that returns something so you need to assign it to a variable when you call it. This should do it:
:
#defining the variable |
:
#defining the variableReturn from a function returns the variable to whatever called the function. The way you had it setup, the new value wasn't being returned to any variable, and the temporary variables were therefore not used. For this part: :
def changeit(new):Could be made: :
def changeit(new):Because declaring msg doesn't do anything anyways. Inside a function, only the variables that were changed and created within that function will operate, none will exist outside that function or the next time you visit the function again. The only way to ever see it again is with the command global, or using return and then passing it back as a paramater. Here is another way of looking at your program that is slightly more advanced: :
class variable(object): #variable can be changed to any word |
Thanks for your help, just after i posted this topic, "the python bible" book form amazon.co.uk got delivered and i learnt how to do object oriented python, so i managed to sort out my problem. :)
It was a stupid error to make in the first place, thanks dietrich for sorting that out. Sane that advanced way looks good, mine looks a bit like that ;) |
Hey I sorted it out too! Just 30 seconds after dietrich did . ;)
|
| All times are GMT -5. The time now is 2:05 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC