I am supposed to write a program in python that asks the user how many multiplication questions they want, and it randomly gives them questions with values from 1 to 10. Then it spits out the percentage they got correct. My code keeps repeating the same set of numbers and it also doesn't stop at the number the user asked for. Could you tell me what's wrong?
import random
import math
gamenumber = int(input("How many probems do you want?\n"))
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main():
random.seed()
count = 0
while count < gamenumber:
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
correct = guess == answer
if guess == answer:
print("Correct!")
else wrong:
print("Sorry, the answer is", answer, ".")
result = correct/wrong
print("You got ", "%.1f"%result, "of the problems.")
main()
You only assign to num_1 and num_2 once. Their values never change; how can your numbers change? Furthermore, you don't increment count, so its original value is always compared against gamenumber.
You need to assign a new random number to your two variables and increment your counter.
You forgot to increment count in your loop and num_1 and num_2 don't get new values.
Problems you mentioned
My code keeps repeating the same set of numbers
This is no surprise, as you set your num_1 and num_2 (1) outside the main function and (2) outside the main while loop. A simple correction is:
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
My code doens't stop at the number asked for:
There again, no surprise, as you never increment the count counter: you always have count < gamenumber.
A simple correction is:
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
Here, the count += 1 means add 1 to count *in place*. You could also do count = count + 1 but it's a bit less efficient as you create a temporary variable (count + 1) that you don't really need.
Other problems
You never define wrong
You define gamenumber outside the function. While it's not an issue in this case, it'd be easier to use gamenumber as an argument of main, as it's the variable that drives the game.
Your result is defined in the loop. You probably want to increment a counter for each good answer and print the result after the main loop.
Your result is calculated as correct/wrong. While I'm sure you meant correct/gamenumber, you have to be extra careful: count and gamenumber are integers, and dividing integers is no the same as dividing floats. For example, 2/3 gives 0, but 2/float(3) gives 0.6666666. So, we'll have to use a float somewhere.
You want to print a percentage: your result should then be result=correct*100./gamenumber.
You don't want to gamenumber to be 0, otherwise your result will be undefined.
So, all in all, your main function should be
def main(gamenumber):
random.seed()
count = 0
correct = 0
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
if guess == answer:
correct += 1
print("Correct!")
else wrong:
print("Sorry, the answer is", answer, ".")
if gamenumber > 1:
result = correct * 100./gamenumber
print("You got ", "%.1f"%result, "of the problems.")
The most glaring issue to me is that you have an infinite loop; you don't increase count anywhere.
You're only generating the question numbers once, before you start looping. You need to generate num_1 and num_2 every time, before the user is asked a question.
You never actually update the count value after initializing it, so your loop will go on forever.
import random
import math
spelling of "problems" is wrong
gamenumber = int(input("How many probems do you want?\n"))
move these next two lines inside the loop
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main():
random.seed()
count = 0
while count < gamenumber:
You can use "What is {}x{}?".format(num1, num2) here.
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
Is this supposed to count the correct answers? should be correct += guess == answer
correct = guess == answer
Do you mean to count the number of wrong answers? wrong += guess != answer
if guess == answer:
print("Correct!")
else wrong: is a syntax error else: #wrong perhaps?
else wrong:
print("Sorry, the answer is", answer, ".")
This isn't how to compute a percentage. You should use correct*100/gamenumber and dedent to match the print()
result = correct/wrong
print("You got ", "%.1f"%result, "of the problems.")
main()
Also you're not incrementing count anywhere. It's easier to just use
for count in range(gamenumber):
instead of the while loop
Python is a procedural language. It executes statements in your method body from top to bottom. This line:
num_1 = random.randint(1,10)
is an assignment statement. It does not equate num_1 with a random process for assessing its value; it evaluates an expression - by calling random.randint(1,10) - and assigns that value to num_1, once.
You must force another call to random.randint to obtain another random number, and you must have a statement assign a value to num_1 each time you want num_1's value to change.
Write a multiplication game program for kids. The program should give the player ten randomly generated multiplication questions to do. After each, the program should tell them whether they got it right or wrong and what the correct answer is
from random import randint
for i in range (1,11):
num1 = randint (1,10)
num2 = randint (1,10)
print ("Question",i,":",num1,"*",num2,"=", end = " ")
guess = int (input())
answer = num1*num2
if guess == answer:
print ("Right!")
else:
print ("Wrong. The answer is: ",answer)
Related
I am new to Python, so I decided to start with a numbers game. I have my numbers being input correctly, but I would like it to display the number of correct answers and the correct original, random numbers.
Code as follows:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = [random.randint(0, 10), numberOfNumbers]
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got' + numCorrect + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Current output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Original: [5, 3]
Your guess: [1, 2, 3]
Target Output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
(Currently not working for print) You got (x) Correct!
(Here prints answers, it's only printing two numbers) Original: [5, 3, x]
(Your input prints here, working as planned) Your guess: [1, 2, 3]
You do this:
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
But, since you keep appending to values, it will never be equal to (==) answers until all the correct answers are in there, and even then only if they are in the correct order.
If you want numCorrect to have the number of answers in values that is currently correct, you can write something like:
numCorrect = len([v for v in values if v in answers])
Of course, if you only want to print numCorrect if it changes, you have a bit more code to write.
(also note that this goes sideways if you have duplicate correct answers, so it's not quite this simple, but I'm not writing your game, just correcting your code so it does what you appear to want it to do)
You do this:
answers = [random.randint(0, 10), numberOfNumbers]
That creates a list with two numbers, a random number and numberOfNumbers. It looks like you really want a list of length numberOfNumbers with all random numbers:
answers = [random.randint(0, 10) for _ in range(numberOfNumbers)]
This could include duplicates, but you get to figure out how to avoid that.
In general, I would recommend using a free IDE like PyCharm or Spyder to debug your code. They have options that allow you to step through your code one line at a time, so you can see how the values of variables change as your commands execute - that will make a lot more sense.
Since you are pretty new to python I decided to stick to your code and correct them instead of complicating it. So, what you basically did wrong was that you were using print('You got ' + str(numCorrect) + ' correct!') inside the if statement because if the condition wasn't true the print statement wouldn't work.
The next was that you needed to get the random numbers inside while loop to get the x number of random numbers. Or, else what you were doing was that you simply got one random number and the input from numberOfNumbers.
Here's the final code:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = []
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
ans_var = random.randint(0,10)
answers.append(ans_var)
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got ' + str(numCorrect) + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Hope it helps :)
This is my code, The computer is supposed to guess a number between 1 and 100. The computer's guesses should either decrease or increase by half of the previous guess. The third time through the loop going only higher it breaks, or if I use higher after saying lower it breaks. Both ways, it will stop adding its guesses and divide the previous guess by two, instead of adding the previous guess divided by two to the previous guess. i.e instead of 50 + (50/2) = 75 my code does 50/2 = 25. So where it breaks on higher is at 87, instead of adding half of the previous guess, which would be six, it divides 87 by 2 equaling 43. (I have now edited this question, and the code and everything should work besides where I need help. Thank you)
pcguess = 50
useranswer = 50
print("Wanna see a magic trick?")
print("Please think of a random number between 1 and 100.")
print("Now that you have written down your number")
print("I will guess it in ten guesses or less.")
a = print("My first guess is", pcguess)
tries = 0
while tries < 100000:
newguess = pcguess//2
b = input("Was that your number?")
if b == "no":
tries += 1
c = input("Is your number higher or lower than my guess?")
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess
pcguess = newguess
tries += 1
elif c == "higher":
print("Then my next guess is:")
print(useranswer + newguess)
useranswer = pcguess + newguess
pcguess = newguess
tries += 1
if b == "yes":
print("I got it in", tries, "tries!")
break
You need to narrow down the possible range of numbers based on the user's "higher"/"lower" responses. So you should store the lower and upper bounds as variables, and adjust them as you get responses. Something like this:
lower = 0
upper = 100
while lower < upper:
guess = (lower+upper)//2
print("My guess is ", guess)
# Find out if the correct answer is higher or lower than this guess
if the correct answer is higher:
lower = guess + 1 # This gives a new lower bound
if the correct answer is lower:
upper = guess - 1 # This gives a new upper bound
The first thing I would change in your code is your where you increment your tries variable. In your current while loop, you are incrementing once every time you execute your while loop and then again after whichever if statement gets executed. This means that every iteration, your number of tries goes up by 2 instead of 1. So why don't you just increment tries once at the beginning of your loop instead?
Second, the reason your useranswer variable doesn't become what you expect is simply because you are updating it wrong. For example
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess # WRONG
pcguess = newguess
since you are updating useranswer, it should be useranswer = useranswer + newguess or more succinctly useranswer += newguess
Do this for the other if statement as well (where your guess is higher than what the computer is guessing)
Thirdly. This is more a matter of styling but your while loop condition should be more accurate (i.e. since you are telling the user that you will guess their number in 10 tries or less, does your loop condition really need to have tries < 100000?
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()
I am working on a multiplication tutor program that is assigned to meet the following criteria:
Program asks the user how man problems they want to solve, if the
user enters a value more than 10 the program interprets the number as
an error and prompts the user for a different value.
Program generates a random multiplication problem with two variable
numbers between 0 and 12.
Program prints the problem and prompts the user to answer it, if the
user does not answer it correctly the program will tell the user if
his answer was too high or too low and then ask a new question.
I found the following code on this website and thought I could modify it to work in the ways described above:
import random
import math
game = int(input("How many problems do you want?\n"))
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main(game):
random.seed()
count = 0
correct = 0
#wrong != 0 #Took this variable out and replaced it with "if guess != answer" ('wrong' was originally part of an else statement) because it was not working properly.
while count < game:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
if guess == answer:
correct += 1
print1("Correct!")
if guess != answer:
print("Sorry, the answer is", answer, ".")
if game > 1:
result = correct * 100./game
print("You got ", "%.1f"%result, "of the problems.")
main()
but.... I keep getting the following error and don't know what to do:
Traceback (most recent call last):
File "C:\Users\Internet Fate\Desktop\game.py", line 30, in <module>
main()
TypeError: main() missing 1 required positional argument: 'game'
I have been trying to figure out what the issue is for over an hour now and I am starting to get stressed. In addition to this I have no idea how to get the program to only accept an input from 1-10 for the number of times the game is played (referring to criteria point number one). How to get the program to tell the user that their answer was too high or too low and then have it give them a new problem (referring to point three). And no idea how to repeat this process the designated number of times and then restart.
Replace last main() with main(game) and make this small changes, remember to read the python tutorials, good luck!
import random
import math
game = int(input("How many problems do you want?\n"))
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main(game):
random.seed()
count = 0
correct = 0
result = 0 #Here we initialized result to 0
while count < game:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = num_1*num_2 # Here we don't convert to string so the next "if" works
count += 1
if guess == answer:
correct += 1
print("Correct!")
if guess != answer:
print("Sorry, the answer is", answer, ".")
if game > 1:
result = correct * 100./game
print("You got ", "%.1f"%result, "of the problems.")
main(game) #send game as parameter
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.