Last answered:

28 May 2024

Posted on:

04 Mar 2023

0

i can't stop my while loop after a certain number of loops

i wanted to make a program that gives the user only 3 guess to guess a secret number , the function works as inteded but it keeps going on and only stoping when the user guesses correctly not after 3 tries

what's wrong with my code?

   

1 answers ( 0 marked as helpful)
Instructor
Posted on:

28 May 2024

0

Hi Dena!
Thanks for reaching out!
You have used in the while loop <= and this involves that the variable increase from 0 to 3 – 0, 1, 2 and 3, thus the while loop itterates 4 times. Please, use the following code:

def num_guess():
   tries = 0
   while tries < 3:
       tries += 1
       num = int(input())
       s_num = 3
       if num < s_num:
           print("Higher")
       elif num > s_num:
           print("Smaller")
       else:
           print("You have guessed")
           break
   else:
       print("Your attempts are over. The correct number was", s_num)

Hope this helps.
Best,
Martin

Submit an answer