我正在尝试编写一个程序,它读取一个整数,并使用星号显示给定边长的填充菱形。例如,如果边长是4,程序应该显示
*
***
*****
*******
*****
***
*
这就是我要做的。它正在执行,但我似乎无法为程序正确地显示菱形形状而获得正确的空格。。。。
userInput = int(input("Please input side length of diamond: "))
if userInput > 0:
for i in range(userInput):
for s in range(userInput -3, -2, -1):
print(" ", end="")
for j in range(i * 2 -1):
print("*", end="")
print()
for i in range(userInput, -1, -1):
for j in range(i * 2 -1):
print("*", end="")
print()
谢谢你!
谢谢各位,我能够根据我得到的帮助来制定/修正我的代码。感谢大家的投入和帮助,所以社区!
这可能对您更有效:
用户输入的输出=6:
以下几点怎么样:
给予:
那么它是如何工作的呢?
首先我们需要一个计数高达
side
的计数器,然后再返回。没有什么能阻止您将两个范围列表附加在一起,因此:这给了你一个列表
[0, 1, 2, 1, 0]
从这里开始,我们需要为每一行计算出正确的空格和星号:
因此需要两个公式,例如对于
side=3
:使用Python的字符串格式,可以同时指定填充字符和填充宽度。这样就避免了使用字符串连接。
如果您使用的是Python 3.6或更高版本,则可以使用
f
字符串表示法:相关问题 更多 >
编程相关推荐