Python 解释器说我缺少位置参数。我对传递参数有点陌生并且感到困惑

Python Interpreter Says that I am missing a positional argument. I am a little new to passing arguments and confused

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

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()

如果我 select 我的年龄是 25 岁且零违规,我希望程序显示客户欠款多少。问题是我不断收到位置参数错误。我对这意味着什么有点困惑。谁能提供help/example?

您没有return函数中的任何内容,也没有向函数传递任何参数


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?")) - user_name 将是 None 因为 print 函数 returns 什么都没有。实际上,您不需要 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 未使用)但这可能是一个好的开始。