Guess Number with class and method - python

I am trying to create a guess game using class/methods, but got stuck. When trying the code does not show me any errors but it does not print any of the conditionals created under the method. Can you please tell me what am I doing wrong?
class GuessProcessor:
def __init__(self, my_secretNumber, user_numGuess):
self.my_secretNumber = my_secretNumber
self.user_numGuess = user_numGuess
def compareGuess(self, user_numGuess, my_secretNumber):
return compareGuess
if user_numGuess >10 or user_numGuess <= 0:
print("Invalid number. Try again!")
elif user_numGuess < my_secretNumber:
print("You guessed too low!")
elif user_numGuess > my_secretNumber:
print("You guessed too high")
my_secretNumber = int(6)
user_numGuess = int(input("Enter a number between 1 and 10: "))
The only thing that prints out is:
Enter a number between 1 and 10: 6
Process finished with exit code 0

There are some flaws in your code.
First, your if-else logic won't be checked because you have return compareGuess
Second, you do not use the correct initialization variables when doing the if-else checking
Third, you don't have the condition when the guessing number is correct.
Fourth, you didn't initiate that GuessProcessor class to run the compareGuess with your "my_secretNumber" and "user_numGuess"
Fifth, start to read the coding guideline, especially for the naming convention (https://google.github.io/styleguide/pyguide.html#3162-naming-conventions)
Probably, you would like the code something like this
class GuessProcessor:
def __init__(self, my_secret_number, user_num_guess):
self.my_secret_number = my_secret_number
self.user_num_guess = user_num_guess
def compare_guess(self):
if self.user_num_guess > 10 or self.user_num_guess <= 0:
print("Invalid number. Try again!")
elif self.user_num_guess < self.my_secret_number:
print("You guessed too low!")
elif self.user_num_guess > self.my_secret_number:
print("You guessed too high")
else:
print("You guessed correctly!")
my_secret_number = int(6)
user_num_guess = int(input("Enter a number between 1 and 10: "))
GuessProcessor(my_secret_number, user_num_guess).compare_guess()

You never thought about when the answer is right.
You need to add one more elif statement:
elif user_num_guess == my_secretNumber:
print("Your right!")
Then, you can compare, if you want an response back from Python.
test = GuessProcessor(my_secretNumber, user_num_guess)
test.compare_guess()
The full code will look like this:
class GuessProcessor:
def __init__(self, my_secretNumber, user_numGuess):
self.my_secretNumber = my_secretNumber
self.user_numGuess = user_numGuess
def compareGuess(self, user_numGuess, my_secretNumber):
return compareGuess
if user_numGuess >10 or user_numGuess <= 0:
print("Invalid number. Try again!")
elif user_numGuess < my_secretNumber:
print("You guessed too low!")
elif user_numGuess > my_secretNumber:
print("You guessed too high")
elif user_num_guess == my_secretNumber:
print("Your right!")
my_secretNumber = int(6)
user_numGuess = int(input("Enter a number between 1 and 10: "))
test = GuessProcessor(my_secretNumber, user_num_guess)
test.compare_guess()

Related

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

On the First guess nothing is being registered even if i get it right

This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)

Is there a way to limit the amount of while loops or input loops?

I was just wondering if there is a way to limit the amount of times a user can input something on a while loop. This is simply a guess a number 1-100 game. I have the found variable = False.
while not found:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")
I wanted to see if i could make this code seem more like a game by limiting the amount a user can guess for the input. Ive had some ideas i just cannot wrap my head around it. do i have set a variable value for the input to set the amount of times it can run? Im new to programming so i am struggling a bit.
count = 0
max_guesses_allowed = pick your max here
while not found or count < max_guesses_allowed:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
count += 1
print("Guess lower")
else:
count += 1
print("guess higher")
The standard way would be to count the number of loops, and then exit if they exceed the maximum.
max_allowed = 10
attempt = 0
while not found:
attempt += 1
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif attempt == max_allowed:
print("You've reached the maximum number of guesses.")
break
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")

The returned value not defined

I am creating a guessing game and I have created two functions. One to take the user input and the other to check whether the user input is correct.
def getGuess(maxNum):
if maxNum == "10":
count=0
guess = -1
guessnum = [ ]
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
guesses.append(guess)
return guesses
return guess
def checkGuess(maxNum):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
print (guesses)
and the main code is
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
while guess != num1:
getGuess("10")
checkGuess("10")
count = count+1
print (guess)
Although the function returns the users guess the code always takes the guess as 11. If I don't define guess, it doesn't work either. Please help.
First, you are returning two values. A return statement also acts as a break, so the second return will not be called. Also, you are not storing the returned value anywhere, so it just disappears.
Here is your edited code:
def getGuess(maxNum):
if maxNum == "10":
guess = -1
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
return guess
def checkGuess(maxNum, guess, num1):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
return True
return False
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
guesses = []
while guess != num1:
guess = getGuess("10")
guesses.append(guess)
hasWon = checkGuess("10", guess, num1)
if hasWon:
print(guesses)
break
count = count+1
You have selected Easy as the level of difficulty
2
Guess?5
Too High
Guess?1
Too Low
Guess?2
Correct
[5, 1, 2]
>>>
You have a programming style I call "type and hope". maxNum seems to bounce between a number and a string indicating you haven't thought through your approach. Below is a rework where each routine tries do something obvious and useful without extra variables. (I've left off the initial choice logic as it doesn't contribute to this example which can be put into your choice framework.)
import random
def getGuess(maxNum):
guess = -1
while guess < 1 or guess > maxNum:
try:
guess = int(input("Guess? "))
except ValueError:
print("Please enter valid input")
return guess
def checkGuess(guess, number):
if guess > number:
print("Too High")
elif guess < number:
print("Too Low")
else:
print("Correct")
return True
return False
print("You have selected Easy as the level of difficulty")
maxNum = 10
maxTries = 3
number = random.randint(1, maxNum)
count = 1
guess = getGuess(maxNum)
while True:
if checkGuess(guess, number):
break
count = count + 1
if count > maxTries:
print("Too many guesses, it was:", number)
break
guess = getGuess(maxNum)
A couple of specific things to consider: avoid using except without some sense of what exception you're expecting; avoid passing numbers around as strings -- convert numeric strings to numbers on input, convert numbers to numeric strings on output, but use actual numbers in between.

Asking the user if they want to play again [duplicate]

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break

Categories