J.W J.W - 17 days ago 4
Python Question

python 3.5 shortening and compressing repeated codes

so im trying to create this program on python, right now i have this:

for word in problem.split():
if word in appledata[2]:
print(appledata[3])
func()
elif word in appledata[4]:
print(appledata[5])
func()
elif word in appledata[6]:
print(appledata[7])
func()
elif word in appledata[8]:
print(appledata[9])
func()
elif word in appledata[10]:
print(appledata[11])
func()
elif word in appledata[12]:
print(appledata[13])
func()
elif word in appledata[14]:
print(appledata[15])
func()


is there a better more efficient way to write this, sorry if i sound like a complete noob, im quite new to python.

Answer

You could do something like this:

for word in problem.split():
    for i in range(2, 15, 2):
        if word in appledata[i]:
            print(appledata[i+1])
            func()
            break

The for loop will start the counter i at 2, adding 2 every round until it reaches 15.

If the word is in appledata[i], we make sure to break the for loop. If we didn't, it would be the same as changing all your elifs for ifs.

Comments