首页 > 解决方案 > Python 需要一个缩进的块 kkk

问题描述

我对 python 比较陌生,我不确定 if else 的缩进是如何工作的。

编写一个 Python 程序,计算从 x 到 y 的所有数字的总和,其中 x 和 y 是用户输入的数字。

print("This program prints the sum of range from x to y. ")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers from 10 to 50. ")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))

if type(x) == int and type(y) == int:
 if x > 0 and y > 0:
    if y > x:
        sum_of_numbers = []
        for counter in range(x , y):
        sum_of_numbers.append(x)
        x += 1
        print("The sum of numbers from {} to {} is  {}".format(x,y,sum(sum_of_numbers)))

    else:
        print("You did not enter a value of y greater than x")
        print("Unable to continue.Program terminated.")
        exit()
 else:
    print("One or more inputs is not greater than zero")
    print("Unable to continue.Program terminated.")
    exit()       
else:
    print("One or more inputs is not numeric!")
    print("Unable to continue.Program terminated.")
    exit()

标签: python

解决方案


if type(x) == int and type(y) == int:
 if x > 0 and y > 0:                    # indented 1
    if y > x:                           # indented 3
        sum_of_numbers = []             # indented 4

根据PEP8 ,您需要有一致的缩进,每个缩进最好有四个空格。

没有它,Python 编译器(或者你也一样,真的)无法判断你的代码是如何构造的。


推荐阅读