I'm VERY new to programming (as in, in an intro class) and python. My assignment is to prompt a user to answer math questions, count the number they got correct/incorrect, calculate/display their numeric grade, and display their letter grade.
Everything seems to be working fine.. except I can't figure out how to get it to count the number of correct/incorrect answers. Any help?
def main():
name = input("What is your name? ")
correct = 0
incorrect = 0
ans = int(input("What is 4 + 5? "))
val = add(4, 5)
if(ans == val):
correct + 1
else:
incorrect + 1
ans2 = int(input("What is 20 * 6? "))
val2 = mult(20, 6)
if(ans2 == val2):
correct + 1
else:
incorrect + 1
ans3 = int(input("What is 14 - 10? "))
val3 = sub(14, 10)
if(ans3 == val3):
correct + 1
else:
incorrect + 1
ans4 = int(input("What is 30 / 5? "))
val4 = div(30, 5)
if(ans4 == val4):
correct + 1
else:
incorrect + 1
ans5 = int(input("What is 29 + 2? "))
val5 = add(29, 2)
if(ans5 == val5):
correct + 1
else:
incorrect + 1
ans6 = int(input("What is 50 - 10? "))
val6= sub(50, 10)
if(ans6 == val6):
correct + 1
else:
incorrect + 1
ans7 = int(input("What is 5 * 11? "))
val7 = mult(5, 11)
if(ans7 == val7):
correct + 1
else:
incorrect + 1
ans8 = int(input("What is 9 / 3? "))
val8 = div(9, 3)
if(ans8 == val8):
correct + 1
else:
incorrect + 1
ans9 = int(input("What is 90 - 5? "))
val9 = sub(90, 5)
if(ans9 == val9):
correct + 1
else:
incorrect + 1
ans10 = int(input("What is 412 + 5? "))
val10 = add(412, 5)
if(ans10 == val10):
correct + 1
else:
incorrect + 1
print()
print("Thanks, " + str(name) + "!")
print()
print("Correct " + str(correct))
print()
print("Incorrect " + str(incorrect))
print()
calcGrade(correct)
def add(value, value2):
return value + value2
def sub(value, value2):
return value - value2
def mult(value, value2):
return value * value2
def div(value, value2):
return value / value2
def calcGrade(correct):
grade = (correct * 100)/ 10
print("Numeric Grade " + str(grade))
if(grade > 90):
letterGrade = "A"
if(grade > 80):
letterGrade = "B"
if(grade < 70):
letterGrade = "C"
if(grade < 69):
letterGrade = "F"
print()
print("Letter Grade " + str(letterGrade))
main()
When you write correct + 1 you are evaluating what correct plus one is equal to, but you aren't updating the value stored in correct.
What you want to put instead is correct = correct + 1. Or, more succinctly, correct += 1.
The same applies to incorrect.
Every programming language has some specific features which you can use for different purposes. In Python, there is this function called eval() which is very useful for your case ...
Here is an example if its use:
In [2]: eval('2*3'), eval('12+13'), eval('30/5')
Out[2]: (6, 25, 6)
Notice that you do the same set of operations many times:
Print a prompt
Input a number
evaluate another number
see of the two numbers are equal
increment respective counters
In Python (or in many other languages), these would be done in a loop. For this, you need to create a list if things you want to loop over. The list will look like this:
In [4]: qns
Out[4]:
['4+5',
'20*6',
'14-10',
'30/5',
'29+2',
'50-10',
'5*11',
'9/3',
'90-5',
'412+5']
At this point, you can use something called list comprehension to get all the results ...
In [5]: [input('what is ' + q + '?') for q in qns ]
what is 4+5?9
what is 20*6?12
what is 14-10?34
what is 30/5?6
what is 29+2?31
what is 50-10?40
what is 5*11?50
what is 9/3?2
what is 90-5?85
what is 412+5?417
Out[5]: [9, 12, 34, 6, 31, 40, 50, 2, 85, 417]
Now you need to compare them with the actual values. You can actually put the comparison within the list comprehension into a single operation.
In [6]: results = [input('what is ' + q + '?') == eval(q) for q in qns ]
what is 4+5?9
what is 20*6?12
what is 14-10?34
what is 30/5?6
what is 29+2?31
what is 50-10?40
what is 5*11?50
what is 9/3?2
what is 90-5?85
what is 412+5?417
In [7]: results
Out[7]: [True, False, False, True, True, True, False, False, True, True]
In Python, it turns out that True == 1 and False == 0 for some cases. Which cases you ask? Well, that's something that comes with experience in something called duck typing. So in a couple of months, with enough experience, you will find the answer to "which cases" almost trivial. Anyway, because of this phenomenon, you can count the right answers as:
In [8]: sum(results)
Out[8]: 6
And the incorrect answers?
In [9]: len(qns) - sum(results)
Out[9]: 4
Cheers, and happy programing!
you have some mistakes with your code. Please try to this. correct +=1 or correct = correct + 1 and incorrect -=1 and incorrect = incorrect - 1
correct = correct + 1
incorrect = incorrect + 1
By doing this, the current value of the correct/incorrect answers is incremented and stored in the same variable, basically, this is a counter, for the number of correct and incorrect answers
Related
I'm here with my code, here you can see it:
def generate_integer(level):
score = 0
i = 0
false = 0
level = int(level)
while i != 10:
# Choosing the numbers of digit if 1 >> 1-9 / if 2 >> 11-99 / if 3 >> 100-999
end = 10**level-1
# Define x and y
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
# Users cal
user = int(input(f'{x} + {y} = '))
if user == answer:
score = score + 1
while user != answer:
false + 1
print('EEE')
user = int(input(f'{x} + {y} = '))
if false == 3:
print(f'{x} + {y} = {answer}')
i = i + 1
print(f'score: {score}/10')
Let me explain: I defined false for, if user inputs the answer 3 times and all of them for that question are false, show user the answer and continue asking
Actually this code asks 10 different math questions, this is a part of my code, I'm checking if answer is not true print('EEE') and re ask it again, but if user tries 3 time and all incorrect, then I show the answer, pass that question and keep asking other questions.
If you have any ideas for re asking question, when users input was non-numerical, I'll be thankful.
You just have an indentation wrong
def generate_integer(level):
score = 0
i = 0
false = 0
level = int(level)
while i != 10:
# Choosing the numbers of digit if 1 >> 1-9 / if 2 >> 11-99 / if 3 >> 100-999
end = 10**level-1
# Define x and y
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
# Users cal
user = int(input(f'{x} + {y} = '))
if user == answer:
score = score + 1
while user != answer:
false + 1
print('EEE')
user = int(input(f'{x} + {y} = '))
if false == 3:
print(f'{x} + {y} = {answer}')
break
i = i + 1
print(f'score: {score}/10')
Would probably work, because you want to be checking for how many times they messed up within the while loop.
OTHER PIECES OF ADVICE
I would also rename false to num_incorrect_tries, and replace 10**level-1 with 10**(level-1)
You can also just for for i in range(11), instead of doing a while loop, and incrementing i
What you can do is ask for the input in a separate function inside of a while True loop that only exits when it detects the input to be an integer. In my example below the getint function does just that.
I made a few other minor adjustments to your function to simplify it a little as well. I have tested and can confirm it does work the way you describe.
I left some inline notes to explain where I made changes
import random
def getint(x,y):
while 1:
user = input(f'{x} + {y} = ') # get user input
if user.isdigit(): # check if it is an integer
return int(user) # return integer value
print("Non-Integer Input Detected: Try Again") # print Error
def generate_integer(level):
score = false = i = 0 # all three are zero
level = int(level)
while i != 10:
end = 10**level-1
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
while getint(x, y) != answer: # while the user input != answer
false += 1 # increment false number
if false == 3: # if 3 wrong answers
print(f'{x} + {y} = {answer}') # print the answer
false = 0 # reset false
break # end while loop
print('EEE') # show error
else:
score = score + 1 # increase score for correct answer
i = i + 1
print(f'score: {score}/10')
def check(user_answer,correct_answer):
for a chance in range(2):
print("Wrong answer, try again")
user_answer=input('User please type your answer for the question')
if user_answer == correct_answer:
return 'True' # Given the Right answer
else:
print('Again wrong answer')
return 'False' #Given all wrongs answers
user_answer=input('User please type your answer for the question')
correct_answer=10
if user_answer != correct_answer:
result=check(user_answer,correct_answer)
if result:
print("your answer is correct")
else:
print("your all answers were wrong, the right answer is: ",correct_answer)
else:
print("Perfect your answer was right in the first guess")
I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)
When I assign the out_of_marks_limit = True in 5th block, I want the first block of if statement to be "True" and I don't want the code to loop or ask the user anymore.
In other programming language indentation is used to make the program look good. But because python only checks the condition of first block to the same indent, I can't assign boolean of 2 block of code to the first block.
This is what I'm trying to say.
I'm an intermediate level programmer and this program is just for practice purpose.
a = int(input("Enter no. of subjects: "))
count = 1
d = 0
out_of_marks_limit = False #I want the out_of_limit to be True
if a <= 10:
if not out_of_marks_limit:
if count <= a:
for c in range(a):
b = float(input("Enter mark of subject " + str(count) + ": "))
if b <= 100: #If this condition went false then it will skip to else statement
d += b
count += 1
if count > a:
cal = round(d/a, 2)
print("Your percentage is " + str(cal) + "%")
else:
out_of_marks_limit = True #So this boolean value should passed to the first line of code
print("Marks enter for individual subject is above 100")
else:
print("Subject limit exceeded")
I expect the output to print("Marks enter for individual subject is above 100"), if out_of_marks_limit is True and don’t want to loop anymore
I think you can use a while loop to check your out_of_marks_limit condition:
a = int(input("Enter no. of subjects: "))
count = 1
d = 0
out_of_marks_limit = False #I want the out_of_limit to be True
while not out_of_marks_limit:
if a <= 10:
if not out_of_marks_limit:
if count <= a:
for c in range(a):
b = float(input("Enter mark of subject " + str(count) + ": "))
if b <= 100: #If this condition went false then it will skip to else statement
d += b
count += 1
if count > a:
cal = round(d/a, 2)
print("Your percentage is " + str(cal) + "%")
else:
out_of_marks_limit = True #So this boolean value should passed to the first line of code
print("Marks enter for individual subject is above 100")
else:
print("Subject limit exceeded")
When I choose question 3, even I do put in the right answer(value_c * value_d, it tells me that it is incorrect. Help?
import random
value_a = random.randint(100, 999)
value_b = random.randint(100, 999)
value_c = random.randint(21, 89)
value_d = random.randint(21, 89)
value_e = random.randint(81, 100)
value_f = random.randint(81, 100)
print('''Straight to the point. Pick an option.
1. 2 numbers with 3-digit values added.")
2. 2 numbers with 3-digit values added and then multiplied by 2.
3. 2 numbers with 2-digit values and less than 89 multiplied.
4. 2 numbers with 2-digit values and between 80 and 100 multiplied.
5. 3 random numbers added or subtracted.''')
question = int(input("Choose the type of question you want: "))
print("\n")
if question == 1:
answer = int(input(str(value_a) + " + " + str(value_b) + " : "))
if answer == value_a + value_b:
print("Dayum quicc mafs, trie again if yu wand.")
else:
print("Bed mafs.")
elif question == 2:
answer = int(input( "(" + str(value_a) + "+" + str(value_b) + ")"+ "*2" + " : "))
if answer == 2*(value_a + value_b):
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
this is the part where my answer never seems to be right:
elif question == 3:
answer == int(input(str(value_c) + " * " + str(value_d) + " : "))
print(value_c, value_d)
if answer == value_c * value_d:
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
In Python, a single = means assignment. You used a double == which is an equality operator. Don't confuse the two, since the answer is not being assigned. Below I have changed the == to =.
elif question == 3:
answer = int(input(str(value_c) + " * " + str(value_d) + " : "))
print(value_c, value_d)
if answer == (value_c * value_d):
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
Q: Why does my count function only count as high as one when I have multiple integers?
CODE:
import random
while True:
value = 0
count = 0
right_counter = 0
value = int(input("Enter the amount of questions would you like to answer: "))
AVG = right_counter / value
if 0<=value<=10:
for i in range(value):
numb1 = random.randint(0, 12)
numb2 = random.randint(0, 12)
answer = numb1 * numb2
AVG = right_counter / value
problem = input("What is " + str(numb1) + " * " + str(numb2) + "? ")
right_counter =+ 1
if int(problem) == answer:
print("You are Correct! Great Job!".format(right_counter))
elif int(problem) > answer:
print("Incorrect, Your answer is too high!")
elif int(problem) < answer:
print("Incorrect, your answer is too low!")
print("You got",right_counter,"out of",value,"correct, giving you an average of ",AVG,"")
break
else:
print(" Error, Please type a number 1-10 ")
This is what the output looks like:
Enter the amount of questions would you like to answer: 3
What is 1 * 8? 8
You are Correct! Great Job!
What is 11 * 11? 122
Incorrect, Your answer is too high!
What is 1 * 7? 7
You are Correct! Great Job!
You got 1 out of 3 correct, giving you an average of 0.3333333333333333
I found some help on Tutorial, but I couldn't answer my question.
bug:
right_counter =+ 1
This is (insidiously) equivalent to
right_counter = 1
you probably meant
right_counter += 1
You probably also want to address the logic issue that right_counter is incremented regardless of the correctness of the answer.