pythonmodularity

NameError: function is not defined in Python


Please some help with the function

weightDiff

It works if I leave everything in a single .py file, however

import functions

firstName = input("Hi there, what's your name? ")
genderQuestion = input('Hello ' + firstName + ', are you a male or a female? ')
gender = genderQuestion.casefold()
age = input('How old are you? ')
weight = input("What's your weight in kg? ")
userData = [firstName, gender, age, weight]
userDetails = ['Name: ' + userData[0], 'Gender: ' + userData[1], 'Age: ' + userData[2], 'Weight: ' + userData[3] + 'kg']
print(functions.newLine())
print('Thanks for that. Below your details')
print('\n'.join(userDetails))

recommendedWeight = [89, 55]


def weightDiff(weight):
    if gender == 'male':
        return weight - recommendedWeight[0]
    else:
        return weight - recommendedWeight[1]


weightDifference = weightDiff(int(weight))
print(weightDifference)

What I want to achieve is a neat file, and a second file where I can store all my functions.


Solution

  • Not sure what the issues is, but in general you put the function in the other file and import the desired function into your script where you'll use it.

    Something like:

    functions.py

    recommendedWeight = [89, 55]
    
    
    def weightDiff(weight, gender):
        if gender == 'male':
            return weight - recommendedWeight[0]
        else:
            return weight - recommendedWeight[1]
    
    

    File where you want to use the function.

    main.py

    from functions import weightDiff
    
    
    # !!! Update this section to get input from user !!!
    weight = 5
    gender = "male"
    result = weightDiff(weight, gender)