在 while 循环中只执行一行代码一次 [英] Executing one line of code inside a while loop only once

查看:56
本文介绍了在 while 循环中只执行一行代码一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让特定的代码行在 while 循环中只执行一次?

How do I make a specific line of code execute only once inside a while loop?

我想要这条线:您好 %s,请输入您的猜测:"%p1" 只运行一次,而不是每次玩家猜错时都运行.

I want the line: "Hello %s, please enter your guess: " %p1" to run only once and not every time the player guesses wrong.

是否有我可以使用的命令或功能,或者我是否必须以不同的方式构建整个游戏?这种形式的程序有没有简单的修复方法?

Is there are command or function I can use or do I have to structure the whole game differently? Is there a simple fix to the program in this form?

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.")

推荐答案

您可以创建一个标志变量,例如.G.

You can create a flag variable, e. g.

print_username = True

在 while 循环之前.在循环第一次迭代后取消选中它:

before the while loop. Inside the loop uncheck it after loop's first iteration:

if print_username:
    guess = input("Hello %s, please enter your guess: " % p1)
    print_username = False
else:
    guess = input("Try a new guess:")

这篇关于在 while 循环中只执行一行代码一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆