检查Python输入是否包含特定单词

时间:2017-02-07 13:23:50

标签: python

这只是INPUT / OUTPUT编码 做什么:你输入" Area"或"周长"或"卷"它会询问某些字符串并进行计算。此代码检查长度以及输入是否包含数字,如果超过长度则会打印错误。

目标:如果" Area"," perimeter"或"卷"在输入中,继续下一个功能..

print ("This program will find the area, perimeter and volume of the Rectangle!")

    find = input ("Type in one to calculate "area", "perimeter"  and volume": ")

    if len(find) == 4 and find.isalpha():   #This is area, people can type 4 chars and can get away with it, is there a way to fix it?
        w = int (input ("What is the Width of the rectangle: "))
        l = int (input ("What is the Length of the rectangle: "))
        a = w*l
        ans = "The area of the rectangle is %s units!"
        print (ans%(a))
    elif len (find) == 6 and  find.isalpha():   # This is Volume
        w = int(input ("What is the Width of the rectangle: "))
        l = int(input ("What is the Length of the rectangle: "))
        h = int(input ("What is the Height of the rectangle: "))
        v = l*w*h
        ans = "The volume of the rectangle is %s units!"
        print (ans%(v))
    elif len (find) == 9 and find.isalpha():  #This is  Perimeter
        w = int (input ("What is the Width of the rectangle: "))
        l = int (input ("What is the Length of the rectangle: "))
        p = 2*(l+w)
        ans = "The primeter of the rectangle is %s units!"
        print (ans%(p))
    else:
        print ("You spelled area, perimeter or volume wrong, or what you typed in includes NUMBERS!")

1 个答案:

答案 0 :(得分:5)

您只需比较字符串,而不是用长度检查它。
例如:

if find == "area":    #to check if the user input is "area"

等等..对于周长和体积。