Python, loops - code results do not match expected outcome - python

I am trying to make a program for basic addition(+) on mathematics. My code is as follows:
import random
Totalrounds = input("Input how many rounds you want try? ")
answerlist = list()
for i in range(0, int(Totalrounds)):
numb1 = random.randint(0,9)
numb2 = random.randint(0,9)
print(numb1, "+" , numb2,)
Answer = int(input("Your answer is? " ))
if Answer == numb1 + numb2 :
print("Your answer is correct")
print()
else:
print("Your answer is wrong")
print("the right answer is ", numb1 + numb2)
print()
answerlist.append(Answer)
#Result
print("this is your Answersheet from" ,Totalrounds, "question")
for i in range(0, len(answerlist)):
if answerlist[i] == numb1 + numb2 :
Result1 = "correct"
print (numb1, "+" , numb2, "=" ,answerlist[i], Result1 ,)
else:
Result1 = "wrong"
print (numb1, "+" , numb2, "=" ,answerlist[i], Result1 ,)
If I put totalrounds around 5, on #result print, the question 1 - 4 will have different number from upper list. can anyone tell me what I did wrong in this code and what can i do to make it same like upper list question ?
question = numb1 "+" numb2
thank you for you help

There are several things that are problematic or style related in your code.
In the second for loop you try to access the numb1/numb2 but they are not relevant because each iteration of the first for loop you change them so to overcome this issue you need to store them as well.
There is no need to set range to start from 0, this is the default value.
When initiating a list there is no need to do list() just [] is enough.
a correction to your code is as follows:
import random
Totalrounds = input("Input how many rounds you want try? ")
answerlist = []
numb1_list = []
numb2_list = []
for i in range(int(Totalrounds)):
numb1 = random.randint(0,9)
numb1_list.append(numb1)
numb2 = random.randint(0,9)
numb2_list.append(numb2)
print(numb1, "+" , numb2,)
Answer = int(input("Your answer is? " ))
if Answer == numb1 + numb2 :
print("Your answer is correct")
print()
else:
print("Your answer is wrong")
print("the right answer is ", numb1 + numb2)
print()
answerlist.append(Answer)
#Result
print("this is your Answersheet from" ,Totalrounds, "question")
for i in range(len(answerlist)):
if answerlist[i] == numb1_list[i] + numb2_list[i] :
Result1 = "correct"
print (numb1_list[i], "+" , numb2_list[i], "=" ,answerlist[i], Result1 ,)
else:
Result1 = "wrong"
print (numb1_list[i], "+" , numb2_list[i], "=" ,answerlist[i], Result1 ,)

You store the values of the answers in answerlist but you only store the most recent values of numb1 and numb2 so they are always printed as the same.
If you want to print all the previous questions you should store them in a list too.
Then change the print statement at the end
print (numb1list[i], "+" , numb2list[i], "=" ,answerlist[i], Result1)

Related

Errors pertaining to the "!==" function in Python

I'm currently trying to make a program in Python that basically asks you math problems. For some reason, there's a lot of errors, and I have no idea why, such as the "!==" function, which seems to be incorrect. There might also be some other issues as I've only just started Python. Could someone direct me to how to use the !== function correctly and also my other issue: Making my input for "addition, subtraction, or multiplication" into a possible command?
# import random
import time
choice = 0
counterright = 0
counterwrong = 0
def add_question_to_file(a, b):
with open("wrong_answers.txt", 'a') as f:
f.write(f"{a} {operation} {b}\n")
def test(a,operation,b):
user_input = int(input(f"{a} {operation} {b} = "))
if user_input == a + b:
print("You got it right!")
counterright += 1
while user_input != a + b:
if user_input == a + b:
print("You got it right!")
counterwrong += 1
break
else:
add_question_to_file(a, b)
print("Try Again!")
user_input = int(input(f"{a} + {b} = "))
def get_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
with open("calc_log.txt", 'a') as f:
if a<b: #insures a is always greater than b
a, b = b, a
f.write(f"{a} {operation} {b}\n")
def check_operation():
if operation !==t "+" or "-" or "*"
print("Sorry, that's invalid. You have to choose of the three operations!")
t1=time.perf_counter() #
m = input("What mode would you like to use? Review/Normal. Choose Normal if this is your first time!")
operat ion = input("Which operation would you like to use? +,-,or *?")
if m == "review":
with open("wrong_answers.txt", 'r') as f:
for line in f:
a, operation, b = line.split()
test(int(a), int(b))
elif m == "normal":
num_questions = int(input("How many questions would you like to do? "))
for i in range(num_questions):
print(f"You are on question {i + 1}: ")
get_question()
t2=time.perf_counter() #
print("It took you", t2-t1, "seconds for you to solve this problemset") #
print ("You got",counterright,"correct and",counterwrong,"wrong.")
The reason !== isn't working is because this is not an operator in python. Try using !=. It means not equal too.
The does not equal function in python is !=. The double equal sign (==) is only used when you want to check for equality. I hope this helps!

Apparently I cannot achieve the correct answer, everything I input is wrong? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
Okay so I made my own Multiplication Game for my AS Computing course, but I'm running into a number of issues, mainly this occurring around this line:
if ans == result:
print ("That's right -- well done.\n")
solved = solved + 1
else:
print ("No, I'm afraid the answer is %d.\n" % result)
return solved"
The problem seems to present itself. When playing this Multiplication Game any answer that you input, seems to always be incorrect. I've posted the entire of my game below in hopes that someone can help me <3
Thanks in advance!
from random import *
solved = 0
total_num_q = 0
def play(num1, num2, type, solved):
""" The main play function"""
def sp_type():
type = input("Specify the question type: Multiplication: M, Addition :A, Subtraction: S, Division: D: ")
if type not in ['M','A','S','D']:
print("Please input only enter a valid character: ")
return type
type = ""
while type not in ['M','A','S','D']:
type = sp_type()
if type == "M":
ans = input("What's %d times %d? " % (num1, num2))
result = num1 * num2
if type == "A":
ans = input("What's %d plus %d? " % (num1, num2))
result = num1 + num2
if type == "S":
ans = input("What's %d minus %d? " % (num1, num2))
result = num1 - num2
if type == "D":
ans = input("What's %d divided by %d? " % (num1, num2))
result = num1/num2
if ans == result:
print ("That's right -- well done.\n")
solved = solved + 1
else:
print ("No, I'm afraid the answer is %d.\n" % result)
return solved
All fixed now, just took some tweaking. The issue was solved by Bruno and Chris, the error was that my inputs weren't integers, after changing the inputs, the code is working perfectly. Thanks to everyone who helped!
Not so sure, but have you checked the variable types? num1 and num2 should obviously be numerical (int?). Maybe input is string?

Arthimatic Quiz Not Accepting Correct Answers

I am attempting to make an arithmetic quiz, but have run into this issue: Even if I input the correct answer, it seems to ignore the correct answer code and go straight to the incorrect answer code. Basically, it doesn't accept any right answers.
import random
num1 = (random.randrange(10))
num2 = (random.randrange(10))
correct1 = (num1*num2)
ans1 = input("What is " + str(num1) + " multiplied by " + str(num2) + "? ")
if ans1 == correct1:
print("Correct! ")
if ans1 != correct1:
print(" Incorrect. ")
print(" The correct answer was " + str(ans1))
When ran, I get something like this:
What is 3 multiplied by 0? 0
Incorrect.
The correct answer was 0
Note how the answer and my input were the same, but it ran the code for an incorrect answer. Can anyone help me to fix this? I am using Python 3.4.
3 is not equal to "3". The result of a call to input (in Python3) is a string, not a number.
Call int on the user input
...
ans1 = input("What is " + str(num1) + " multiplied by " + str(num2) + "? ")
ans1 = int(ans1)
...
if int(ans1) == correct1:
print("Correct! ")
else:
print(" Incorrect. ")
print(" The correct answer was " + str(ans1))
You must compare numbers with numbers.
You were comparing '3' vs 3

multiplication game python

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)

How to make sure that first random value is always bigger than the second?

Code:
def Division():
print "************************\n""********DIVISION********\n""************************"
counter = 0
import random
x = random.randint(1,10)
y = random.randint(1,10)
answer = x/y
print "What will be the result of " + str(x) + '/' + str(y) + " ?"
print "\n"
userAnswer = input ("Enter result: ")
if userAnswer == answer:
print ("Well done!")
print "\n"
userInput = raw_input ("Do you want to continue? \n Enter 'y' for yes or 'n' for no.")
if userInput == "y":
print "\n"
Division()
else:
print "\n"
Menu()
else:
while userAnswer != answer:
counter += 1
print "Try again"
userAnswer = input ("Enter result: ")
if counter == 3: break
userInput = raw_input ("Do you want to continue? \n Enter 'y' for yes or 'n' for no.")
if userInput == "y":
print "\n"
Division()
else:
print "\n"
Menu()
In this case I want x value to be always bigger than y value. How to do I do it?
Code for subtraction is similar and the question remains the same, target is to avoid
negative result.
You can check if x < y and swap them e.g.
if x < y:
x, y = y, x
Note in python you can swap two variables without need of a temporary variable.
You can even take further shortcut by using bultin min and max and do it in a single line e.g.
x, y = max(x,y), min(x,y)
In addition to Anrag Uniyal's answer, you might also try this:
y,x = sorted([x,y])
You can do randint between x and 10 to get a number greater than x:
x = random.randint(1,10)
y = random.randint(x,10)

Categories