Jaded-Coded
Jaded-Coded

Reputation: 13

Python: return between functions

I have one function that generates a list of strings, with 8 strings placed in it

def MajorScale(s):
    i = notes.index(s)
    t = i
    major_scale = []
    major_scale.append(notes[t])
    t = t+2
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    t = t+2
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    t = t+1
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    t = t+2
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    t = t+2
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    t = t+2
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    t = t+1
    if t >= 12:
        t = t-12
    major_scale.append(notes[t])
    print(major_scale)
    return major_scale

The next function calls MajorScale and relies on the list major_scale to work

def MajorChord(s):
    MajorScale(s)
    major_chord = []
    major_chord.append(major_scale[0])
    major_chord.append(major_scale[2])
    major_chord.append(major_scale[4])
    print(major_chord)

However, when I run the program, I get an error saying "major_scale is not defined"

I'm just not sure what I'm doing wrong at this point. If anyone can see the dumb mistake I'm making I'd love to find out.

Upvotes: 0

Views: 54

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114038

you could use a list comprehension to make you code more readable

def MajorScale(note):
    i = notes.index(note)
    offsets = [0, 2, 4, 6, 7, 9, 11, 13, 14]
    return [notes[(i+x)%12] for x in offsets]

def MajorChord(note):
    return MajorScale(note)[0:5:2]

Upvotes: 0

Steven Kryskalla
Steven Kryskalla

Reputation: 14669

Your function MajorScale returns a value, which you aren't saving to a variable in MajorChord.

def MajorChord(s):
    MajorScale(s)
    major_chord = []
    ...

So the return value is calculated and immediately thrown away. Put the return value into a variable like this in order to use it:

def MajorChord(s):
    major_scale = MajorScale(s)
    major_chord = []
    ...

Upvotes: 5

Related Questions