开发者

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

  • 开发者_JAVA技巧If I create a new file called functions.py and move the function in a new file

  • The function is missing the weight value

  • This is because the value weight is manually defined from the user by input()

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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜