python - 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()
解决方案
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 编译器(或者你也一样,真的)无法判断你的代码是如何构造的。
推荐阅读
- python - 将列表中的元素与以下元素相除?
- python-3.x - 重试装饰方法 Python Nosetest 的单元测试
- c++ - 将可修改的二维数组作为类参数传递
- android - 当应用程序关闭时,WakefulBroadcastReceiver 不起作用
- react-native - React Native 0.59 -> 0.60 - 无法解析模块“NativeModules”
- mongodb - 数据库(Mongo)卷持久性 Docker Swarm
- python - 考虑到日期和时间值,如何从 csv 中创建 Python 字典?
- swift - 在 Swift 中检查对象是否是给定的泛型类型
- excel - 如何将现有的 IF 语句插入 ISBLANK 公式
- r - 如何根据下一个开始日期计算结束日期 R,并将数据重塑为日期计数/时间序列?