0

我正在创建一个程序,您可以在其中输入密码,然后就可以玩游戏了。在我的一个定义riddle()中,它告诉我d1, d2, d3,d4d5在定义之前被引用,但据我所知,它们已经被定义。此外,当这仍然有效时,我试图让它解决一个任务会让它说它已经完成,但是当我完成一个时,它仍然说 1 不完整等等。我需要解决这两个问题。

def riddle():
    d1 = 'n'
    d2 = 'n'
    d3 = 'n'
    d4 = 'n'
    d5 = 'n'
    def compcheck():
        print('There are 5 tasks to complete. Enter a number to see task.')
        if d1 in ('y'):
            t1 = 'Completed.'
        if d2 in ('y'):
            t2 = 'Completed.'
        if d3 in ('y'):
            t3 = 'Completed.'
        if d4 in ('y'):
            t4 = 'Completed.'
        if d5 in ('y'):
            t5 = 'Completed.'
        if d1 in ('n'):
            t1 = 'Incomplete.'
        if d2 in ('n'):
            t2 = 'Incomplete.'
        if d3 in ('n'):
            t3 = 'Incomplete.'
        if d4 in ('n'):
            t4 = 'Incomplete.'
        if d5 in ('n'):
            t5 = 'Incomplete.'
        print ('1 is ' + t1)
        print ('2 is ' + t2)
        print ('3 is ' + t3)
        print ('4 is ' + t4)
        print ('5 is ' + t5)
    def solve():
        compcheck()
        if d1 and d2 and d3 and d4 and d5 in ['y']:
            print ('The password is 10X2ID 4TK56N H87Y8G.')
        tasknumber = input().lower()
        if tasknumber in ('1'):
            print('Fill in the blanks: P_tho_ i_ a c_d_ng lan_u_ge. (No spaces. Ex: ldkjfonv)')
            task1ans = input().lower()
            if task1ans in ['ysoinga']:
                d1 = 'y'
            solve()
        if tasknumber in ('2'):
            print('Is the shape of a strand of DNA: A): a Lemniscate, B): a Hyperboloid, C): a Double Helix, or D): a Gömböc.')
            task2ans = input().lower()
            if task2ans in ['c']:
                d2 = 'y'
            solve()
        if tasknumber in ('3'):
            print ('What is the OS with a penguin mascot?')
            task3ans = input().lower()
            if task3ans in ('linux'):
                d3 = 'y'
            solve()
        if tasknumber in ('4'):
            print('')
        if tasknumber in ('5'):
            print('')
    solve()
4

1 回答 1

6

在函数内部,solve您正在分配、等变量。这使得这些变量成为该函数的局部变量,但您也尝试在开始时测试它们的内容。这就是您的错误的来源。d1d2

您必须声明这些变量nonlocal

def solve():
    nonlocal d1, d2, d3, d4, d5

您可能想改用列表:

d = ['n'] * 5
t = ['Incomplete' if x == 'n' else 'Complete' for x in d]
for i, x in enumerate(t, 1):
    print('{} is {}'.format(i, x)

if tasknumber == '1':
    print('Fill in the blanks: P_tho_ i_ a c_d_ng lan_u_ge. (No spaces. Ex: ldkjfonv)')
    answer = input().lower()
    if answer == 'ysoinga':
        d[0] = 'y'
    solve()

这具有额外的优势,现在您也不再需要nonlocal关键字;您不再分配给. 中包含索引d,而是分配给. 您正在 mutating ,而不是用另一个值替换它。 dd

其他备注;该行:

if d1 and d2 and d3 and d4 and d5 in ['y']:

也不行;我认为你的意思是:

if d1 == 'y' and d2 == 'y' and d3 == 'y' and d4 == 'y' and d5 == 'y':

但列表可能是:

if all(x == 'y' for x in d):

也许

if d == ['y'] * 5:

测试特定字符串时,使用== 'value to test for',而不是in ['value to test for']。后者有效,但必须做件事;遍历列表并测试每个元素的相等性。==直接进行平等测试。

于 2013-05-27T19:35:49.443 回答