gpt4 book ai didi

Python while 循环测试两个真/假元素

转载 作者:太空宇宙 更新时间:2023-11-03 19:16:08 24 4
gpt4 key购买 nike

我正在为我的 children 开发一个文字游戏。我希望他们能够在猜测中输入“提示”以获得提示。第一个“提示”应该给出单词的第一个和最后一个字母。下次他们输入“提示”时应提供该单词的前两个和最后两个字母......等等。

他们第一次输入“提示”时我让它工作,但随后 while 循环被破坏,他们无法猜测错误或再次输入“提示”。

我知道问题出在这一行:

while guess != correct and guess != 'hint':

我似乎无法修复它,以便用户可以多次输入提示。

这是我的代码:

# The computer picks a random word, and then "jumbles" it
# the player has to guess the original word

import random

replay = "y"
while replay == "y":

print("\n"* 100)
word = input("Choose a word for your opponent to de-code: ")
print("\n"* 100)
# provide a hint if the user wants one
hint_count = 1

# create a variable to use later to see if the guess is correct
correct = word

# create a empty jumble word
jumble = ""
# while the chosen word has letters in it
while word:
position = random.randrange(len(word))
# add the random letter to the jumble word
jumble += word[position]
# extract a random letter from the chosen word
word = word[:position] + word[position +1:]

# start the game
print(
"""

Welcome to the Word Jumble!

Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
score = 10
print("The jumble is: ",jumble)

guess = input("\nType 'hint' for help but lose 3 points. \
\nYOUR GUESS: ")

while guess != correct and guess != 'hint':
print("Sorry that's not it.")
score -= 1
guess = input("Your guess: ")

if guess == 'hint':
print("The word starts with '"+ correct[0:hint_count]+"' and ends with '"+correct[len(correct)-hint_count:len(correct)]+"'")
score -= 3
hint_count += 1
guess = input("Your guess: ")

if guess == correct:
print("That's it! You guessed it!\n")
print("Your score is ",score)


print("Thanks for playing.")

replay = input("\n\nWould you like to play again (y/n).")

最佳答案

在第一个“提示”之后,程序应该要求猜测,然后继续打印(“感谢您玩。”),因为检查提示的条件位于 while 循环之外。将其放入 while 循环中:

while guess != correct:
if guess == 'hint':
print("The word starts with '"+ correct[0:hint_count]+"' and ends with '"+correct[len(correct)-hint_count:len(correct)]+"'")
score -= 3
hint_count += 1
guess = input("Your guess: ")

else:
print("Sorry that's not it.")
score -= 1
guess = input("Your guess: ")

关于Python while 循环测试两个真/假元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11250745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com