python - 由于 for 循环,打印功能失败
问题描述
当我注释掉 for 循环时,一切正常。但是,一旦它再次处于活动状态,IDLE 就会吐出一个语法错误。我已经尝试适当地间隔它,因为这是对其他问题的建议之一,但无论我输入多少次,这都没有奏效。
# futval.py
# A program to compute the value of an investment
# carried 10 years into the future
#begins main function of program
def main():
#description of program
print("This program calculates the future value")
print("of a 10-year investment.")
#creates and assign three variables to user input
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annual interest rate: "))
compound = eval(input("How often is the interest compounded: "))
#begins a 'for' loop that iterates 10 times indicative of 10 years
for i in range(10):
print (principal)
principal = principal * (1 + (apr/compound)
#prints out the final result of the above equation.
print("The value in 10 years is:",principal)
#original program exited too fast and didn't allow user to see output
#I added the following line so the user could see.
print(input("Press enter to exit."))
main()
解决方案
语法错误是您缺少一个右括号:更改principal = principal * (1 + (apr/compound)
为principal = principal * (1 + (apr/compound))
此外,你应该改掉使用的习惯,eval
因为它通常被认为是危险的,在这里绝对不需要。只需转换为类型并捕获异常就可以了。