if语句在python中。不会阻止其他if语句起作用

时间:2015-06-22 07:35:35

标签: python if-statement turtle-graphics

import turtle

print("Give me a shape")
shape = input()

if shape == "pentagon" or "Pentagon":
    for i in range(5):
        turtle.fd(100)
        turtle.rt(72)

if shape == "triangle" or "Triangle":
    for i in range(3):
        turtle.fd(100)
        turtle.rt(120)

if shape == "square" or "Square":
    for i in range(4):
        turtle.fd(100)
        turtle.rt(90)

if shape == "hexagon" or "Hexagon":
    for i in range(6):
        turtle.fd(100)
        turtle.rt(60)

if shape == "circle" or "Circle":
    turtle.circle(100)

else:
    print("Not a shape")

3 个答案:

答案 0 :(得分:3)

您的支票shape == "pentagon" or "Pentagon"不正确且始终为True,因为检查字符串始终返回True,例如bool("Pentagon")True"pentagon" == "pentagon"的检查为True 您应该使用shape in ["pentagon", "Pentagon"]或更好shape.lower() == "pentagon"

import turtle

print("Give me a shape")
shape = input().lower()  
if shape == "pentagon": 
    for i in range(5): 
        turtle.fd(100) 
        turtle.rt(72)    
elif shape == "triangle": 
    for i in range(3): 
        turtle.fd(100) 
        turtle.rt(120)    
elif shape == "square": 
    for i in range(4): 
        turtle.fd(100) 
        turtle.rt(90)    
elif shape == "hexagon": 
    for i in range(6): 
        turtle.fd(100) 
        turtle.rt(60)    
elif shape == "circle": 
    turtle.circle(100)    
else: 
    print("Not a shape")

答案 1 :(得分:1)

您的陈述,如

// Workaround for iOS below 8.3: LAErrorDomain constant can't be found and leads to a crash
NSString *const MyLAErrorDomain = @kLAErrorDomain;

评估为shape == "pentagon" or "Pentagon" True

您需要将"Pentagon"与两个值进行比较:

shape

答案 2 :(得分:0)

你应该在第一个if之后使用elif语句。或者,您可以使用'.lower'将输入转换为小写。这意味着您不必拥有或在声明中。例如,它也会接受三角形。

import turtle

print("Give me a shape")
shape = input()

if shape == "pentagon" or shape == "Pentagon":
    for i in range(5):
        turtle.fd(100)
        turtle.rt(72)

elif shape == "triangle" or shape == "Triangle":
    for i in range(3):
        turtle.fd(100)
        turtle.rt(120)

elif shape == "square" or shape == "Square":
    for i in range(4):
        turtle.fd(100)
        turtle.rt(90)

elif shape == "hexagon" or shape == "Hexagon":
    for i in range(6):
        turtle.fd(100)
        turtle.rt(60)

elif shape == "circle" or shape == "Circle":
    turtle.circle(100)

else:
    print("Not a shape")