7

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 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.")
Božo Stojković
  • 2,893
  • 1
  • 27
  • 52
Vomer
  • 97
  • 1
  • 1
  • 6

4 Answers4

6

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 = False
else:
    guess = input("Try a new guess:")
Lev Leontev
  • 2,538
  • 2
  • 19
  • 31
  • 3
    ternary is shorter - and `count` already works as discriminator - no need to create another flag. This is "easier" though. – Patrick Artner Jan 27 '19 at 11:47
3

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 == 0 
                  else "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

tripleee
  • 175,061
  • 34
  • 275
  • 318
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

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.

fuomag9
  • 138
  • 1
  • 12
0

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)

Karsten
  • 2,772
  • 17
  • 22