如何在 python 函数错误代码 "name 'male' is not defined" 中的函数内声明变量

How to declare variiables within functions in python function error code "name 'male' is not defined"

我想写一个程序,输入身高和性别,然后根据你的身高和理想的 BMI(男性 22,女性 21)告诉你你的理想体重应该是多少。

但是,当我调用该函数时,它始终不起作用。

源代码

def BMI(h,g):
    h = int(input("your height \n"))
    g = str(input("input your gender, 'male' or 'female' \n"))
    male = "male"
    female = "female"
    if g == male:     
        w=22*((h)**2)
    if g == female:
        w=21*((h)**2)
    return(w)

错误代码

"name 'male' is not defined"

感谢任何帮助 我正在使用 python 3

尝试:

def BMI():
    h = int(input("your height \n"))
    g = str(input("input your gender, 'male' or 'female' \n"))
    if g == "male":     
      w=22*((h)**2)
    elif g == "female":
      w=21*((h)**2)
    return(w)

如果您想通过@MrPrincerawat 调用该函数,您可以这样做:

def BMI(h,g):
    if g == "male":     
      w=22*((h)**2)
    elif g == "female":
      w=21*((h)**2)
    return(w)

致电:

BMI(100, 'male')

如果要打印:

print(BMI(100, 'male'))

如果你想把它作为一个变量:

weight = BMI(100, 'male')

只有在使用 Python 时才能解释您遇到的错误 2. 在这种情况下,您必须使用 raw_input 而不是 input

% python2
...
>>> input("input your gender, 'male' or 'female' \n")
input your gender, 'male' or 'female'
male
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'male' is not defined
>>> raw_input("input your gender, 'male' or 'female' \n")
input your gender, 'male' or 'female'
male
'male'

首先,如 , verify you are using Python 3 (Python 2 is still available, though EoL 并且在许多系统上可能是默认值 python

接下来,当您 总是 input 将它们设置在函数中时,您会破坏函数的参数!在函数之外设置它们不会影响其输出,并且始终向用户请求数据。要么

  • 接受函数外部的输入并将其作为参数传递
  • 设置默认值(None 几乎总是用于表示可选性)并且仅在未设置时覆盖它们
    def fn(a=None, b=None):
        if a is None:
            # logic to set a
    

这是Python3

中第一种形式的例子
#!/usr/bin/env python3

import sys

def healthy_weight_from_bmi(height, gender=None):
    """ calculate a healthy body weight from height and gender, using a BMI constant
    """
    height = float(height)  # input could be a string, but should be a float
    try:  # select BMI constant based upon gender or choose average if missing
        healthy_bmi = {
            "m": 22.0,
            "f": 21.0,
        }[str(gender).lower()[0]]
    except Exception:  # ValueError, KeyError, IndexError..
        healthy_bmi = 21.5
    return round(healthy_bmi * (height**2))  # int


# collect height
height = input("enter height(meters) (q to quit): ")
if height.lower().startswith("q"):
    sys.exit("quit by user!")
try:
    height = float(height)
except ValueError:
    sys.exit("invalid height {}: expected a float".format(height))

# collect gender
gender = input("enter gender (optional): ")
if gender.lower().startswith("q"):
    sys.exit("quit by user!")

# calculate healthy weight from inputs
healthy_weight = healthy_weight_from_bmi(height, gender)
print("healthy weight: {}kg".format(healthy_weight))

用法

% python3 ./bmi.py
enter height(meters) (q to quit): 1.7
enter gender (optional):
healthy weight: 62kg