【问题标题】:How to declare variiables within functions in python function error code "name 'male' is not defined"如何在python函数错误代码“名称'男性'未定义”中声明函数内的变量
【发布时间】:2020-12-18 20:23:34
【问题描述】:

我想编写一个程序,输入身高和性别,并据此告诉你理想体重应该是多少,给定你的身高和理想的 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

【问题讨论】:

  • 你用的是什么版本的python?
  • 为什么h和g在方法内部的赋值。这应该在方法之外
  • 我投票结束这个,因为它不可复制,唯一的另一个问题是一个小错字(例如BMI(),而不是BMI(h, g))。

标签: python function variables scope call


【解决方案1】:

如果你想通过@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')

【讨论】:

    【解决方案2】:

    尝试:

    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)
    

    【讨论】:

    • 我仍然收到错误代码,即“男性”未定义。基本上在终端我写:BMI(1.83,男性),它只是不工作。嘘
    • 因为你将 h 和 g 作为函数内部的输入,所以不需要做 BMI(h,g)
    【解决方案3】:

    只有在使用 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'
    

    【讨论】:

    • 问题是使用 Python 3,
    • @FedericoBaù 有充分的证据表明这是错误的假设!
    【解决方案4】:

    首先,作为suggested by Nacib Neme,验证您使用的是Python 3(Python 2 仍然可用,though EoL 并且可能是许多系统上的默认python

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

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

    这是 Python 3 中第一种形式的示例

    #!/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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      相关资源
      最近更新 更多