Python解释器说我缺少位置参数我对传递论点有些陌生,感到困惑

问题描述

我正在做一个关于通过函数传递参数的项目。我的问题是我正在编写一个程序,该程序根据年龄和交通违规情况给出收费金额。这是我当前的代码

print("Use this program to estimate your liability.")

def main():
    user_name()
    age()
    violations()
    risk_code()
#Input#

#Def for name
    
def user_name():
    user_name = print(input("What is your name?"))
    
#Def for age
def age():
    age = int(input("What is your age?"))
    
#Def for traffic violations (tickets.)
def violations():
    violation = print(input("How many traffic violations (tickets) do you have?"))
   
#Process#
def risk_code(violation):
    if violation == 0 and age >= 25: 
        risk = "None"
        cost = int(275)
#How many tickets to indicate risk code (therefore risk type)

# Age + traffic violations (tickets) = risk code

# Age + Traffic violations + Risk Code = Price

#Output#

#Def for customer name

# Def for risk output

# Def for cost
main()

如果我将年龄设为25岁(违规次数为零),我希望程序显示客户的欠款。问题是我不断收到位置参数错误。我对这意味着什么有些困惑。谁能提供帮助/示例?

解决方法

您没有从函数返回任何内容,也没有向函数传递任何参数


def risk_code(violation,age ):
 if violation == 0 and age >= 25: 
  risk = "None"
  cost = int(275)
  return risk,cost
def main():
 user_name = input("What is your name?")
 age = int(input("What is your age?"))
 violation =input("How many traffic violations (tickets) do you have?")
 risk,cost = risk_code(violation,age)
 print(f" Risk :{risk} and cost {cost}")


main()
,

您的代码中有几个问题:

  1. 位置参数错误是由于调用risk_code() func而没有提供所需的参数而引起的:violation

  2. user_name = print(input("What is your name?"))-用户名将为None,因为print函数不返回任何内容。实际上,您不需要print来输出消息,input可以为您完成消息。

  3. 必须将return添加到函数中,才能将在函数范围内定义的变量传递给其他函数。例如,在violations()函数中,violation变量是在函数范围内定义的,并且不返回该变量,您将无法在代码的其他地方使用它。

我对您的代码进行了一些更改,请尝试:

print("Use this program to estimate your liability.")


def main():
    user_name = get_user_name()
    user_age = get_age()
    violation = get_violations()
    risk_code(violation,user_age)


# Input#

# Def for name

def get_user_name():
    user_name = input("What is your name?")
    return user_name


# Def for age
def get_age():
    user_age = int(input("What is your age?"))
    return user_age


# Def for traffic violations (tickets.)
def get_violations():
    violation = input("How many traffic violations (tickets) do you have?")
    return violation


# Process#
def risk_code(violation,age):
    if violation == 0 and age >= 25:
        risk = "None"
        cost = int(275)
        print("cost:",cost)
        print("risk:",risk)


# How many tickets to indicate risk code (therefore risk type)

# Age + traffic violations (tickets) = risk code

# Age + Traffic violations + Risk Code = Price

# Output#

# Def for customer name

# Def for risk output

# Def for cost
main()

仍有很多工作要做(例如,user_name未使用),但这可能是一个好的开始。