Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.")
like image 461
Vomer Avatar asked Jan 27 '19 11:01

Vomer


2 Answers

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:")
like image 103
Leo Leontev Avatar answered Oct 12 '22 19:10

Leo Leontev


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

like image 3
Patrick Artner Avatar answered Oct 12 '22 19:10

Patrick Artner