How to count number of tries in python
So I'm trying to coutn how many tries it takes to guess the mixed up words. Quite frankly, I've been stuck for so long because this code doesn't work at all. Please help. Img Source : funbrain.comI found that most of the projects one can find online of making a Number Guessing Game in Python are quite cumbersome and use a ton of functions.(You can play the number guessing game online here). In this article i have implemented the logic of the same game by using a single function which is convenient to understand and at the same time easy to code. Objectives of the game-:
Let’s jump right into it! Step 1: Including an ASCII art logo Text to ASCII generator can be found here. Just type in the text to be converted and the tool generates an ASCII art form of the text. Step 2: Inputting settings from the user import random We import the random library for the MY_GUESS variable which takes a random integer value from 1 to 100 using randint method of random. difficulty = str(input("Choose a difficulty. Type 'easy' or 'hard': ")).lower() The variable difficulty is a string variable which lets the user decide the settings of the game if they want to play it on easy or hard setting. Step 3: Defining the count function def count(counts, attempts): The count function takes two arguments “counts” and “attempts”. The count variable is different from the ‘counts’ variable as it is incremented whenever the guess is wrong and the ‘attempts’ variable is decremented after every attempt. Defining a boolean variable ‘no_of_guesses’: no_of_guesses = False The no_of_guesses keeps track of the while loop and when it should be stopped. Condition for the while loop : while no_of_guesses == False and count <= counts: If the number of guesses is False and count is less than the counts(argument) we ask the user for his guess. We check for equality with the MY_GUESS variable which is the initial guess taken randomly. elif guess < MY_GUESS: If however the user’s guess is wrong we increment the count variable by 1 and decrement the attempts by 1. Here, if the guess value is small compared to the MY_GUESS value. We output a hint that the value is “Too Low. Guess Again.” Also, cautioning the user about the number of attempts he has reamining. Similarly, if the guess value is high compared to the MY_GUESS value. We output a hint that the value is “Too High. Guess Again.” Again, cautioning the user about the number of attempts he has reamining. Step 4: Calling the ‘count’ function. if difficulty == 'easy': We pass arguments 10, 10 : counts, attempts for easy mode and 5,5 for hard mode as laid out in the objectives.
I hope this one upholds the old adage by Martin, “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” — Martin Fowler Did you like my efforts? If Yes, please follow me to get my latest posts and updates or better still, buy me a coffee!☕ |