Counting the number of loops python - 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()

Related

My while loop doesn't function correctly after my first input, why?

I'm having trouble with getting the while loop to function correctly in my code.
I want to create a program that randomly generates 2 numbers and asks the user to give the sum of them. This is what I have so far: 
import random
def add_random_numbers():
num1 = random.randint(0, 100)
num2 = random.randint(0, 100)
print(num1, '+', num2)
answer = num1 + num2
user_answer = int(input("Enter Your Answer: "))
while user_answer != answer:
if (user_answer > answer):
print("Sorry, your guess is too high.")
int(input("\nTry again: "))
if (user_answer < answer):
print("Sorry, your guess is too low.")
int(input("\nTry again: "))
add_random_numbers()
But once you enter the wrong number and you're prompted to try again, the while loop no longer works. It just keeps repeating the first result. I know it's probably a simple fix but I can't figure it out. What am I missing?
You need to reassign your input back to user_answer
while user_answer != answer:
if (user_answer > answer):
print("Sorry, your guess is too high.")
user_answer = int(input("\nTry again: "))
if (user_answer < answer):
print("Sorry, your guess is too low.")
User_answer = int(input("\nTry again: "))
That's because you don't reassing user_answer on your input "Try again". So that's why it keeps using the first input
So the problem lies in the line where you ask the user to put a new input
int(input("\nTry again: "))
This line does ask for a new input but the answer isn't assigned anywhere, in order to fix this you only need to rewrite the value of user_answer as follows
user_answer = int(input("\nTry again: "))

While loop keeps printing constantly, doesn't allow for user input

I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers.
I'm getting stuck with the actual loop - it endlessly keeps printing the message to user to enter a different number - as in the picture - and doesn't give user a chance to enter a different number. Please help, I've been through so many videos and blogs and can't figure out what's actually wrong.
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num =int(input("number:"))
#looping
while num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
break
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
print("Nope, guess again:")
You need to include the input function in the loop if you want it to work. I corrected the rest of your code as well, you don't need the if condition. More generally you should avoid to use break, it often means you are doing something wrong with your loop condition. Here it is redondant and the code after break is never executed.
wrong = []
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num = int(input("Number: "))
while num != -1 :
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
You are just breaking the loop before printing the results, first print the results, then break the loop.
And a while loop isn't necessary for your program, use if condition wrapped in a function instead:
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
#looping
def go():
num =int(input("number:"))
if num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
break
print("Nope, guess again:")
go()
There are lots of issues in the code.
If you want to get inputs in while looping, you should include getting input code inside the while loop like below,
while num != -1:
......
num =int(input("number:"))
......
Also you don't have to include 'break' inside the while loop because, when num != 1, the loop will stop.
You should ask for input inside your loop, but you just print "Nope, guess again:".
wrong = []
print("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\n"
"If not correct you'll have to guess again ^-^")
num = int(input("number: "))
# looping
while num != -1:
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")

Multiplication guessing game in Python | if wrong guess until it is correct

I am trying to write a program as follows:
Python generates random multiplications (factors are random numbers from 1 to 9) and asks to the users to provide the result
The user can quit the program if they input "q" (stats will be calculated and printed)
If the user provides the wrong answer, they should be able to try again until they give the correct answer
if the user responds with a string (e.g. "dog"), Python should return an error and ask for an integer instead
It seems I was able to perform 1) and 2).
However I am not able to do 3) and 4).
When a user gives the wrong answer, a new random multiplication is generated.
Can please somebody help me out?
Thanks!
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
while True:
counter_attempt += 1
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1
Hi my Idea is to put the solving part in a function:
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
def ask(num1, num2, attempt, loss, win):
result = str(num1 * num2)
guess = input(f"How much is {num1} * {num2}?: ")
if guess == "q":
print(
f"Thank you for playing, you guessed {win} times, you gave the wrong answer {loss} times, on a total of {attempt} guesses!!!")
return attempt, loss, win, True
try:
int(guess)
except ValueError:
print("Please insert int.")
return ask(num1, num2, attempt, loss, win)
if guess == result:
print("Congratulations, you got it!")
win += 1
return attempt, loss, win, False
elif guess != result:
print("Wrong! Please try again...")
loss += 1
attempt += 1
return ask(num1, num2, attempt, loss, win)
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
counter_attempt, counter_loss, counter_win, escape = ask(num_1, num_2, counter_attempt, counter_loss, counter_win)
if escape:
break
Is that what you asked for?
Note that everything withing your while loop happens every single iteration. Specifically, that includes:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
So you are, indeed, generating new random numbers every time (and then announcing their generation to the user with guess = input(f"How much is {num_1} * {num_2}?: "), which is also within the loop).
Assuming you only intend to generate one pair of random numbers, and only print the "how much is...?" message once, you should avoid placing those within the loop (barring the actual input call, of course: you do wish to repeat that, presumably, otherwise you would only take input from the user once).
I strongly recommend "mentally running the code": just go line-by-line with your finger and a pen and paper at hand to write down the values of variables, and make sure that you understand what happens to each variable & after every instruction at any given moment; you'll see for yourself why this happens and get a feel for it soon enough.
Once that is done, you can run it with a debugger attached to see that it goes as you had imagined.
(I personally think there's merit in doing it "manually" as I've described in the first few times, just to make sure that you do follow the logic.)
EDIT:
As for point #4:
The usual way to achieve this in Python would be the isdigit method of str:
if not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
An alternative method, just to expose you to it, would be with try/except:
try:
int(guess) # Attempt to convert it to an integer.
except ValueError: # If the attempt was unsuccessful...
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration.
And, of course, you could simply iterate through the string and manually ensure each of its characters is a digit. (This over-complicates this significantly, but I think it is helpful to realise that even if Python didn't support neater methods to achieve this result, you could achieve it "manually".)
The preferred way is isdigit, though, as I've said. An important recommendation would be to get yourself comfortable with employing Google-fu when unsure how to do something in a given language: a search like "Python validate str is integer" is sure to have relevant results.
EDIT 2:
Make sure to check if guess == 'q' first, of course, since that is the one case in which a non-integer is acceptable.
For instance:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
elif guess == result:
...
EDIT 3:
If you wish to use try/except, what you could do is something like this:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
try:
int(guess)
except ValueError:
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
if guess == result:
...
You are generating a new random number every time the user is wrong, because the
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
Is in the while True loop.
Here is the fixed Code:
import random
counter_attempt = 0
counter_win = 0
counter_loss = 0
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
while True:
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
input()
quit()
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
break
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

Python- Finding average

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.

Categories