(python)append用于列表,然后仅返回值(如果尚未使用)

时间:2012-05-03 09:05:28

标签: python list

标题几乎说明了一切。以下是我写的日本小型学习游戏的准系统。如果尚未在当前循环中打印假名,我只需打印假名。谁能看出我做错了什么?谢谢:))

#!/usr/bin/python
from os     import system as cmd
from random import choice as random
from time   import sleep
from sys    import platform

m = ["ma",  "mi",  "mu",  "me",  "mo"]
y = ["ya",         "yu",         "yo"]
n = ["n"]

def get_dict(group):
    if   group == 1:
        return m
    elif group == 13:
        return y
    elif group == 14:
        return n
    elif group == 15:
        return m + y + n

def clear():
    if "win" in platform: cmd("cls")
    if "lin" in platform: cmd("clear")

def get_kana():
    global kana
    return random(kana)

## Initiate      ##
kana = get_dict(15)
speed = speed()
clear()
print disp
print "Please get ready!..."
sleep(5)

def chk_used():
    global used_kana
    numlpo = 0
    while numlpo < 50:
        numlpo = numlpo + 1
        kana = get_kana()
        if kana not in used_kana:
            used_kana = used_kana.append(kana)
            return kana
            break

def main():
    used_kana = []
    while True:
        clear()
        print disp
        print "Please write the following kana: \n"
        print "    " + chk_used()
        sleep(3)

main()

1 个答案:

答案 0 :(得分:0)

一些事情:

chk_used中,您有一行:

used_kana = used_kana.append(kana)

只有一个问题。 list.append()返回None。每次执行此操作时,您都会将kana追加到used_kana,但之后您将used_kana的值设置为无。

used_kana.append(kana)

就足够了

您在函数

中定义used_kana
def main():
    used_kana = []

但是你试图在全球范围内引用它。 Python查找全局变量,但找不到它。

def chk_used():
    global used_kana

解决方案: 将用过的假名作为参数传递给chk_used()

def chk_used(usedCharacters):
    ...

def main():
    used_kana = []
        ...
        print "    " + chk_used(used_kana)

最后:

    if kana not in used_kana:
        used_kana.append(kana)
        return kana
        break #there's no reason for this break. the return on the line before exits the function, your code will never ever execute this line.