0

For example:

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)

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

then it should produce an image that is somewhat like the one above.

Jay Klope
  • 135
  • 2
  • 7

1 Answers1

4

This can be done using single-nested loops, multiplying a string, and the usage of the input function.

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)

There is an even more efficient way of printing the desired shape in terms of code and time, involving just one line. Replace the loop with this line:

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

Here is a test run of my program. The first way using a loop took 11908 microseconds, the second took just 4998 microseconds.

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
%%%%%%%%%%
%%%%%%%%%%
%%%%%%%%%%
  • 2
    `line = char * width` would also work, and be more efficient – jedwards Jun 04 '18 at 03:31
  • @jedwards Thanks. The edit states the existance of the more naive double-nested version – Ṃųỻịgǻňạcểơửṩ Jun 04 '18 at 03:32
  • 1
    More efficient: `"\n".join(char * width for _ in range(height))` – OneCricketeer Jun 04 '18 at 03:33
  • 2
    If you made that a list comprehension inside join -- e.g. `"\n".join([char * width for _ in range(height)])` -- instead of a generator expression, even more profit. (See [this post](https://stackoverflow.com/a/9061024/736937) from Python developer Raymond Hettinger). – jedwards Jun 04 '18 at 03:34
  • @jedwards Thanks for providing a more efficient alternative. I wonder why is `join` more efficient than loops? – Ṃųỻịgǻňạcểơửṩ Jun 04 '18 at 03:50
  • 1
    Appending to strings doesn't *really* append (strings are immutable, blah blah). It creates a *new* string and reassigns the output variable to it. Long loops will create many strings that will be used only once (the next iteration) and thrown away. `join()` is more efficient in that it will create a single string of appropriate length, then fill in the characters as necessary. Now 14 years old, [this site](https://waymoot.org/home/python_string/) benchmarked different string concatenation methods. You may try experimenting with them on your own if interested. – jedwards Jun 04 '18 at 03:57