在python上有缩进问题

时间:2016-12-05 04:08:17

标签: python python-2.7

我不知道如何使用此代码修复python上的标识问题。 因为这一切都在这一刻抛出。我跑的时候。

import math

p = int(raw_input("Please enter deposit amount: \n"))

i = int(raw_input("Please input interest rate: \n"))

t = int(raw_input("Please insert number of years of the invesment: \n"))

interest = raw_input("Do you want a simple or compound interest ? \n")



A =p(1+r*t)

B =p (1+r)^t



if interest == "simple":
print int(float(A))

elif interest == "compound":
print int(float(B))

2 个答案:

答案 0 :(得分:2)

Python要求缩进语句块以便定义块结束的位置。有些语言使用大括号({})或其他符号来分隔块的开头和结尾。但是,在Python中,行末尾的冒号(:)表示下一行是块的开头,并且该块必须缩进多于冒号所在的行,并且该行中的每一行都是块必须缩进完全相同的数量。后面的任何一行回到带冒号的行的原始缩进级别(或者反向缩进(后退)?)表示该块的结束。

因此...

您的if块(if行下方的单行代码)应缩进超过if行本身。 elif行没有缩进,因为它不是if块的一部分。与elif行和elif块类似。

因此,最后4行的缩进应为:

if interest == "simple":
    print int(float(A))
elif interest == "compound":
    print int(float(B))

对于大多数语言而言,缩进仅仅是为了样式和可读性。使用Python,它也是语法的一部分。

答案 1 :(得分:1)

在Python中编写if a == b: print c

if

如果条件为真,则if a == b: print c print b 必须运行一些代码。

当你的if不仅仅是一件事

if

并不总是清楚哪些操作与if a == b: print c print b 条件相关联

print b

在这种情况下,python不知道a == bprint b还是 File "broken.py", line 2 print(c) ^ IndentationError: expected an indented block 当代码不清楚时,计算机不喜欢它。

if a == b:
    print c
print b

但我们可以采取措施使其更加清晰。

喜欢这个

print b

现在,Python可以判断if interest == "simple": print int(float(A)) elif interest == "compound": print int(float(B)) 与if条件无关,因为它没有缩进。

TL; DR: 你的程序的最后4行应该是

$1