[ANSWERED] How to pass a variable itself to a method | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[ANSWERED] How to pass a variable itself to a method

https://code.sololearn.com/cuiFOyezKL4G/#py I wrote a code that makes you at last enter a numerical answer. It tests the variable if it is a float and if not, requests for new answer. I wanted to abandon line 11 and 13 and pass variable itself, not its value to a method. All operations are done with variable fl, but all values are assigned to myNum. Otherwise you take var myNum, assign it to argument fl, make all neccessary calculations, and assign fl value to myNum. Obviously, writing the method we dont know the passed variable name. Is it possible to implement?

11th Sep 2017, 10:41 AM
Alex Snaidars
Alex Snaidars - avatar
1 Answer
+ 5
Python is a pass by Object or reference language. The problem is that you are using an immutable type, so that a copy is being made inside the function/method instead of changing the original variable. If you wrap the immutable type inside of a mutable type (list) then that value can be changed directly using the reference to the wrapper. def ifFloat(var): ToF = True while ToF: try: float(var[0]) # access the via its index ToF = False except: var[0] = input("Enter a valid number\n") # change the value via its index ToF = True myNum = [input("Enter a number\n")] # wrap the value in a list instead so that it is mutable ifFloat(myNum) print(myNum[0]) # access the via its index This code works as before but changes the value directly.
10th Sep 2017, 10:43 PM
ChaoticDawg
ChaoticDawg - avatar