vendredi 13 décembre 2019

using dictionary instead of if statements

I am much familiar with python and now I started learning how to write codes as short and efficient as possible.

So, this is a piece of code that my teacher told me it is better not to have repeated blocks in my code.

He told me to use dictionaries instead of if statements but I couldn't figure out how to do it because there're for loops.

if day == '1':
    for elem in today:
        if city.lower() in elem or city.upper() in elem:
            print(today1[0])
            print(elem)
            cur_execute("INSERT INTO data VALUES(?, ?)", today1[0], elem)
            break

    else:
        print('data was not found')

if day == '2':
    for elem in tomorrow:
        if city.lower() in elem or city.upper() in elem:
            print(tomorrow1[0])
            print(elem)
            cur_execute("INSERT INTO data VALUES(?, ?)", tomorrow1[0], elem)
            break

    else:
        print('data was not found')

if day == '3':
    for elem in aftertomorrow:
        if city.lower() in elem or city.upper() in elem:
            print(aftertomorrow1[0])
            print(elem)
            cur_execute("INSERT INTO data VALUES(?, ?)", aftertomorrow1[0], elem)
            break

    else:
        print('data was not found')

Aucun commentaire:

Enregistrer un commentaire