如何在python shell中绘制“形状”?

时间:2018-06-04 03:25:21

标签: python

例如:

Enter the character you want to use to draw your square: *
Enter the width of your square: (insert value here)
Enter the height of your square: (insert value here)

*****
*****
*****

然后它应该产生一个有点像上面的图像。

1 个答案:

答案 0 :(得分:4)

这可以使用单嵌套循环,乘以字符串以及使用input函数来完成。

char = input("Enter the character you want to use to draw your square: ")
width = int(input("Enter the width of your square: (insert value here): "))
height = int(input("Enter the height of your square: (insert value here): "))

for h in range(0,height):
    print(char * width)

在代码和时间方面打印所需形状的效率更高,只涉及一行。用这一行替换循环:

print("\n".join([char * width for _ in range(height)]))

这是我的程序的测试运行。使用循环的第一种方式花了11908微秒,第二种方式花了4998微秒。

Enter the character you want to use to draw your square: %
Enter the width of your square: (insert value here): 10
Enter the height of your square: (insert value here): 3
%%%%%%%%%%
%%%%%%%%%%
%%%%%%%%%%