Skip to content Skip to sidebar Skip to footer

Executing One Line Of Code Inside A While Loop Only Once

How do I make a specific line of code execute only once inside a while loop? I want the line: 'Hello %s, please enter your guess: ' %p1' to run only once and not every time the pl

Solution 1:

You can create a flag variable, e. g.

print_username = True

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 = Falseelse:
    guess = input("Try a new guess:")

Solution 2:

You have to ask for a new guess on every iteration - else the code will loop either endlessly (after first wrong guess) or finish immediately.

To change up the message you can use a ternary (aka: inline if statement) inside your print to make it conditional:

# [start identical]while guess != number and guess != "exit": 
    guess = input("Hello {}, please enter your guess: ".format(p1) if count == 0else"Try again: ")

# [rest identical]

See Does Python have a ternary conditional operator?

The ternary checks the count variable that you increment and prints one message if it is 0 and on consecutive runs the other text (because count is no longer 0).

You might want to switch to more modern forms of string formatting as well: str.format - works for 2.7 as well

Solution 3:

A way to execute an instruction only x times in a while loop could be to implement a counter, and add an if condition that checks if the counter < x before executing the instruction.

Solution 4:

You should ask for the username outside of the loop and request input at the beginning of the loop.

Inside the loop you create output at the end and request input on the next iteration. The same would work for the first iteration: create output (outside of the loop) and then request input (first thing inside the loop)

Post a Comment for "Executing One Line Of Code Inside A While Loop Only Once"