-2

I am trying to learn what notes are where on the guitar, so I want to be able to type in what the string is tuned to and what fret I am playing and have the program tell me what note it is or type in the note and get back all the different places I can play it.

So far, I have a program that tells me what the note is based on the string and fret but I just wrote it the long way and it takes a lot of processing power. Based on what the user types in for what the string is tuned to, it opens a function for that string which asks what fret is being used, then based on the fret it runs one of the many elifs that I individually typed out.

For example:

elif fret == '3':
    print('That note is E')

I know there's a way to do it with not nearly as much code, but I'm really new to programming clearly and can't quite come up with the logic.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Tanner
  • 11
  • 3
  • 1
    The canonical replacement for lots of `elif`s is a [`dict`](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) e.g. `{'3': 'E', ...}`. – jonrsharpe Nov 19 '14 at 22:21
  • As others have hinted at, you're trying to solve a "data question" with a "programming answer"... Since D strings and F-sharps won't change anytime soon, you can pre-calculate the answers to _all_ possible questions and save them in a data structure (bgporter's pair of `dict`s) or a file (probably `notes.json` or something). Then the only _programming_ part of the job is taking user questions, looking up the pre-calculated answer, and spitting it out. Much easier. – Kevin J. Chase Nov 20 '14 at 00:06

1 Answers1

4

Build a pair of dicts that map note names to pitch numbers and back, and you can build a simple function to do this, like:

NOTES = {"C" : 0, "C#" : 1,  "D": 2, "D#" : 3, "E": 4, "F": 5, 
   "F#" : 6, "G":  7, "G#" : 8, "A": 9, "A#" : 10, "B": 11}


NAMES = dict([(v, k) for (k, v) in NOTES.items()])


def GetNote(stringNote, fretNum):
   baseNote = NOTES[stringNote]
   fretNoteNum = (baseNote + fretNum) % 12
   return NAMES[fretNoteNum]

>>> GetNote("E", 0)
'E'
>>> GetNote("E", 1)
'F'
>>> GetNote("A", 7)
'E'
>>> GetNote("G", 6)
'C#'
bgporter
  • 35,114
  • 8
  • 59
  • 65