Python函数错误

时间:2019-01-04 09:32:37

标签: python

我知道这并不难,但是我总是遇到未定义的错误或其他错误,因此我尽了一切努力来寻求解决方案。我将输入变量放置在代码之外,并且部分起作用。我刚上第一门计算机科学课程仅三个星期。感谢您的帮助,谢谢。

# function that prompts the user for a name and returns it

def user():
    name = input("Please enter your name: ")
    return name

# function that receives the user's name as a parameter, and prompts the user for an age and returns it

def userAge(name):
    age = input("How old are you, {}? ".format(name))
    return age
# function that receives the user's name and age as parameters and displays the final output

def finalOutput(name, age):
    age2x = int(age) * 2
    print("Hi, {}.  You are {} years old.  Twice your age is {}.").format(name, age, str(age2x))

###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name

user()

# get the user's age

userAge("name")

# display the final output

finalOutput("name", "age")

2 个答案:

答案 0 :(得分:2)

您不会在此处存储用户提供的值,也不会将其传递回函数调用:

user()
userAge("name")
finalOutput("name", "age")

将以上行更改为:

name = user()
age = userAge(name)
finalOutput(name,age)

答案 1 :(得分:0)

更正1:

不要使用双引号传递参数,这意味着您正在将字符串文字传递给函数,而不是变量的实际值。 例如,如果您将变量名分配为“ Jhon”,并以userAge(“ name”)的形式传递给函数,则意味着您正在将字符串文字“ name”传递给userAge(),而不是变量值“ Jhon”。

def printName(name):
    print(name)
name = "jhon"
printName("name")

输出:名称

def printName(name):
    print(name)
name = "jhon"
printName(name)

输出:jhon

更好地将返回值分配给某些Valerie,并按@TBurgis的说明将其不带双引号传递。

更正2:

打印语句中的语法错误。正确的语法应该是

print("Hi, {}.  You are {} years old.  Twice your age is {}.".format(name, age, str(age2x)))