Python 跳过一半的 while 循环及其内部的 while 循环,但在嵌套的 while 循环之后运行代码

问题描述 投票:0回答:1

在我正在开发的这个终端游戏中,一个 while 循环要求你猜测一个具有一定数量字母的单词(用变量

diff
表示,但你 + 2 才能得到实际的字母数量)。但是,在下面的代码中,它跳到使用
type()
函数询问您是否要再次播放的行。所有变量,例如
stop
diff
guess
都在开始时定义。我正在使用Python 3.12.1。

-代码片段(出现问题的地方)

while stop not in ['y']:
    roll()
    if "\'" in word:
        roll()
    print(word)
    while word != guess:
        type("\nYour guess...")
        guess = input(" ")
        guess = guess.lower()
        if len(guess) != diff + 2:
            type(f'\nYour guess has to be at least {diff+2} characters long.')
        for i in range(len(guess)):
            if guess[i] == word[i]:
                print(f"{bcolors.OKGREEN}{guess[i]}{bcolors.ENDC}", end = '')
            elif guess[i] in word:
                print(f"{bcolors.WARNING}{guess[i]}{bcolors.ENDC}", end = '')
            else:
                print(f"{bcolors.FAIL}{guess[i]}{bcolors.ENDC}", end = '')
    type('\nWould you like to play again or stop? (a/s)')
    ans = input(" ")
    if ans == 's':
        stop = 'y'

-完整代码(以防问题发生在其他地方)

import nltk
from nltk.corpus import brown
from time import sleep
from os import *
from random import *
import sys
import os.path

def type(phrase, speed = 1):
    a = 0
    for i in range (len(phrase)):
        print(phrase[a], end='', flush=True)
        c = phrase[a]
        if c == '.' or c=='!' or c=='?':
            sleep(0.5/speed)
        elif c == ',':
            sleep(0.25/speed)
        else:
            sleep(0.05/speed)
        a+=1

word = ''
diff = ''
stop = ''
guess = ''

def roll():
    word = (word_list[randint(0, len(word_list)-1)])
    word = word.lower()

nltk.download('brown')
common_words = set(brown.words())

common_known_words = sorted(set(common_words))

threelw = [word for word in common_known_words if len(word) == 3]
fourlw = [word for word in common_known_words if len(word) == 4]
fivelw = [word for word in common_known_words if len(word) == 5]
sixlw = [word for word in common_known_words if len(word) == 6]

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

system('cls')

type(f"Welcome to...")
type('''
░▒▓█▓▒░      ░▒▓█▓▒░▒▓███████▓▒░ ░▒▓██████▓▒░ ░▒▓██████▓▒░  
░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░      ░▒▓█▓▒░░▒▓█▓▒░ 
░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒▒▓███▓▒░▒▓█▓▒░░▒▓█▓▒░ 
░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
░▒▓█▓▒░      ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ 
░▒▓████████▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░░▒▓██████▓▒░ ░▒▓██████▓▒░  ''', 45)
print("\n")
sleep(1)
type("The game where you get a word and you have to guess it in as little guesses possible.")
type('''\nWhat difficulty would you like to play at?:\n[1] 3 letter words\n[2] 4 letter words\n[3] 5 letter words\n[4] 6 letter words\n''')

while diff not in ['1', '2', '3', '4', '5']:
    diff = input("\n(1/2/3/4): ")
    if diff == '1':
        word_list = threelw
    elif diff == '2':
        word_list = fourlw
    elif diff == '3':
        word_list = fivelw
    elif diff == '4':
        word_list = sixlw
    else:
        type("Invalid input. Try again.")

diff = int(diff)

while stop not in ['y']:
    roll()
    if "\'" in word:
        roll()
    print(word)
    while word != guess:
        type("\nYour guess...")
        guess = input(" ")
        guess = guess.lower()
        if len(guess) != diff + 2:
            type(f'\nYour guess has to be at least {diff+2} characters long.')
        for i in range(len(guess)):
            if guess[i] == word[i]:
                print(f"{bcolors.OKGREEN}{guess[i]}{bcolors.ENDC}", end = '')
            elif guess[i] in word:
                print(f"{bcolors.WARNING}{guess[i]}{bcolors.ENDC}", end = '')
            else:
                print(f"{bcolors.FAIL}{guess[i]}{bcolors.ENDC}", end = '')
    type('\nWould you like to play again or stop? (a/s)')
    ans = input(" ")
    if ans == 's':
        stop = 'y'

我尝试更改 while 循环的格式(从

while stop != 'y'
while stop not in ['y']
)并弄乱缩进。我期待 Python 运行整个(非嵌套)while 循环,直到你猜对了这个词。

python while-loop
1个回答
0
投票

这个函数就是问题所在:

def roll():
    word = (word_list[randint(0, len(word_list)-1)])
    word = word.lower()

在此函数内部,

word
是一个local变量。 对同名全局变量没有影响。

所以在全局层面,

word
仍然是一个空字符串,并且
while word != guess
循环立即退出,因为
guess
也是一个空字符串。

如果您希望函数分配给全局变量,则必须使用

global
关键字告诉函数它是全局的:

def roll():
    global word
    word = (word_list[randint(0, len(word_list)-1)])
    word = word.lower()
© www.soinside.com 2019 - 2024. All rights reserved.