简体   繁体   English

NameError:function 未在 Python 中定义

[英]NameError: function is not defined in Python

Please some help with the function请帮助 function

weightDiff

It works if I leave everything in a single.py file, however但是,如果我将所有内容都放在一个 single.py 文件中,它会起作用

  • If I create a new file called functions.py and move the function in a new file如果我创建一个名为 functions.py 的新文件并将 function 移动到一个新文件中

  • The function is missing the weight value function 缺少权重值

  • This is because the value weight is manually defined from the user by input()这是因为值权重是用户通过 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.不确定问题是什么,但通常您将 function 放在另一个文件中,然后将所需的 function 导入到您将使用它的脚本中。

Something like:就像是:

functions.py函数.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. function 要使用的文件。

main.py主程序

from functions import weightDiff


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM