IS there a way to simplify this python code?

  • A+
Category:Languages

I am still in the "any technology sufficiently advanced..." phase of learning to program. This code seems clunky, and hard to update if needed. Is there a better way to go about this? It just looks completely bonkers to me, but it works... so yay?

It takes a variable from TKinter radial 1-16, and uses it select the grade1 ect variable. The grade1 variable then link to sheet names on gspread.

def go():     subject = v.get()     if  subject == 1:         subject = grade1     elif  subject == 2:         subject = grade2         elif  subject == 3:         subject = grade3     elif  subject == 4:         subject = grade4       elif  subject == 5:         subject = grade5     elif  subject == 6:         subject = grade6     elif  subject == 7:         subject = grade7     elif  subject == 8:         subject = grade8     elif  subject == 9:         subject = grade9     elif  subject == 10:         subject = grade10         elif  subject == 11:         subject = grade11     elif  subject == 12:         subject = grade12      elif  subject == 13:         subject = grade13     elif  subject == 14:         subject = grade14     elif  subject == 15:         subject = grade15     elif  subject == 16:         subject = grade16 

 


Do not keep 16 different variables for grade**! Use one list:

grades = [1, 2, 3, ...]  # or whatever your values are 

Then all you need to do is:

subject = grades[v.get() - 1] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: