You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编程中if语句内的自定义函数无法正常启动执行问题

直接原因

你代码里触发不了if分支的核心问题是:input() 函数返回值为字符串类型,你将其和整数1做全等判断,结果永远为False,所以if内的代码永远不会执行,函数自然不会启动。

其他需要修复的问题

  • 代码开头缺少依赖导入:你用到的sleep、randrange需要先从对应模块导入,否则运行会报错
  • 猜数字游戏的for i in range(5)逻辑错误:当前写法会循环5次反复生成随机数、重置尝试次数,仅保留最后一次的随机数和用户输入,完全不符合功能预期
  • else分支仅定义了TicTacToe函数,没有编写调用逻辑,即使进入else分支也不会运行井字棋代码

修复后可运行代码

from time import sleep
from random import randrange

print("Please choose from one of the following: \n")
print("1. Tic-Tac-Toe. \n")
print("2. Number Guessing Game. \n")
# 把输入转成整数适配判断逻辑
playerQuestion = int(input(""))
print("You have selected game " + str(playerQuestion) + "! Starting the game up. . . ")
sleep(2)

def guessingGame():
    computerNumber = randrange(100)
    playerGuess = int(input("I am thinking of a number... Please make your first guess! "))
    tries = 1
    while playerGuess != computerNumber:
        tries += 1
        if playerGuess > computerNumber:
            print("Lower! \n")
            playerGuess = int(input("I am thinking of a number... Please make your next guess! "))
        elif playerGuess < computerNumber:
            print("Higher! \n")
            playerGuess = int(input("I am thinking of a number... Please make your next guess! "))
    tries = str(tries)
    print("You got it in " + tries + " tries! Congratulations! ")
    again = str(input("Do you want to play again (type yes or no): ")).lower()[:1]
    if again == "y":
        guessingGame()
    else:
        sleep(1)
        print("Thank you for playing! ")

def TicTacToe():
    board = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
    ]
    for i in range(5):
        print(board)
    # 此处可补充井字棋剩余业务逻辑

if playerQuestion == 2:
    guessingGame()
    sleep(10)
else:
    TicTacToe()

注:原代码将猜数字游戏放在了选项1的分支,但你的菜单里标注1对应井字棋、2对应猜数字,修复代码已经对应调整了分支判断逻辑,你可以根据实际需求修改匹配规则。

内容的提问来源于stack exchange,提问作者Carter Marshall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:27:03