在函数Python中使用用户输入作为输入

时间:2015-04-09 15:04:44

标签: python

我目前在Python 3中遇到了一些问题。我已经尝试弄清楚如何使用incomepension_contribution中存储的用户输入pension()但没有任何事情发生。这些用户输入应该放在哪里以便被视为输入,以便该功能可以工作?

income = input(int("What is your annual income?"))
pension_contribution = input(int("What is your monthly pension contribution?"))

def pension(pension_contribution, income):
    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")
    else:
        print("Your annual pension contribution is R", pension_contribution * 12)

2 个答案:

答案 0 :(得分:3)

1)你的缩进似乎已经关闭了 2)你需要调用函数

income = input(int("What is your annual income?"))
pension_contribution = input(int("What is your monthly pension contribution?"))

def pension (pension_contribution, income):

    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")

    else:
        print("Your annual pension contribution is R", pension_contribution * 12)

pension(pension_contribution, income)

答案 1 :(得分:0)

你可以用3种不同的方式做到这一点:

<强> 1。只需调用函数

即可
def pension (pension_contribution, income):

    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")

    else:
        print("Your annual pension contribution is R", pension_contribution * 12)

income = int(input("What is your annual income?"))
pension_contribution = int(input("What is your monthly pension contribution?")) 

pension(pension_contribution, income) #call function

<强> 2。将变量放在函数

def pension ():
    income = int(input("What is your annual income?"))
    pension_contribution = int(input("What is your monthly pension contribution?"))
    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")

    else:
        print("Your annual pension contribution is R", pension_contribution * 12)


pension() #still have to call function

<强> 2。全局变量(不推荐)

income = int(input("What is your annual income?"))
pension_contribution = int(input("What is your monthly pension contribution?"))

def pension ():
    global income, pension_contribution
    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")

    else:
        print("Your annual pension contribution is R", pension_contribution * 12)

pension() #still have to call function

注意每次必须实际“调用”该函数。否则程序将成功运行,但从不打扰进入该功能。