How can I count the number of times this function is called? - python

So my assignment(I have to use the while statement) was to make a number guessing game, part of that was to show the number of guesses the player had after they get the number right. I found something that I read is supposed to work but doesn't. here is my code.
#A text program that is a simple number guessing game.
import time
import random
#Setting up the A.I.
Number = random.randint(1,101)
def AI():
B = AI.counter =+ 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while Guess > Number:
print("nope, to high.")
return AI()
while Guess < Number:
print("Sorry, thats to low. try again!")
return AI()
while Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(60)
quit()
AI.counter = 0
AI()
Though when the player gets the number right it says that the player got it in one guess even when that's not the case.

You were pretty close #Simpson! Here's a slightly changed version that should give you what you're looking for :)
Let me know if you have any questions!
#A text program that is a simple number guessing game.
import random
#Setting up the A.I.
def AI():
counter = 1
number = random.randint(1,101)
guess = int(input("Can you guess what number I'm Thinking of?: "))
while guess != number:
if guess < number:
print("Sorry, thats to low. try again!")
else:
print("nope, too high")
counter += 1
guess = int(input("Can you guess what number I'm Thinking of?: "))
print("Congragulations! you win! You guessed " + str(counter) + " times")
time.sleep(60)
quit()
AI()

Without recursion - changed the whiles to ifs and added counter inside the method.
import time
import random
Number = random.randint(1,101)
def AI():
B = 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while True:
if Guess > Number:
print("nope, to high.")
elif Guess < Number:
print("Sorry, thats to low. try again!")
if Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(2)
break # leave the while true
# increment number
B += 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
AI()

Counting function calls is a perfect case for function decorators, a very useful feature of Python. You can define your decorator as:
def call_counted(funct):
def wrapped(*args, **kwargs):
wrapped.count += 1 # increase on each call
return funct(*args, **kwargs)
wrapped.count = 0 # keep the counter on the function itself
return wrapped
And then you can use it to decorate a function you wish to count calls to without dealing with the counter itself in your process flow:
import time
import random
secret_number = random.randint(1, 101)
#call_counted # decorate your AI function with the aforementioned call_counted
def AI():
current_guess = int(input("Can you guess what number I'm thinking of?: "))
while current_guess > secret_number:
print("Nope, too high. Try again!")
return AI()
while current_guess < secret_number:
print("Sorry, that's too low. Try again!")
return AI()
while current_guess == secret_number:
print("Congratulations! You win! You guessed {} times.".format(AI.count))
time.sleep(60)
quit()
AI()
I restyled your code a bit, but it's essentially the same.
I'd avoid recursion, tho, because this can be written much simpler and without the need to count function calls:
import time
import random
secret_number = random.randint(1, 101)
def AI():
counter = 0
while True:
counter += 1
current_guess = int(input("Can you guess what number I'm thinking of?: "))
if current_guess > secret_number:
print("Nope, too high. Try again!")
elif current_guess < secret_number:
print("Sorry, that's too low. Try again!")
else:
break
print("Congratulations! You win! You guessed {} times.".format(counter))
time.sleep(60)
quit()
AI()

You could do it generically with a function decorator that addes a call counter to any function to which it is applied:
(Note I also modified your code so it follows the PEP 8 - Style Guide for Python Code more closely.)
""" A text program that is a simple number guessing game. """
import functools
import time
import random
def count_calls(f):
""" Function decorator that adds a call count attribute to it and counts
the number of times it's called.
"""
f.call_count = 0
#functools.wraps(f)
def decorated(*args, **kwargs):
decorated.call_count += 1
return f(*args, **kwargs)
return decorated
# Setting up the A.I.
number = random.randint(1, 101)
# print('The number is:', number) # For testing.
#count_calls
def AI():
guess = int(input("Can you guess what number I'm thinking of?: "))
while guess > number:
print("Nope, too high.")
return AI()
while guess < number:
print("Sorry, that's too low. Try again!")
return AI()
while guess == number:
print("Congragulations! You win! You guessed " + str(AI.call_count) + " times")
time.sleep(10)
quit()
AI()

Use default arguments:
def AI(B=1):
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while Guess > Number:
print("nope, to high.")
return AI(B + 1)
while Guess < Number:
print("Sorry, thats to low. try again!")
return AI(B + 1)
while Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(60)
return
And then call the function:
AI()
Also, you should really be using ifs instead of whiles here since the loops are run exactly once, but whiles also work, so that's fine. Also, recursion might eat up your RAM, which just wastes resources, provided that you could've implemented the same thing as a loop, but your approach works, so that's fine too.

Related

Number Guessing Games with continuation

I know there is a solution to the number guessing game in python. I've seen the code here too. and as a continuation how can I add a function(or anything else) to prompt the user- after successfully guessing it- if he wants to continue or not if not halt it. I know the code don't know how to add it to code.
import random
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
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")
return
count+=1
so here is what we had in this forum but how can I add this to what I have above :
ask = input('do you want to continue? y stands for yes and n for discontinuing')
if ask=="y":
UserGuess=int(input('Enter youre desired Number: '))
else:
return
Include it in a while loop outside the function. This way, you will get recursion out of the way.
def play_game():
....
....
count+=1
play_game()
while True:
ask = input('do you want to continue? y stands for yes and n for discontinuing')
if ask=="y":
play_game()
else:
break

How to get my random number guessing game to loop again upon user input and how to create an error trap?

So this is my random number guessing program I made. It asks the user to input two numbers as the bound, one high and one low, then the program will choose a number between those two. The user then has to try and guess the number chosen by the program. 1) How do I get it to ask the user if they would like to play again and upon inputting 'yes' the program starts over, and inputting 'no' the program ends? 2) How do I create an error trap that tells the user "Hey you didn't enter a number!" and ends the program?
def main(): # Main Module
print("Game Over.")
def introduction():
print("Let's play the 'COLD, COLD, HOT!' game.")
print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
small = int(input("Enter your smaller number: "))
large = int(input("Enter your bigger number: "))
print("\n")
return small, large
def game(answer):
c = int(input('Input the number of guesses you want: '))
counter = 1 # Set the value of the counter outside loop.
while counter <= c:
guess = int(input("Input your guess(number) and press the 'Enter' key: "))
if answer > guess:
print("Your guess is too small; you're ICE COLD!")
counter = counter + 1
elif answer < guess:
print("Your guess is too large; you're still ICE COLD!")
counter = counter + 1
elif answer == guess:
print("Your guess is just right; you're HOT ON THE MONEY!")
counter = c + 0.5
if (answer == guess) and (counter < c + 1):
print("You were burning hot this round!")
else:
print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)
def Mystery_Number(a,b):
import random
Mystery_Number = random.randint(a,b) # Random integer from Python
return Mystery_Number # This function returns a random number
A,B = introduction()
number = Mystery_Number(A,B) # Calling Mystery_Number
game(number) # Number is the argument for the game function
main()
You'd first have to make game return something if they guess right:
def game(answer):
guess = int(input("Please put in your number, then press enter:\n"))
if answer > guess:
print("Too big")
return False
if answer < guess:
print("Too small")
return False
elif answer == guess:
print("Your guess is just right")
return True
Then, you'd update the 'main' function, so that it incorporates the new 'game' function:
def main():
c = int(input("How many guesses would you like?\n"))
for i in range(c):
answer = int(input("Your guess: "))
is_right = game(answer)
if is_right: break
if is_right: return True
else: return False
Then, you'd add a run_game function to run main more than once at a time:
def run_game():
introduction()
not_done = False
while not_done:
game()
again = input('If you would like to play again, please type any character')
not_done = bool(again)
Finally, for error catching, you'd do something like this:
try:
x = int(input())
except:
print('That was not a number')
import sys
sys.exit(0)

There's an issue somewhere in my Python code.. I can't find where it's at

I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")

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

Could not convert string to float in input

#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)

Categories