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.")
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:")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With