我要“编写一个 python 程序,提示用户输入一个正整数 n。然后该程序打印一个包含 n 行和 2*n 列的空心矩形。例如,输入 3 将输出:”
******
* *
******
我的代码是:
n=int(input('Please enter a positive integer between 1 and 15: '))
for col in range(n):
for row in range(n):
print('*' if col in(0,(2*n)+1) or row in(0,n+1) else ' ', end=' ')
print()
但我的输出看起来根本不像我需要的;它就像一个空心盒子的上半部分和左半部分。此外,我没有得到我需要的双列。我究竟做错了什么?
编辑:谢谢大家的帮助!给了我很多见解并且非常有帮助。我将我的代码修改为以下内容,并且效果很好:
>n=int(input('Please enter a positive integer between 1 and 15: '))
>for row in range(n):
> for col in range(2*n):
> print('*' if row in(0,n-1) or col in(0,(2*n)-1) else ' ', end=' ')
> print()
特别感谢用户2357112;你让我清楚地意识到我犯了什么错。
我的解决方案:
# Response to StackOverflow post:
# Making a hollow box in Python
# The multiplication operator (*) is the same as repeated
# concatenation when applied to strings in Python.
# I solved the problem by creating an array with N elements
# and gluing them together (str.join(array)) with newline
# characters.
# I trust you're already familiar with string formatting and
# concatenation, but in case you're not, please feel free to
# ask for clarification.
def main():
n = int (input("Enter an integer between 1 and 15"))
box = "\n".join(["*"*(2*n)] + ["*%s*" % (" "*(2*n-2))]*(n-2) + ["*"*(int(n>1)*2*n)])
print (box)
if __name__ == '__main__':
main()
input() # Prevents the console from closing immediately
至于你的解决方案。在我看来,循环条件被搞乱了;列循环和行循环的顺序相反,列循环中 range() 的参数应该是 2*n (因为这是与每行相交的列数)。您还应该再次查看第一个打印语句中的条件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)