簡體   English   中英

NameError:function 未在 Python 中定義

[英]NameError: function is not defined in Python

請幫助 function

weightDiff

但是,如果我將所有內容都放在一個 single.py 文件中,它會起作用

  • 如果我創建一個名為 functions.py 的新文件並將 function 移動到一個新文件中

  • function 缺少權重值

  • 這是因為值權重是用戶通過 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)

我想要實現的是一個整潔的文件,以及一個可以存儲我所有功能的第二個文件。

不確定問題是什么,但通常您將 function 放在另一個文件中,然后將所需的 function 導入到您將使用它的腳本中。

就像是:

函數.py

recommendedWeight = [89, 55]


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

function 要使用的文件。

主程序

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