%d运算符不在python 3.x中运行

时间:2017-01-28 22:55:57

标签: python python-3.x

运营商%d似乎在这里工作正常

print("The value in 10 years is $%d. Don't spend it all in one place!") % (principal)

main()

然而,它在这里不起作用:

 x = int(input("Enter how many years you would to calculate the future value of $%d. \nPlease choose at least 10 years: " ))  % principal

这里是完整的代码:

def main():
    #Describes the program
    print("This program calculates the future value")
    print("of a 10-year investment.")

    #Prompts the user to enter a principal amount
    principal = int(input("Enter the initial principal: "))

    x = int(input("Enter how many years you would to calculate the future value of $%d. \nPlease choose at least 10 years: " ))  % principal
    #loops through 10 periods, years in this case
    for i in range( x ):
        #calculates the new principal based on the interest
        principal = principal * (1 + 0.75)

     #prints the value and %d is a placeholder to format the integer
    print("The value in 10 years is $%d. Don't spend it all in one place!") % (principal)
    main()

我是否缺少此操作符的范围,或者它是否只是使用不正确且格式应完全不同?

2 个答案:

答案 0 :(得分:3)

您的代码不正确:

x = int(input("Enter how many years you would to calculate the future value of $%d. \nPlease choose at least 10 years: " ))  % principal

您应该将其替换为:

x = int(input("Enter how many years you would to calculate the future value of $%d. \nPlease choose at least 10 years: " % principal))

或使用format()

x = int(input("Enter how many years you would to calculate the future value of ${}. \nPlease choose at least 10 years: ".format(principal)))

此外,此代码也不正确:

print("The value in 10 years is $%d. Don't spend it all in one place!") % (principal)

您可以通过以下方式替换它:

print("The value in 10 years is $%d. Don't spend it all in one place!" % principal)

或使用format()

print("The value in 10 years is ${}. Don't spend it all in one place!".format(principal))

<强> NB:

%d会将您的principal变量格式化为integer = int 您可以使用%f并将其格式化为float以获得更好的效果。

答案 1 :(得分:0)

试试这个:

print("The value in 10 years is $" + str(principal) + ". Don't spend it all in one place!")

并且不要忘记将函数main()移到函数定义之外。