【问题标题】:Python: return between functionsPython:函数之间的返回
【发布时间】:2015-10-16 10:07:56
【问题描述】:

我有一个函数可以生成一个字符串列表,其中放置了 8 个字符串

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

下一个函数调用 MajorScale 并依赖于 major_scale 列表来工作

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)

但是,当我运行程序时,我收到一条错误消息,提示“major_scale 未定义”

我只是不确定此时我做错了什么。如果有人能看到我犯的愚蠢错误,我很想知道。

【问题讨论】:

  • 您使用了大写字母“M”。
  • 在什么情况下?我有一个名为 MajorScale 的函数和一个名为 major_scale 的列表,但它们是不同的东西。

标签: python arrays list return


【解决方案1】:

您的函数MajorScale 返回一个值,您没有将其保存到MajorChord 中的变量中。

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

所以返回值被计算出来并立即丢弃。将返回值放入这样的变量中以便使用它:

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

【讨论】:

【解决方案2】:

您可以使用列表推导使您的代码更具可读性

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2013-09-27
    • 1970-01-01
    相关资源
    最近更新 更多