简体   繁体   中英

How to use input() in function()?

When I call the function using compound_interest(P, r, n, t) it shows error name P is not defined, why ?

def compound_interest(P, r, n, t):
    P=int(input())
    r=int(input())
    n=int(input())
    t=int(input())
    A=P*(1+r/n)**(n*t)
    return(f'Total Amount = {A}')

compound_interest(P, r, n, t)

Best is first : because a method should only compute things, from parameters and not asking new value

Either pass the values as parameters you'd get from another source of input in the main program

def compound_interest(P, r, n, t):
    A = P * (1 + r / n) ** (n * t)
    return f'Total Amount = {A}'

# call compound_interest(1, 2, 3, 4)

Or you get the values from the input() inside the function so you don't need to passe them as parameters

def compound_interest():
    P = int(input("P: "))
    r = int(input("r: "))
    n = int(input("n: "))
    t = int(input("t: "))
    A = P * (1 + r / n) ** (n * t)
    return f'Total Amount = {A}'

# call compound_interest()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM