0

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

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 岁,我希望程序显示客户欠款多少,并且违规行为为零。问题是我不断收到位置参数错误。我对这意味着什么有点困惑。任何人都可以提供帮助/示例吗?

4

2 回答 2

0

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


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()
于 2020-10-04T05:35:42.800 回答
0

您的代码中有几个问题:

  1. 位置参数错误是因为您调用risk_code()func 而不提供它需要的参数:violation

  2. user_name = print(input("What is your name?"))- user_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例如未使用),但这可能是一个好的开始。

于 2020-10-04T05:43:45.900 回答