如何使while循环内的特定代码行仅执行一次?
我希望这一行代码:"Hello %s, please enter your guess: " %p1"
仅在玩家猜错时不被重复运行。
是否有命令或函数可以使用,还是必须重新构建整个游戏程序?在当前形式下,是否有简单的解决方案?
import random
number = random.randint(1,9)
p1 = input("Please enter your name: ")
count = 0
guess = 0
while guess != number and guess != "exit":
guess = input("Hello %s, please enter your guess: " % p1)
if guess == "exit":
break
guess = int(guess)
count += 1
if guess == number:
print("Correct! It Took you only", count, "tries. :)")
break
elif guess > number:
print("Too high. Try again.")
elif guess < number:
print("Too low. Try again.")
count
已经可以作为鉴别器使用,不需要创建另一个标志。虽然这样做“更容易”。 - Patrick Artner