在Python中使用If-elif-else语句

时间:2014-02-10 05:25:12

标签: python

编写一个程序,询问用户颜色,线宽,线长和形状。形状应该是直线,三角形或正方形。使用乌龟图形绘制用户请求的形状,用户请求的大小,颜色,线宽和线长。例如,如果这些是用户对颜色,宽度,线长和形状的选择。

输出应如下所示: 什么颜色?蓝色 什么线宽? 25 什么线长? 100 线,三角形还是方形?三角形

我的代码:

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!')

此外,我的输出只会持续到第一个“if”语句,之后不会继续。它接受前三个问题的用户,但无论第四个问题的答案是什么,它总是一行。

2 个答案:

答案 0 :(得分:1)

首先 if 被解释为

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

因为非空迭代在布尔表达式中被解释为 True ,所以整个表达式总是 True - 如果不是第一个组件,那么第二个 您可以将其重写为

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

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

应对所有if表达式

应用相同的更改

答案 1 :(得分:0)

你在做什么:

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

这意味着:

shape=='line' or True or True

因为对象是 truthy ,可以通过输入以下内容在REPL上轻松测试:

if 'line': print 'true'

您需要做什么:

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

最好的办法是一次覆盖所有基地:

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

这是一个更加动态的草编:

在这种情况下,您甚至不需要任何if语句!

def line():
    print 'Line selected!'

def square():
    print 'Square selected'

def triangle():
    print 'Triangle selected'

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

对于对象的动态调度,请使用:

getattr(module,method_name);
  

警告:谨慎使用时会很优雅,使用太多时会变得完全无法维护