Python Forum

Full Version: Still confused about how passing arguments works
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a simple user input program:

#!/usr/bin/python
#QuickTest.py

def getLocation(x,y,z):
    x = input("Specify horizontal position: ")#latitude
    y = input("Specify vertical position: ")#longitude
    z = input("Specify altitude: ")#above sea level
    return x,y,z

def QuickTestMain():
##    x = 0
##    y = 0
##    z = 0
    getLocation(x,y,z)
    print("You are located at " + str(x) + "degrees latitude, " +
          str(y) + " degrees longitude, " + " and " + str(z) +
          " feet above sea level.")

QuickTestMain()
When lines 11 - 13 are not commented out, it just prints all 0's (I just wanted to initialize them, so that they exist in the program):
Error:
========== RESTART: I:/Python/Python36-32/SamsPrograms/QuickTest.py ========== Specify horizontal position: 3 Specify vertical position: 4 Specify altitude: 5 You are located at 0degrees latitude, 0 degrees longitude, and 0 feet above sea level. >>>
And then if I comment them out, I get:
Error:
========== RESTART: I:/Python/Python36-32/SamsPrograms/QuickTest.py ========== Traceback (most recent call last): File "I:/Python/Python36-32/SamsPrograms/QuickTest.py", line 19, in <module> QuickTestMain() File "I:/Python/Python36-32/SamsPrograms/QuickTest.py", line 14, in QuickTestMain getLocation(x,y,z) NameError: name 'x' is not defined >>>
How do I fix this?
x,y,z = getLocation(x,y,z)
There is no need for your getLocation function to have x,y,z arguments, because user will input them after the function is called.
def getLocation():
    x = input("Specify horizontal position: ")#latitude
    y = input("Specify vertical position: ")#longitude
    z = input("Specify altitude: ")#above sea level
    return x,y,z
and then when you are printing it inside QuickTestMain function add
x,y,z = getLocation()
because you need to store the return values from your getLocation function, otherwise they will get lost :D
As mention bye @mlieqo getLocation() shall not have argument in,they get create in function.
PEP-8 and f-string.
def location():
    x = input("Specify horizontal position: ")
    y = input("Specify vertical position: ")
    z = input("Specify altitude: ")
    return x, y, z

def quick_test():
    latitude,longitude,altitude = location()
    print(f'You are located at {latitude} degrees latitude '
          f'{longitude} degrees longitude and {altitude} feet above sea level.')

quick_test() 
Output:
You are located at 100 degrees latitude 200 degrees longitude and 300 feet above sea level.