All, I was recently introduced to programming, so this is really a beginner's query. Let me know if this is not the right mailing list for that. I will switch it accordingly. Anyway to my query:
I have heard that the "Globals are bad for programming" - ( http://c2.com/cgi/wiki?GlobalVariablesAreBad). Keeping that in mind, I need to change my solution from below to something more elegant. Can someone let me know the best solution for sharing the values of Num1 and Num2 in the example given below. From my perspective 3 options came into my mind when I coded this #1. Was to use Globals (Num1 and Num2) to pass variable values between the various methods. #2. Was to create an object and have Num1 and Num2 defined as class member variables. In that case, the value of these variables could be used across multiple methods defined on that class. #3. Was to use an array/list type data structure, store the Num1 and Num2 values in it and then return that structure everytime I want to expose the value of Num1 and Num2 between various method calls. It is possible that there maybe more elegant solutions. But I quite frankly do not know how to decide. Therefore requesting help ... =================================================== #!/usr/bin/env python __author__ = 'vsharma' Num1 = 0 Num2 = 0 def captureInput(): # Capture Input - Get the 2 numbers to be checked for connectivity. # Remember to do a file based parsing logic for the same. global Num1, Num2 Num1 = int(raw_input('First Number: ').rstrip('\n')) Num2 = int(raw_input('Second Number: ').rstrip('\n')) print "Checking (", num1, ",", num2, ")" def doConnectivityCheck(Num1, Num2): # I have removed the actual code for simplicity print "The following 2 numbers are connected (", Num1, ",", Num2, ")" return def storeInput(Num1, Num2): # I have removed the actual code for simplicity print "The following 2 numbers have been stored (", Num1, ",", Num2, ")" return def main(): userResponseFlag = 1 while userResponseFlag: userResponse = raw_input('Do you want to check connectivity between 2 given numbers - answer(y/n) only: ') if userResponse == 'y': captureInput() doConnectivityCheck(Num1, Num2) storeInput(Num1, Num2) elif userResponse == 'n': userResponseFlag = 0 else: print "Your input does not confirm to the y/n rule, fix that and retry" continue main() =================================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/portland/attachments/20120729/460d0530/attachment.html> _______________________________________________ Portland mailing list [email protected] http://mail.python.org/mailman/listinfo/portland
