Python传递变量

时间:2017-05-19 20:12:32

标签: python

我有这个简化的代码(我正在处理的代码实际上更大)...

def My_Age()
    Age = input ("What is your age")

def Message()
    print ("Your age is:", Age)

# Main program
Message()

我的问题是如何在消息函数中显示Age中的值?

4 个答案:

答案 0 :(得分:0)

别忘了':'用于功能

def My_Age():
    Age = input ("What is your age? ")
    return Age

def Message():
    print ("Your age is: " + str(My_Age()))

# Main program
Message()

# Output:
# What is your age? 15
# Your age is: 15
使用参数

编辑

def My_Age():
    Age = input ("What is your age? ")
    return Age

def Message(age):
    print ("Your age is: " + str(age))

# Main program
Age = My_Age()
Message(Age)

答案 1 :(得分:0)

def My_Age():
    # No need a variable
    return(input("What is your age? "))

def Message():
    print ("Your age is: {}".format(My_Age()))

# Main program
if (__name__ == '__main__'):
    Message()

最好在主程序之前使用此if (__name__ == '__main__'):语句,以便可以从其他函数调用此脚本中的函数。看一下这个 What does if __name__ == "__main__": do?

答案 2 :(得分:0)

您可以使用全局变量:

def My_Age():

        global Age
        Age = input ("What is your age")
def Message():

        My_Age()
        print ("Your age is: "+ Age)
Message()

答案 3 :(得分:-1)

你确定你一直在寻找吗?

def My_Age()
    Age = input ("What is your age")
    return Age

def Message()
    print ("Your age is:", My_Age())

# Main program
Message()