-4

Write a program that asks the user for a color, a line width, a line length and a shape. The shape should be either a line, a triangle, or a square. Use turtle graphics to draw the shape that the user requests of the size, color, line width and line length that the user requests. For example, if these are the user choices for color, width, line length and shape.

The output should look like this: what color? blue what line width? 25 what line length? 100 line, triangle or square? triangle

My code:

import turtle
colour=input('What color? ')
width=int(input('What width? '))
length=int(input('What line length? '))
shape=input('line, triangle, or square? ')

if shape=='line' or 'Line' or 'LINE':
    t=turtle.Turtle()
    t.pendown()
    t.color(colour)
    t.pensize(width)
    t.forward(length)
elif shape=='triangle' or 'Triangle' or 'TRIANGLE':
    t=turtle.Turtle()
    t.pendown()
    t.color(colour)
    t.pensize(width)
    t.forward(length)
    t.left(120)
    t.forward(length)
    t.left(120)
    t.forward(length)
elif shape=='square' or 'Square' or 'SQUARE':
    t=turtle.Turtle()
    t.pendown()
    t.color(colour)
    t.pensize(width)
    t.forward(length)
    t.left(90)
    t.forward(length)
    t.left(90)
    t.forward(length)
    t.left(90)
    t.forward(length)
else:
    print('Command not recognized, try again!')

Also, my output only goes until the first "if" statement, it does not proceed after that. It accepts the user for the first three questions, but no matter what the answer for the 4th question, it will always be a line.

some1
  • 5
  • 5

2 Answers2

1

First of your if 's is interpreted as

if (shape=='line') or 'Line' or 'LINE':

since non-empty iterables are interpreted as True in boolean expressions, the whole expression is always True - if not by the first component, then by the second You may rewrite it as

if shape in ('line', 'LINE', 'Line'):

or

if shape.lower() == 'line':

The same changes should be applied to all your if expressions

volcano
  • 3,578
  • 21
  • 28
0

What you are doing:

shape=='line' or 'Line' or 'LINE'

What this translates to is:

shape=='line' or True or True

Because an object is truthy, which can easily be tested at the REPL by entering:

if 'line': print 'true'

What you need to be doing:

shape=='line' or shape=='Line' or shape=='LINE'

Best way is to cover all the bases at once:

if re.match('line', shape.strip(), re.IGNORECASE):

Here is a strawman for doing it even more dynamically:

You don't even need any if statements in this case!

def line():
    print 'Line selected!'

def square():
    print 'Square selected'

def triangle():
    print 'Triangle selected'

globals()[shape.strip().lower()]()

For dynamic dispatch on objects use:

getattr(module,method_name);

Warning: this can be elegant when used sparingly, when used too much it just becomes completely unmaintainable