'How to draw things without turtle in python
I was trying to draw a square using asterisks but this code was not working This is the code
def drawStar(numStars):
for x in range(0,numStars):
print("* ")
def menu():
# prompting the user to pick what they want drawn
input("Welcome to my draw shapes program ")
print("What would you like me to draw")
input(" Draw a Square (1)\n Draw a Rectangle (2)\n Draw a Rectangle (2)\n Draw an Arrow Head (3)\n Exit (4)")
def drawSquare():
width = int(input("What is the width of your square "))
for x in range(0,width):
drawStar(width)
drawSquare()
This is the output i kept getting
What is the width of your square 2
*
*
None
*
*
None
Solution 1:[1]
Rectangle:
m, n = 10, 10
for i in range(m):
for j in range(n):
print('*' if i in [0, n-1] or j in [0, m-1] else ' ', end='')
print()
Triangle:
m, n = 10, 10
for i in range(m):
for j in range(n):
print('*' if i in [j, m-1] or j == 0 else ' ', end='')
print()
Solution 2:[2]
print("* ")
The print() function by default prints a newline character after the data you provide. That is why you see each asterisk (and space) on a separate line. The print() function accepts a keyword argument named end to specify something else to print at the end.
You probably want something like this:
def drawStar(numStars):
for x in range(0,numStars):
print("* ", end='')
print()
or alternatively, you can use the feature of python that strings can be multiplied by a number:
def drawStar(numStars):
print( "* " * numStars )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maddy |
| Solution 2 | dsh |
