using Python Modules

jskfan
jskfan used Ask the Experts™
on
using Python Modules

I have this Python Code:

def test1(weight):
    return weight * 0.45
print(test1())

def test2(weight):
    return weight/ 0.45
print(test2())

Open in new window


I want to call the methods above from this program and pass the wight argument for instance 200
from mod1 import test1,test2
test1(200)
test2(200)

Open in new window


however, it seems like if I do not specify the weight  in Mod1.py   the calling code will fail.

C:\Users\user\AppData\Local\Programs\Python\Python38\python.exe C:/Python-Projects/Mydjangoproject/test.py
Traceback (most recent call last):
  File "C:/Python-Projects/Mydjangoproject/test.py", line 1, in <module>
    from mod1 import test1,test2
  File "C:\Python-Projects\Mydjangoproject\mod1.py", line 3, in <module>
    print(test1())
TypeError: test1() missing 1 required positional argument: 'weight'

Process finished with exit code 1[code]

Open in new window


[/code]
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
your print statements are after the function returns (ergo not in the function) so it will error out when it tries to compile the functions
Top Expert 2016

Commented:
a.py
def test1(weight):
    return weight * 0.45

def test2(weight):
	return weight / 0.45

Open in new window

>>> from a import test1,test2
>>> test1(200)
90.0
>>> test2(200)
444.44444444444446
>>>

Open in new window

NorieAnalyst Assistant

Commented:
Remove the print statements from mod1.py

Or if you want to keep them for some reason, e.g. to test the functions, then try something like this.
def test1(weight):
    return weight * 0.45

def test2(weight):
	return weight / 0.45

if __name__ == '__main__':
    print(test1(100))
    print(test2(100))

Open in new window

Author

Commented:
David,

I corrected the code but still do not get any result:

Test.py
from mod1 import test1,test2
test1(200)
test2(200)

Open in new window


Mod1.py

def test1(weight):
    return weight * 0.45
    print(test1())

def test2(weight):
    return weight/ 0.45
    print(test2())

Open in new window


when I run it, I do not get any result:

C:\Users\user\AppData\Local\Programs\Python\Python38\python.exe C:/Python-Projects/Mydjangoproject/test.py

Process finished with exit code 0

Open in new window

Analyst Assistant
Commented:
jskfan

The print statements are never reached due to the return statements preceding them.

Try this.

Mod1.py
def test1(weight):
    return weight * 0.45

def test2(weight):
    return weight/ 0.45

Open in new window

Test.py
from mod1 import test1,test2

print(test1(200))
print(test2(200))

Open in new window

Author

Commented:
Perfect!

it worked ..Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial