【问题标题】:Is there a way in python 3 to make it so that two user defined functions only require input oncepython 3中是否有一种方法可以使两个用户定义的函数只需要输入一次
【发布时间】:2020-04-29 04:35:41
【问题描述】:

假设我在 Python 3 中有两个用户定义函数 monthly_salary()report()

def monthly_salary():
    monthly_salary = int(input('Enter Monthly Salary'))
    return monthly_salary

def report():
    yearly_salary = monthly_salary() * 12

    message = '%s %4d %s %6d' % ('John gets paid monthly salary of', monthly_salary(), '& yearly salary of', yearly_salary)

    print(message)

如果我运行上面的代码,它会询问用户每月用户两次。有没有办法让它只向用户询问一次月薪?

【问题讨论】:

  • 提示:你是如何已经做到的,​​这样当你格式化message时,你就不必再次计算monthly_salary() * 12了?做同样的事情,这样您就不必重复 monthly_salary() 计算。
  • 不需要时不要调用该函数两次

标签: python python-3.x variables user-defined-functions


【解决方案1】:

您的代码要求输入两次,因为您调用了monthly_salary() 两次。 更改您的代码以存储在一个变量中,并将其用于进一步计算。

def monthly_salary(): 
    return int(input('Enter Monthly Salary: '))

def report():
    m_salary = monthly_salary()

    message = '%s %4d %s %6d' % ('John gets paid monthly salary of', m_salary, '& yearly salary of', m_salary * 12)

    print(message)

report()

【讨论】:

    【解决方案2】:

    您可以将月薪存储在一个变量中并使用该变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2012-02-06
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多