Python- Finding average - python

I am trying to find the average number of times a user guesses a number. The user is asked how many problems they want to do and then the program will give them that many problems. I am having trouble recording the amount of times they guess and get wrong and guess and get right and finding the average between the two. This is what I have so far
print("Hello!")
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVGcorrect = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
AVGcorrect+=1
print("Correct!")
AVERAGE+=((AVGcorrect+AVGcounter)/AVGcorrect)
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
numPROBLEMS = input("How many problems would you like to solve? ")
PROBLEMS = int(numPROBLEMS)
if PROBLEMS in range(1,11):
for PROBLEMS in range(PROBLEMS):
HOOBLAH()
else:
print("Average number of tries: {0}".format(HOOBLAH,AVERAGE))
else:
print("Please input a value between 1 through 10!")
main()
Thanks!

So I tried to change as little as possible as to not cramp your style. So think about it like this, the average number of guesses needed to get the correct answer is just the total number of guesses divided by the number of correct guesses. Because you make sure the user eventually gets the correct answer, the number of correct guesses will just be the number of problems!
So each time you run HOOBLAH(), return the number of guesses it took to get the correct answer. Add all those up together outside the for loop, then at the end of the loop, divide the number of guesses by the number of problems and then you've got your answer! Also, I don't think python supports '+=', so you may need to change AVGcounter+=1 to AVGcounter = AVGcounter +1, but I totally may be mistaken, I switch between languages a bunch!
One note is I cast numGuesses to a float ( float(numGuesses) ), that is to make sure the int data type doesn't truncate your average. For example, you wouldn't want 5/2 to come out to 2, you want it to be 2.5, a float!
Hopefully that helps!
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
print("Correct!")
return AVGcounter
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
problemsString = input("How many problems would you like to solve? ")
numProblems = int(problemsString)
numGuesses = 0
if numProblems in range(1,11):
for problem in range(numProblems):
numGuesses = numGuesses + HOOBLAH()
print("Average number of tries: " + str(float(numGuesses)/numProblems)
else:
print("Please input a value between 1 through 10!")
main()

I'm not totally sure what you're trying to do, but if you want to give the user x number of problems, and find the average number of guesses per problem, you'll want your HOOBLAH() function to return the number of guesses for each run. You can keep track of this outside your method call and average it at the end. But right now, your program has no access to AVGcounter, which seems to be the variable you're using to count the number of guesses, outside the HOOBLAH() function call.

Related

I am extremely new to python and I am making a random number guessing game [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
For right now, I have it so it will print the random number it chose. However, whether I get it wrong or right it always says I am wrong.
here is my code:
import random
amount_right = 0
number = random.randint(1, 2)
guess = input
print(number)
print(
"welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!")
input("enter your guess here! ")
if guess != number:
print("Not quite!")
amount_right -= 1
print("you have a score of ", amount_right)
else:
print("good Job!!")
amount_right += 1
print("you have a score of ",amount_right,"!")
what did I do wrong? I am using Pycharm if that helps with anything.
I tried checking my indentation, I tried switching which lines were the if and else statements (lines 13 - 21) and, I tried changing lines 18 - 21 to elif: statements
guess = int(input())
You need to convert your guess to int and there should be () in input
Also there are 2 input() in your code. One is unnecessary. This can be the code.
import random
amount_right = 0
number = random.randint(1, 2)
print(number)
print(
"welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!")
guess = int(input("enter your guess here! "))
if guess != number:
print("Not quite!")
amount_right -= 1
print("you have a score of ", amount_right)
else:
print("good Job!!")
amount_right += 1
print("you have a score of ",amount_right,"!")

python while loop in a while loop ignores the print after winning the game

I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")

Loops and comparing strings in homework assignment

I need help with an assignment I have for Intro to Python.
The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.
My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?
P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.
Code:
import random
#answer= a
a= random.randint(1,100)
#x= original variable of a
x= a
correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")
#guess= g
while not correct:
g= input("Please enter a number between 1 and 100: ", )
if g == "x":
print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")
elif int(g) < x:
print("your guess was too low, try again.")
elif int(g) > x:
print("your guess was too high, try again.")
else:
print("Congratulations, you guessed the number!")
So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:
g=input("blah blah blah input here: ")
if g.isdigit():
# now you can do your too high too low conditionals
else:
print("Your input was not a number!")
You can learn more in this StackOverflow thread.

Counting the number of loops python

I am learning python, and one of the exercises is to make a simple multiplication game, that carries on every time you answer correctly. Although I have made the game work, I would like to be able to count the number of tries so that when I've answered correctly a few times the loop/function should end. My problem is that at the end of the code, the function is called again, the number of tries goes back to what I originally set it, obviously. How could I go about this, so that I can count each loop, and end at a specified number of tries?:
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt != answer:
print("not correct")
attempt = int(input("try again: "))
if attempt == answer:
print("Correct!")
multiplication_game()
You could surround your call of multiplication_game() at the end with a loop. For example:
for i in range(5):
multiplication_game()
would allow you to play the game 5 times before the program ends. If you want to actually count which round you're on, you could create a variable to keep track, and increment that variable each time the game ends (you would put this inside the function definition).
I would use a for loop and break out of it:
attempt = int(input(": "))
for count in range(3):
if attempt == answer:
print("correct")
break
print("not correct")
attempt = int(input("try again: "))
else:
print("you did not guess the number")
Here's some documentation on else clauses for for loops if you want more details on how it works.
NB_MAX = 10 #Your max try
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
i = 0
while i < NB_MAX:
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt != answer:
print("not correct")
attempt = int(input("try again: "))
if attempt == answer:
print("Correct!")
i += 1
multiplication_game()

Python 3.1 number guessing game higher or lower loop

In the process of learning Python using the book 'Python Programming for the Absolute Beginner Third Edition' and struggling with a challenge that has been set.
I have to create a Number Guessing program where the player picks a number and the program tries to guess it by picking a random number then using higher or lower questions to get closer to the number. I've got most of it figured out but I'm struggling with the higher or lower loop. The trouble I'm having is that i can't get the program to not go above or below it's second to last guess i.e.
My number is 78
computer picks 50
i say higher
computer picks 80
i say lower
computer can then pick 12 (when i don't want it going below 50.
I'm using Python 3.1
Here is a copy of the code.
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
Thanks in advance for any help you folks can give.
Ally
I see the following problems with your code:
your random number generators are bound only on one side of the number spectrum, e.g. random.randint(0, lower) - so it's ignoring the higher bound. Similarly for computer_guess = random.randint(higher, 101).
I suggest you initialise higher and lower.
Some debug helps :)
Here's the working code:
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
lower = 0 # initial lower guess
higher = 101 # initial higher guess
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(lower+1, higher-1)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(lower+1, higher-1)
else:
print("Please choose either higher or lower.")
print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))
input("\n\nPress the enter key to exit")
You have to store something like min_comp_guess and max_comp_guess
Then, when you are about to "guess" number you have to generate it for a valid range (obviously min_comp_guess up to max_comp_guess).
I'm always second! :)
You are never storing the upper and lower bounds to the possible numbers. In your example, as soon as your program picks 50 and you say "higher", you need to store somewhere the information that "the number is definitely higher than 50". The same goes for when you answer "lower".
I may be completely wrong but whilst testing your code I found that by choosing the programs number was higher than my chosen number it would increase the number instead or a presumable decrease, not making it any closer to the number I had guessed. A similar higher/lower program I created had the same problem, to fix the problem I simply switched the more than and less than signs around, hopefully you find this helpful and could apply this to your program.

Categories