Home > Back-end >  print statement only when the condition is CONSECUTIVELY met 3 times in a row
print statement only when the condition is CONSECUTIVELY met 3 times in a row

Time:04-17

I'm currently making a guessing game where user can get a congrats statement if they guess correctly 3 times in a row or a hint statement if they guesses incorrectly 3 times in a row. If user makes two correct guesses and one incorrect guess the count will reset and vice versa for incorrect guesses. the goal is for the right/wrong guess to be 3 times in a row for the statement to print

Here is what I have

count = 0

rightGuess = 0

wrongGuess = 0

die1 = random.randint(1,6)



guess = int(input('Enter guess: '))

if guess == die1:
     
rightGuess  = 1
     
print('Good job')
     
     if rightGuess == 3:
          print('You guessed three times in a row!')


if guess != die1:
      
wrongGuess  = 1
      
print('Uh oh wrong answer')
     
      if wrongGuess == 3:
           print("Hint: issa number :)")

This works but it displays the text whenever the user reaches 3 wrong or right guesses even if it's not in a row. Please help

CodePudding user response:

You can reset the rightGuess variable using rightGuess = 0 when you add 1 to the wrongGuess variable.

CodePudding user response:

You just have to reset the opposite variable to 0 when incrementing either of them.

count = 0
consecutiveRightGuess = 0
consecutiveWrongGuess = 0
die1 = random.randint(1, 6)
guess = int(input('Enter guess: '))

if guess == die1:
    consecutiveWrongGuess = 0
    consecutiveRightGuess  = 1
    print('Good job')
    if consecutiveRightGuess == 3:
        print('You guessed three times in a row!')

if guess != die1:
    consecutiveRightGuess = 0
    consecutiveWrongGuess  = 1
    print('Uh oh wrong answer')
    if consecutiveWrongGuess == 3:
        print("Hint: issa number :)")

CodePudding user response:

You could also do it like this only using one variable for counting guesses:

import random

count = 0

while True:
    die1 = random.randint(1,6)

    guess = int(input("Enter guess: "))

    if guess == die1:
        count = count   1 if count >= 0 else 1
        print('Good job')

    if guess != die1:
        print('Uh oh wrong answer')
        count = count - 1 if count <= 0 else -1

    if count == 3:
        print('You guessed three times in a row!')
        break

    if count == -3:
        print("Hint: issa number :)")
        break
  • Related