【问题标题】:Python: Return variables from one function to the other without rerunning the first functionPython:将变量从一个函数返回到另一个函数而不重新运行第一个函数
【发布时间】:2020-11-30 20:59:03
【问题描述】:

我是编程新手,也是 python 新手。我做了一些没有大问题的小项目(石头剪刀布和刽子手)。为了挑战自己,我试图在没有示例的情况下连续制作 4 场比赛。我创建了多个函数来代表游戏的一部分/步骤。

其中一个函数 (get_player_input) 负责处理用户输入。我要求用户选择一列。然后我检查多个东西(它是从 1 到 7 的 int 并且列不满吗?)。如果输入有效,我返回变量column_selectfree_places_column。我返回这些变量的原因是因为我想重用这些信息以使用第二个函数在游戏板上“放置一块”(place_piece

这是我迷路的地方。我可以通过以下方式使用这些变量:column_select, free_places_column = get_player_input() 但是这段代码重新运行函数get_player_input。导致用户被询问两次他想在哪一栏中放一块。

到目前为止我的代码:

# The game 4 in a row

# Define the game table with 6 rows and 7 columns
game_board = [[" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "]]


# print the game board
def printboard():
    print("|", game_board[0][0], "|", game_board[0][1], "|", game_board[0][2], "|", game_board[0][3], "|",
          game_board[0][4], "|", game_board[0][5], "|", game_board[0][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[1][0], "|", game_board[1][1], "|", game_board[1][2], "|", game_board[1][3], "|",
          game_board[1][4], "|", game_board[1][5], "|", game_board[1][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[2][0], "|", game_board[2][1], "|", game_board[2][2], "|", game_board[2][3], "|",
          game_board[2][4], "|", game_board[2][5], "|", game_board[2][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[3][0], "|", game_board[3][1], "|", game_board[3][2], "|", game_board[3][3], "|",
          game_board[3][4], "|", game_board[3][5], "|", game_board[3][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[4][0], "|", game_board[4][1], "|", game_board[4][2], "|", game_board[4][3], "|",
          game_board[4][4], "|", game_board[4][5], "|", game_board[4][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[5][0], "|", game_board[5][1], "|", game_board[5][2], "|", game_board[5][3], "|",
          game_board[5][4], "|", game_board[5][5], "|", game_board[5][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("  1   2   3   4   5   6   7")
    print()



def get_player_input():
    # set varaibles
    free_places_column = 0
    received_valid_input = False

    # Validate if player input is int and anywhere from 1 to 7. if not ask again
    while received_valid_input == False:
        try:
            column_select = int(input("Which column (1-7) do you want to drop the piece: "))
            if 0 < column_select < 8:
                for i in range(0, 6):
                    if game_board[i][column_select - 1] == " ":
                        free_places_column = free_places_column + 1
                if free_places_column == 0:
                    print("Column is full. please select an other column")
                else:
                    received_valid_input = True
            else:
                print('Please provide a number between 1 and 7')
        except ValueError:
            print('Wrong input. Please enter a number between 1 and 7')
        return column_select, free_places_column

def place_piece(player):
    column_select, free_places_column = get_player_input()
    print("Going to place a piece in column", column_select, "and row", free_places_column)
    if player == "A":
        game_board[free_places_column - 1][column_select - 1] = "X"
    else:
        game_board[free_places_column - 1][column_select - 1] = "O"


while True:
    printboard()
    get_player_input()
    place_piece("A")

当我运行这段代码时,结果如下:

|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
  1   2   3   4   5   6   7

Which column (1-7) do you want to drop the piece: 1
Which column (1-7) do you want to drop the piece: 1
Going to place a piece in column 1 and row 6
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
| X |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
  1   2   3   4   5   6   7

我已经在互联网上搜索并观看了有关将变量从一个函数重新调整到另一个函数的 YouTube 教程,但我还没有找到如何处理这个问题。我发现了一些可以解决我的问题的方法,但目前似乎没有一个方法可以解决:

  • 让我的变量全局化 --> 发现很多很多人告诉其他人不要这样做
  • 开始使用类 --> 对我来说仍然是一个难以掌握的概念。也有点想在不完全放弃迄今为止的选择的情况下解决这个问题
  • 抛弃函数,编写一大段代码 --> 努力学习使用函数

我还编写了一小段代码来消除一些复杂性。希望让我自己更容易理解:

def function1():
    a = 10
    b = 20
    print("We are in function 1")
    return a, b


def function2():
    a, b = function1()
    print(a, b)
    print("We are in function 2")


function1()
function2()

结果:

We are in function 1
We are in function 1
10 20
We are in function 2

谁能指出我正确的方向?

最好的问候

【问题讨论】:

  • 您能否更新最后的简单示例以显示您如何调用function2()
  • 我明白了。当 function2() 会为你调用时,不要自己调用 function1()。毕竟这是一种命令式编程语言。
  • 代码审查评论:您可以使用 for 循环显着简化 printboard() 函数。对于新程序员来说将是一个很好的练习:)
  • 我设法将它写成两个 for 循环。第二个 for 循环位于第一个 for 循环内。我试图在此处粘贴代码,但无法将其识别为代码。

标签: python function return


【解决方案1】:
# The game 4 in a row

# Define the game table with 6 rows and 7 columns
game_board = [[" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "]]


# print the game board
def printboard():
    print("|", game_board[0][0], "|", game_board[0][1], "|", game_board[0][2], "|", game_board[0][3], "|",
          game_board[0][4], "|", game_board[0][5], "|", game_board[0][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[1][0], "|", game_board[1][1], "|", game_board[1][2], "|", game_board[1][3], "|",
          game_board[1][4], "|", game_board[1][5], "|", game_board[1][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[2][0], "|", game_board[2][1], "|", game_board[2][2], "|", game_board[2][3], "|",
          game_board[2][4], "|", game_board[2][5], "|", game_board[2][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[3][0], "|", game_board[3][1], "|", game_board[3][2], "|", game_board[3][3], "|",
          game_board[3][4], "|", game_board[3][5], "|", game_board[3][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[4][0], "|", game_board[4][1], "|", game_board[4][2], "|", game_board[4][3], "|",
          game_board[4][4], "|", game_board[4][5], "|", game_board[4][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[5][0], "|", game_board[5][1], "|", game_board[5][2], "|", game_board[5][3], "|",
          game_board[5][4], "|", game_board[5][5], "|", game_board[5][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("  1   2   3   4   5   6   7")
    print()



def get_player_input():
    # set varaibles
    free_places_column = 0
    received_valid_input = False

    # Validate if player input is int and anywhere from 1 to 7. if not ask again
    while received_valid_input == False:
        try:
            column_select = int(input("Which column (1-7) do you want to drop the piece: "))
            if 0 < column_select < 8:
                for i in range(0, 6):
                    if game_board[i][column_select - 1] == " ":
                        free_places_column = free_places_column + 1
                if free_places_column == 0:
                    print("Column is full. please select an other column")
                else:
                    received_valid_input = True
            else:
                print('Please provide a number between 1 and 7')
        except ValueError:
            print('Wrong input. Please enter a number between 1 and 7')
        return column_select, free_places_column

def place_piece(player):
    column_select, free_places_column = get_player_input()
    print("Going to place a piece in column", column_select, "and row", free_places_column)
    if player == "A":
        game_board[free_places_column - 1][column_select - 1] = "X"
    else:
        game_board[free_places_column - 1][column_select - 1] = "O"
   

while True:
    printboard()
    place_piece("A")

我刚刚在您的 while True 循环中删除了一行。

当您在place_piece(player) 函数中调用get_player_input() 时,无需调用两次。

您希望这两个函数都以给定的顺序执行,但由于get_player_input() 嵌入在place_piece(player) 的代码中,您只需要执行place_piece(player)

使用您的简单示例:

def function1():
    a = 10
    b = 20
    print("We are in function 1")
    return a, b


def function2():
    a, b = function1()
    print(a, b)
    print("We are in function 2")

如果您只调用function2(),则输出为:

We are in function 1
10 20
We are in function 2

如果只调用function1(),则输出为:

We are in function 1

如果你调用function1()然后function2(),输出是:

We are in function 1
We are in function 1
10 20
We are in function 2

然后是function2(),然后是function1()

We are in function 1
10 20
We are in function 2
We are in function 1

要通过在代码中调用两个函数来获得所需的内容,您需要:

def function1():
    a = 10
    b = 20
    print("We are in function 1")
    return a, b


def function2(a,b):
    print(a, b)
    print("We are in function 2")

a, b = function1()

function2(a,b)

你会得到:

We are in function 1
10 20
We are in function 2

使用您的完整代码:

# The game 4 in a row

# Define the game table with 6 rows and 7 columns
game_board = [[" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "],
              [" ", " ", " ", " ", " ", " ", " "]]


# print the game board
def printboard():
    print("|", game_board[0][0], "|", game_board[0][1], "|", game_board[0][2], "|", game_board[0][3], "|",
          game_board[0][4], "|", game_board[0][5], "|", game_board[0][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[1][0], "|", game_board[1][1], "|", game_board[1][2], "|", game_board[1][3], "|",
          game_board[1][4], "|", game_board[1][5], "|", game_board[1][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[2][0], "|", game_board[2][1], "|", game_board[2][2], "|", game_board[2][3], "|",
          game_board[2][4], "|", game_board[2][5], "|", game_board[2][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[3][0], "|", game_board[3][1], "|", game_board[3][2], "|", game_board[3][3], "|",
          game_board[3][4], "|", game_board[3][5], "|", game_board[3][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[4][0], "|", game_board[4][1], "|", game_board[4][2], "|", game_board[4][3], "|",
          game_board[4][4], "|", game_board[4][5], "|", game_board[4][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("|", game_board[5][0], "|", game_board[5][1], "|", game_board[5][2], "|", game_board[5][3], "|",
          game_board[5][4], "|", game_board[5][5], "|", game_board[5][6], "|")
    print("- - + - + - + - + - + - + - -")
    print("  1   2   3   4   5   6   7")
    print()



def get_player_input():
    # set varaibles
    free_places_column = 0
    received_valid_input = False

    # Validate if player input is int and anywhere from 1 to 7. if not ask again
    while received_valid_input == False:
        try:
            column_select = int(input("Which column (1-7) do you want to drop the piece: "))
            if 0 < column_select < 8:
                for i in range(0, 6):
                    if game_board[i][column_select - 1] == " ":
                        free_places_column = free_places_column + 1
                if free_places_column == 0:
                    print("Column is full. please select an other column")
                else:
                    received_valid_input = True
            else:
                print('Please provide a number between 1 and 7')
        except ValueError:
            print('Wrong input. Please enter a number between 1 and 7')
        return column_select, free_places_column

def place_piece(player,column_select,free_places_column):
    print("Going to place a piece in column", column_select, "and row", free_places_column)
    if player == "A":
        game_board[free_places_column - 1][column_select - 1] = "X"
    else:
        game_board[free_places_column - 1][column_select - 1] = "O"
   

while True:
    printboard()
    column_select, free_places_column = get_player_input()
    place_piece("A",column_select, free_places_column)

输出:

Which column (1-7) do you want to drop the piece: 2
Going to place a piece in column 2 and row 6
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   | X |   |   |   |   |
- - + - + - + - + - + - + - -
| X | X | X |   |   |   |   |
- - + - + - + - + - + - + - -
  1   2   3   4   5   6   7

Which column (1-7) do you want to drop the piece: 3
Going to place a piece in column 3 and row 4
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   |   |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   | X |   |   |   |   |
- - + - + - + - + - + - + - -
|   |   | X |   |   |   |   |
- - + - + - + - + - + - + - -
| X | X | X |   |   |   |   |
- - + - + - + - + - + - + - -
  1   2   3   4   5   6   7

Which column (1-7) do you want to drop the piece: 

【讨论】:

  • 谢谢! ,这是解决我的问题的一个非常简单的方法。这确实大大降低了代码的可读性(无论如何对于我的初学者来说),因为之前的 while True 循环非常清楚地显示了游戏的步骤。使用此解决方案,似乎缺少步骤(实际上是由另一个函数调用的。有什么办法吗?
  • 好吧,我用您的第一个代码的“两次调用”版本进行了编辑。我希望这有效!
  • 是的,这绝对有效!可以肯定的是,在非编码语言中,这就是您的简单示例版本中正在发生的事情:我们说变量 A 和 B = 由函数 1 交付(通过返回)。然后我们说function2在这里你有变量A和B。去执行。对吗?
  • 是的,您将一个函数的“返回”值分配给变量 A 和 B。然后将 A 和 B 作为“参数”或另一个函数 (A,B) 传递。然后你从 func1 和返回线得到 A,B,从 func2 的返回中得到 C,用 A,B 馈送。
猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多