定义变量并执行变量python

时间:2014-11-16 17:58:51

标签: python variables

此代码存在问题。当我输入2来尝试执行whaleq()时,它会执行mathschallenge(),而我只想在用户输入1时执行。

任何人都可以看看并帮我解决这个问题吗?下面的代码与我在python idle中的代码完全相同。

print('The first thing you should think about doing is asking the locals if they have seen     anything!')

locallist = ['Ann-Marie, the butcher (1)',
             'Bella, the flourist (2)',
             'Caitlyn, the painter (3)',
             'Daniel, the scientist (4)',
             'Lauren, the Zookeeper (5)']
print(locallist)

localpick = int(input('Type the number of the local you want to talk to '))

def localx():
    if localpick == 1:
        mathschallenge()
    if localpick == 2:
        whaleq()

def mathschallenge():
    print('maths challenge yolo')
    quest = input('What is 10+10?')
    if quest == '20':
        print('correct')
    else:
        print('incorrect')

def whaleq():
    mammal = input('What is the largest mammal?')
    if mammal == 'whale':
        print('correct')
    else:
        print('incorrect')

input('Press the enter key to exit')

1 个答案:

答案 0 :(得分:0)

除了重新组织之外,代码对我来说很好,我感动了:

print('The first thing you should think about doing is asking the locals if they have seen     anything!')

locallist = ['Ann-Marie, the butcher (1)', 'Bella, the flourist (2)', 'Caitlyn, the 
painter         (3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
print(locallist)

localpick = int(input('Type the number of the local you want to talk to '))

从代码顶部到底部,并在上方添加localx()

input('Press the enter key to exit')

所以整个代码看起来像这样:

def localx():
    if localpick == 1:
        mathschallenge()
    if localpick == 2:
        whaleq()

def mathschallenge():
    print('maths challenge yolo')
    quest = input('What is 10+10?')
    if quest == '20':
        print('correct')
    else:
        print('incorrect')

def whaleq():
    mammal = input('What is the largest mammal?')
    if mammal == 'whale':
        print('correct')
    else:
        print('incorrect')


print('The first thing you should think about doing is asking the locals if they have seen     anything!')

locallist = ['Ann-Marie, the butcher (1)', 'Bella, the flourist (2)', 'Caitlyn, the painter     (3)', 'Daniel, the scientist (4)', 'Lauren, the Zookeeper (5)']
print(locallist)

localpick = int(input('Type the number of the local you want to talk to '))
localx()
input('Press the enter key to exit')

我希望这有帮助, 〜Bobbeh

注意:这是在python 3.4.2中测试的