WhoGivesAFlux WhoGivesAFlux - 3 months ago 15
Python Question

How to condense multiple different if statements (Python)

I am making a quiz in the style of 20 Questions. It uses a text file to create a dictionary with codes relating to answers. At the moment it only has 5 questions which is no where near enough to be accurate with 'guesses' but already it is looking messy and hard to understand

CODES.txt Example Contents:

a1000,A Book

a1111,A Saucepan

Code:

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()


How would i make the question segment, the If-Statements easier to read/understand. Currently i have loads of embedded ones and it only consists of 5 questions each with 2/3 answers.

Answer

I will try to give you some thoughts but not solve your problem directly:

  • Think about what you can put into a separate function. This would make sense for statements that are repeated several times.
  • You can very easily return strings from Python functions. Then you can use the returned strings as keys for a dictionary.
  • Also there is the possibility to return functions from other functions as everything is an object in Python.

    For example Q4 = input("Is it smaller than your head: ") could be turned into a statement like obj_size = ask_size() with outputs "small", "big".

I hope that helps you :)