%d运算符不是';t在Python3.x中工作

%d运算符不是';t在Python3.x中工作,python,python-3.x,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: " )) %

操作员%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()

我是否缺少此运算符的某个作用域,或者它只是使用不正确,并且格式应该完全不同?

您的代码不正确:

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))
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)
您可以将其替换为:

x = int(input("Enter how many years you would to calculate the future value of $%d. \nPlease choose at least 10 years: " % principal))
print("The value in 10 years is $%d. Don't spend it all in one place!" % principal)
或使用
格式()

NB:

%d
将把
主体
变量格式化为
整数=int
您可以使用
%f
并将其格式化为
浮点数
,以获得更好的表示效果。

请尝试以下方法:

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

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

您正在将
%
运算符应用于
int()的返回值。
;整数不支持字符串格式,而是应用了
%
运算符(模数)的正常函数:
10%5
0
10%4
是2,等等。此外,您的第一个声明是错误的
print()
返回
None
,因此
print(“…”)%(something,)
引发异常。您必须在打印之前将其应用于字符串。您确定使用的是Python 3吗?如果
print
行实际起作用,那么您就必须使用Python 2。您想要
print(“hello%s”%name)
,而不是
print(“hello%s”)%name
。这同样适用于最后的
print()
函数调用。有更好的方法格式化字符串。OP大致在正确的轨道上,只是不知道在哪里应用
%
操作符。不过,
str.format()
会更好。@DYZ我也是个初学者。我不知道str.format()。看起来确实更好。