![]() Number_of_guesses = 0 while number_of_guesses number : print ( 'Your guess is too high' ) if guess = number : break if guess = number : print ( 'You guessed the number in ' + str (number_of_guesses ) + ' tries!' ) else : print ( 'You did not guess the number. ![]() Sample output of the current program looks like the following: Though it works, right now the user never knows if their guess is correct and they can guess the full 5 times without ever knowing if they got it right. The program is fully functioning, and we can run it with the following command: Then, we converted guess from a string to an integer.īefore the loop is over, we also want to increase the number_of_guesses variable by 1 so that we can iterate through the loop 5 times.įinally, we write a conditional if statement to see if the guess that the user made is equivalent to the number that the computer generated, and if so we use a break statement to come out of the loop. Within the loop, we added a print() statement to prompt the user to enter a number, which we took in with the input() function and set to the guess variable. After the fifth guess, the user will return to the command line, and for now, if the user enters something other than an integer, they’ll receive an error. Then we added the while statement so that the number_of_guesses is limited to 5 total. We’ve initialized the variable number_of_guesses at 0, so that we increase it with each iteration of our loop so that we don’t have an infinite loop. ![]() randint ( 1, 25 ) number_of_guesses = 0 while number_of_guesses < 5 : print ( 'Guess a number between 1 and 25:' ) guess = input ( ) guess = int (guess ) number_of_guesses = number_of_guesses + 1 if guess = number : break
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |