【问题标题】:Python Functions called before referencing error coming up?在出现引用错误之前调用的 Python 函数?
【发布时间】:2017-08-02 11:37:58
【问题描述】:

我对以下代码有疑问:

#1/usr/bin/env python3
import random
financialPoints = 0
debatePointsT = 0
marginalCheck = random.randint(0,1)
debatePointsTO = 0
Choice = random.randint(0,2)

popularity = 0
name = input("What is your first name")
nameSur = input("What is your surname")

print("This is the political campaign simulator")
chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")

if chosenParty == "C":
    print("You have been elected as a councillor by your fellow peers.")
    marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
    if marginality == "marginal":
        if marginalCheck == 0:
            print("You have failed to be elected to parliament")
        else:
            print("You are duly elected the MP for your constituency!")
            campaignT()
    else:
        campaignT()





def debateT():

    #My Code
    if marginality == "safe":
          campaignT()


def campaign():
    #My Code
    if elected == True:
           debateT()

它告诉我在引用它之前我已经调用了一个函数,但我需要它在那里以便我运行代码的另一部分,如上所示。在 python 中,我有没有办法让函数并排运行,或者类似的东西?

【问题讨论】:

  • “我需要它在那里”是什么意思?大部分代码是给你的,你只被允许/期望填写函数体吗?
  • @Anish,您在底部定义了一个函数 campaign,但在 if-else 块中调用了函数 campaignT。除此之外,将函数放在文件的开头。
  • 我需要它在那里,这样我才能使用变量

标签: python function


【解决方案1】:

函数定义必须在引用它的代码之前。

debateT()campaign() 移至文件顶部。

【讨论】:

    【解决方案2】:

    将您定义的函数移动到文件顶部,例如:

    #1/usr/bin/env python3
    import random
    financialPoints = 0
    debatePointsT = 0
    marginalCheck = random.randint(0,1)
    debatePointsTO = 0
    Choice = random.randint(0,2)
    
    def debateT():
    
    #My Code
        if marginality == "safe":
            campaignT()
    
    
    def campaign():
        #My Code
        if elected == True:
            debateT()
    
    popularity = 0
    name = input("What is your first name")
    nameSur = input("What is your surname")
    
    print("This is the political campaign simulator")
    chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")
    
    if chosenParty == "C":
        print("You have been elected as a councillor by your fellow peers.")
        marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
        if marginality == "marginal":
            if marginalCheck == 0:
                print("You have failed to be elected to parliament")
            else:
                print("You are duly elected the MP for your constituency!")
                campaignT()
        else:
            campaignT()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2019-10-11
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多