从1到8猜数字

Jan*_*oe2 0 python if-statement python-2.7 python-3.x

我的程序需要通过只询问3个问题来猜测用户的号码(从1到8).它正确地打印了前两个问题,但是当我按Enter键进入第三个问题时,它只打印我做的最后一个输入.如何使所有输入(是或否)小写?

# Simple Expert System
#firstQuestion = prstr(firstQuestion.lower()) 

print("Think of a number between 1 and 8.")

firstQuestion = (raw_input("Is it an even number? "))
secondQuestion = "Is it less than or equal to 4? "
thirdQuestion = "Is it less than or equal to 3? "
fourthQuestion = "Is it less than 3? "
fifthQuestion = "Is it greater than 6? "
sixthQuestion = "Is it greater than 5? "
seventhQuestion = "Is it less than 2? "




if firstQuestion == "yes":
    print(raw_input(secondQuestion))
elif firstQuestion == "no":
    print(raw_input(thirdQuestion))
elif secondQuestion == "yes":
    print(raw_input(fourthQuestion))
elif secondQuestion == "no":
    print(raw_input(fifthQuestion))
elif thirdQuestion == "no":
    print(raw_input(sixthQuestion))
elif thirdQuestion == "yes":
    print(raw_input(seventhQuestion))

elif fourthQuestion == "yes":
    print("Your number is 2")
elif fourthQuestion == "no":
    print("Your number is 4")

elif fifthQuestion == "yes":
    print("Your number is 8")
elif fifthQuestion == "no":
    print("Your number is 6")   

elif sixthQuestion == "yes":
    print("Your number is 7")
elif sixthQuestion == "no":
    print("Your number is 5")       

elif seventhQuestion == "yes":
    print("Your number is 1")
elif seventhQuestion == "no":
    print("Your number is 3")   
Run Code Online (Sandbox Code Playgroud)

acd*_*cdr 6

考虑到你的程序对于较大的数字根本不能很好地扩展:如果你必须猜测1到1000之间的数字,你将不得不编写大量的代码.

相反,请考虑循环遍历您可能获得的所有范围:

lower_limit = 1
upper_limit = 100

while lower_limit < upper_limit:
    middle = int(0.5 * (lower_limit + upper_limit))
    check = raw_input("Larger than " + str(middle) + "? ")
    if check.lower().startswith("y"): # Accept anything that starts with a Y as "yes"
        lower_limit = middle + 1
    else:
        upper_limit = middle

print(lower_limit)
Run Code Online (Sandbox Code Playgroud)