0

我自学python,我有点困惑

#!/usr/bin/python

def Age():
        age_ = int(input("How old are you? "))


def Name():
        name_ = raw_input("What is your name? ")


def Sex():
        sex_ = raw_input("Are you a man(1) or a woman(2)? ")
        if sex_ == 1:
                man = 1

        elif sex_ == 2:
                woman = 2

        else:
                print "Please enter 1 for man or 2 for woman "

Age()
Name()
Sex()
print "Your name is " + name_ + " you are " + age_ + " years old and you are a " + sex_ + "."

错误

文件“./functions2.py”,第 25 行,打印“你的名字是”+name_+“你是”+age_+“岁,你是”+sex_+“。” NameError:名称'name_'未定义

当然它是在Name()函数中定义的?我很困惑 :(


Arr 我现在感谢它提供了更多的新证明,我现在在 Sex() 函数中遇到了问题。它在打印中返回一个数字而不是“男人”或“女人”这个词,所以我更改了代码以尝试修复它。但是我现在收到以下错误文件

"./functions2.py", line 16
    2 = woman
SyntaxError: can't assign to literal

我试图使 2 成为 str(2) 但它给了我另一个错误。感谢您到目前为止的帮助

#!/usr/bin/python

def Age():
    age_ = raw_input("How old are you? ")
    return age_
def Name():
    name_ = raw_input("What is your name? ")
    return name_
def Sex():
    sex_ = str(raw_input("Are you a man or a woman? "))
    if sex_ == 1:
            1 = man
            return sex_

    elif sex_ == 2:
            2 = woman
            return sex_

    else:
            print "Please enter man or woman "


age_ = Age()
name_ = Name()
sex_ = Sex()


print "Your name is " + name_ + " you are " + age_ + " years old and you are a " + sex_ + "."
4

3 回答 3

0

我已经更改了 "man" "1" 1 等以匹配问题。我也更改str(raw_input("Are you a man..."))input("Are you a man...")反映数据类型。

def Age():
    age_ = raw_input("How old are you? ")
    return age_
def Name():
    name_ = raw_input("What is your name? ")
return name_
def Sex():
    sex_ = input("Are you a man(1) or a woman(2)? ")
    if sex_ == 1:
        sex_ = "man"
        return sex_

    elif sex_ == 2:
        sex_ = "woman"
        return sex_
    else:
        print "Please enter 1 for man or 2 for woman "

age_ = Age()
name_ = Name()
sex_ = Sex()

print "Your name is " + name_ + " you are " + age_ + " years old and you are a " + sex_ + "."
于 2012-12-24T09:08:22.867 回答
0

最终的工作代码,以防有人遇到同样的问题

#!/usr/bin/python

def Age():
    age_ = raw_input("How old are you? ")
    return age_
def Name():
    name_ = raw_input("What is your name? ")
    return name_
def Sex():
    sex_ = str(raw_input("Are you a man or a woman? "))
    if sex_ == "man":
            sex_ = "man"
            return sex_

    elif sex_ == "woman":
            sex_ = "woman"
            return sex_

    else:
            print "Please enter man or woman "


age_ = Age()
name_ = Name()
sex_ = Sex()


print "Your name is " + name_ + " you are " + age_ + " years old and you are a " + sex_ + "."
于 2012-11-04T19:12:19.503 回答
0

是,但_name的范围仅延伸到Name()函数的末尾。一旦Name()函数退出,_name变量就消失了。

尝试这样的事情:

def Name():
    name = raw_input("What is your name? ")
    return name

_name = Name()

print "Your name is " + _name

你需要对年龄和性别做类似的事情。

于 2012-11-04T14:55:38.127 回答