【问题标题】:I want my python program to loop without using a function我希望我的 python 程序在不使用函数的情况下循环
【发布时间】:2018-11-19 01:02:23
【问题描述】:

我正在开发一款井字游戏。我已经完成了,但是如果用户要求它,我希望它再次循环。问题是当我把它放在一个主要功能下并缩进它时。一些变量不再定义,它不起作用!当它不在 main() 函数下时,它们会这样做。这些错误不会发生。有谁知道如何在不使用函数的情况下循环程序,或者帮助修复我的代码。例如:

def main():
    #My code here
#Ouput:
  File "CandT.py", line 205, in <module>
  main()
  File "CandT.py", line 203, in main
  run()
  File "CandT.py", line 188, in run
  runX()
  File "CandT.py", line 163, in runX
  askX()
  File "CandT.py", line 59, in askX
  check_stringX(x = s1)
  NameError: name 's1' is not defined

完整代码在这里:https://pastebin.com/iGcqGkRe

【问题讨论】:

  • 很抱歉没有将代码放在描述中。它有 200 多行,所以我想我会给出一个链接。
  • minimal reproducible example 请,尤其是minimal

标签: python python-3.x loops


【解决方案1】:

像这样创建一个while 循环。

def run()
    clear()
    #check_win() should return true if there is a winner or false if not
    while(check_win()==False): #if there is nobody win, continue this loop
        if turn == 0: # X's move
            runX()
            turn = 1 # the next turn will be O's
        elif turn == 1: # O's move
            runO()
            turn = 0 # the next turn will be O's

    #here after the loop, we check for the winner
    if(turn == 0):
        winner = O #because the last move is O's
    else:
        winner = X

def clear():
#reset all variables here

if __name__ == "__main__": #maybe you miss this line 
    while(True):
        play_again = int(input("play again? 1: OK, 0: No"))
        if play_again == 1:
            run()
        else:
            break

【讨论】:

  • 我尝试创建while True 循环,然后询问 if 语句来中断或继续循环,但它甚至不会在程序结束时询问。我不明白你的代码。你看到我链接的pastebin了吗?
  • 我查看了您的代码。我的代码可以替代您的run()。我将编辑我的代码并添加一些 cmets 以供您理解。
  • 谢谢,但我不需要修改check_win函数,我只需要程序最后重新启动,如果用户暗示的话。
  • 啊,好吧,我想念你的问题。我只是再次修改代码。
  • 你需要一个 clear() 函数来重置一切以便再次播放
猜你喜欢
  • 2021-11-01
  • 2016-12-14
  • 1970-01-01
  • 2013-01-22
  • 2011-04-10
  • 2017-08-01
  • 2017-11-22
  • 2016-03-09
  • 1970-01-01
相关资源
最近更新 更多