如何压缩多个不同的if语句(Python)

时间:2016-08-22 15:12:21

标签: python python-3.x if-statement dictionary

我正在以20个问题的方式进行测验。它使用文本文件来创建包含与答案相关的代码的字典。目前它只有5个问题,这些问题与猜测相近并不准确无误。但它已经看起来很乱,很难理解

CODES.txt示例内容:

a1000,A Book

a1111,A Saucepan

代码:

File = open("CODES.txt","r")
CODES = { }

for line in File:
    x = line.split(",")
    a = x[0]
    b = x[1]
    c = len(b)-1
    b = b[0:c]
    CODES[a] = b

print("Think of anything: \n")

Q1 = str(input("Is it a) An Object, b) A Person, c) A Film: "))
if Q1 == "a":
    Q2 = input("Is it hard: ")
    if Q2 == "0":
        Q3 = input("Is it light: ")
        if Q3 == "0":
            Q4 = input("Is it smaller than your head: ")
            if Q4 == "0":
                Q5 = input("Is it square: ")
            elif Q4 == "1":
                Q5 = input("Is it circular: ")
        elif Q3 == "1":
            Q4 = input("Is it bigger than your head: ")
            if Q4 == "0":
                Q5 = input("Is it square: ")
            elif Q4 == "1":
                Q5 = input("Is it circular: ")
    elif Q2 == "1":
        Q3 = input("Is it heavy: ")
        if Q3 == "0":
            Q4 = input("Is it smaller than your head: ")
            if Q4 == "0":
                Q5 = input("Is it square: ")
            elif Q4 == "1":
                Q5 = input("Is it circular: ")
        elif Q3 == "1":
            Q4 = input("Is it bigger than your head: ")
            if Q4 == "0":
                Q5 = input("Is it square: ")
            elif Q4 == "1":
                Q5 = input("Is it circular: ")

CCODE = str(Q1+Q2+Q3+Q4+Q5)

if CCODE in CODES:
    print("You are thinking of " + CODES[CCODE])
else:
    NV = str(input("You have outsmarted me. What were you thinking of: "))
    File = open("CODES.txt","a")
    File.write((CCODE+","+NV+"\n"))
    File.close()

我如何制作问题段,If-Statements更容易阅读/理解。目前我有很多嵌入式的,只有5个问题,每个问题都有2/3个答案。

1 个答案:

答案 0 :(得分:1)

我会尝试给你一些想法,但不能直接解决你的问题:

  • 想想你可以把它放到一个单独的功能中。这对于重复多次的语句是有意义的。
  • 您可以非常轻松地从Python函数返回字符串。然后,您可以使用返回的字符串作为字典的键。
  • 还有可能从其他函数返回函数,因为一切都是Python中的对象。

    例如,<script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>可以变成一个类似的语句 输出Q4 = input("Is it smaller than your head: ")obj_size = ask_size()的{​​{1}}。

我希望能帮到你:)。

相关问题