【问题标题】:Execution doesn't go on the next fuction执行不继续下一个功能
【发布时间】:2022-01-08 10:57:45
【问题描述】:

我遇到了一个练习,要求我设计一个尺寸为NxM 的门垫,其中N奇数M 等于N*3,顺便可以看到there 附有完整的练习说明。

为此,我编写了以下代码:

door_mat_length = int(input())
door_mat_width = door_mat_length * 3
string = '.|.'
welcome = 'WELCOME'

for i in range(1, int((door_mat_length + 1) / 2)):
    string_multiplier = string * (i + (i - 1))
    print(string_multiplier.center(door_mat_width, '-')) 

print(welcome.center(door_mat_width, '-'))

for i in range(int((door_mat_length + 1) / 2), 1):
    string_multiplier = string * (i + (i - 1))
    print(string_multiplier.center(door_mat_width, '-'))

但是程序在中间的 print 命令处停止,没有迭代下一个函数。我该如何解决这个问题?提前致谢。

【问题讨论】:

标签: python function


【解决方案1】:

范围步长默认为 1。

Python range doc

在文档中,它说 For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop. 所以你的第二个 for 循环范围返回一个空范围。

喜欢

for i in range(5, 1):
    print(i)

不要打印任何东西。要解决这个问题,您必须通过一个负步骤以使其下降。喜欢:

for i in range(5, 1, -1):
    print(i)

打印出来

5
4
3
2

因此,如果您想使用范围向下移动,请确保传递一个步长值。

for i in range(int((door_mat_length + 1) / 2) - 1, 0, -1):

【讨论】:

  • 谢谢!我已经明白问题出在哪里了
【解决方案2】:

将您的代码更改为:

door_mat_length = int(input())
door_mat_width = door_mat_length * 3
string = '.|.'
welcome = 'WELCOME'

for i in range(1, int((door_mat_length + 1) / 2)):
    string_multiplier = string * (i + (i - 1))
    print(string_multiplier.center(door_mat_width, '-'))

print(welcome.center(door_mat_width, '-'))

for i in reversed(range(1,int((door_mat_length + 1) / 2) )):
    string_multiplier = string * (i + (i - 1))
    print(string_multiplier.center(door_mat_width, '-'))

输入:10

输出:

-------------.|.--------------
----------.|..|..|.-----------
-------.|..|..|..|..|.--------
----.|..|..|..|..|..|..|.-----
-----------WELCOME------------
----.|..|..|..|..|..|..|.-----
-------.|..|..|..|..|.--------
----------.|..|..|.-----------
-------------.|.--------------

【讨论】:

  • 谢谢!据我了解,我忘记插入步长值
猜你喜欢
  • 2022-12-01
  • 2017-04-29
  • 2012-02-26
  • 2020-01-15
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多