Problems with python math - python

I'm creating program which will teach my little brother math. But for example, when program is saying 2 + 2, and I enter 4 it's saying "Incorrect!". What am I doing wrong?
import random
import math
def addition():
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")#this is the line with problem
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()

result is an integer (e.g., 4), and the inputed guess is a string (e.g., '4'). You need to convert them to the same type in order to compare them. E.g.:
result = str(num1 + num2)

Wrap the answer to int
guess = int(input(str(num1) + " + " + str(num2) + " = "))

typecast the input to int:
import random
import math
def addition():
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")
guess = int(guess) #input is string and it must be typecast to int
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()

Related

Can I use something else to shorten the code rather than using mutiple IF in python?

I use IF multiple times however there is little change between each if, is there another way to code it to condense the amount line of code to make it look neater?
def StringAll():
global print1, print2, print3
print1,print2,print3 = str(Number1), str(Number2), str(answer)
return
def MathStuff():
global MATH, answer
try: MATH = int(input("1 for +, 2 for -, 3 for *, 4 for/"))
except ValueError:
print("Only input number")
MathStuff()
if MATH == 1:
answer = Number1 + Number2
StringAll()
print(print1 + " + " + print2 + " = " + print3)
elif MATH == 2:
answer = Number1 - Number2
StringAll()
print(print1 + " - " + print2 + " = " + print3)
elif MATH == 3:
answer = Number1 * Number2
StringAll()
print(print1 + " * " + print2 + " = " + print3)
elif MATH == 4:
answer = Number1 / Number2
StringAll()
print(print1 + " / " + print2 + " = " + print3)
else:
print("You can only input number 1-4")
MathStuff()
Well to reduce the lines means we can not only reduce if else but also optimize other lines that may be unneccesary e.g.
VERSION 1 (Renaming StringAll to Display)
Number1 = float(input('Enter a number 1'))
Number2 = float(input('Enter a number 2'))
def Display(operator, ans):
print(Number1, operator, Number2, '=', ans)
return
def MathStuff():
global MATH, answer
try: MATH = int(input("1 for +, 2 for -, 3 for *, 4 for/"))
except ValueError:
print("Only input number")
MathStuff()
if MATH == 1:
Display('+', Number1 + Number2)
elif MATH == 2:
Display('-', Number1 - Number2)
elif MATH == 3:
Display('*', Number1 * Number2)
elif MATH == 4:
Display('/', Number1 / Number2)
else:
print("You can only input number 1-4")
MathStuff()
Many lines are reduced as we eliminated many variables
VERSION 2 (Even further removing Display function itself)
Number1 = float(input('Enter a number 1'))
Number2 = float(input('Enter a number 2'))
def MathStuff():
global MATH, answer
try: MATH = int(input("1 for +, 2 for -, 3 for *, 4 for/"))
except ValueError:
print("Only input number")
MathStuff()
if MATH == 1:
print(Number1, '+', Number2, '=', Number1 + Number2)
elif MATH == 2:
print(Number1, '-', Number2, '=', Number1 - Number2)
elif MATH == 3:
print(Number1, '*', Number2, '=', Number1 * Number2)
elif MATH == 4:
print(Number1, '/', Number2, '=', Number1 / Number2)
else:
print("You can only input number 1-4")
MathStuff()
or for the ultimate optimization we can even remove these if else for even more shorter approach
VERSION 3 (using eval)
Number1 = input('Enter a number 1')
Number2 = input('Enter a number 2')
mapping = { 1: '+', 2: '-', 3: '*', 4: '/'}
def MathStuff():
global MATH, answer
try: MATH = int(input("1 for +, 2 for -, 3 for *, 4 for/"))
except ValueError:
print("Only input number")
MathStuff()
if MATH >= 1 and MATH <= 4:
ans = eval(Number1 + mapping[MATH] + Number2)
print(Number1, mapping[MATH], Number2, '=', ans)
else:
print("You can only input number 1-4")
MathStuff()
MathStuff()
Didn't tested the code, but that's a hint for you after a minor bug fixing just in case if there are you can achieve few lines optimization.
If you are using the latest python version (3.10), you can use the match case statement.
Have a look at this to get started.
Your function could then look like this:
def MathStuff():
global MATH, answer
try: MATH = int(input("1 for +, 2 for -, 3 for *, 4 for/"))
except ValueError:
print("Only input number")
MathStuff()
match MATH:
case 1:
answer = Number1 + Number2
StringAll()
print(print1 + " + " + print2 + " = " + print3)
case 2:
answer = Number1 - Number2
StringAll()
print(print1 + " - " + print2 + " = " + print3)
case 3:
answer = Number1 * Number2
StringAll()
print(print1 + " * " + print2 + " = " + print3)
case 4:
answer = Number1 / Number2
StringAll()
print(print1 + " / " + print2 + " = " + print3)
case _:
print("You can only input number 1-4")
MathStuff()
Of course this is only one of many ways to clean up this code (as already pointed out by others here), but at least you will get rid of the many if statements. You could still further clean up from here.
Note: I have not tested this code example.

My Python 3 file code is not appending nor reading right to a file

I did a calculator code which works perfectly fine, but I need to append the results on a text file and/or read from the text file. I've done most of it but I'm having some errors which I need help with
-When I append the result, it just prints "5.098.042.0..." and it is supposed to be printing like this
"5 + 3 = 8
7 * 3 =43..."
It does show it in the code, but for some reason it just prints the result in the text
Please help, any suggestions to save work in the future or anything will be appreciated, thanks!
def menu():
print("\t1. Addition")
print("\t2. Substraction")
print("\t3. Multiplication")
print("\t4. Division")
print("\t5. Show")
print("\t6. Quit")
def option(min, max, exi):
option= -1
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
while (option < min) or (option > max):
print("\n\t>>> Error. Invalid option.")
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
return option
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
print("\n\t-> The result of " + str(num1) + " + " + str(num2) + "= ", answer)
return answer
def subs():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 - num2
print("\n\t-> The result of " + str(num1) + " - " + str(num2) + "= ", answer)
return answer
def mult():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
answer = num1 * num2
print("\n\t-> The result of " + str(num1) + " * " + str(num2) + "= ", answer)
return answer
def div():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
if num2 != 0:
answer = num1 / num2
print("\n\t-> The result of " + str(num1) + " / " + str(num2) + "= ", answer)
else:
print("\n\t>>> Error. Division by zero.")
answer= "Error. Division by zero."
return answer
def result(r):
print("\n\t The last result was" , r)
def ex():
print("Goodbye")
def main():
solution = 0
op= -1
while op != 6:
op = option(0, 6, 0)
if op == 1:
solution = str(add())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 2:
solution = str(subs())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 3:
solution = str(mult())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 4:
solution = str(div())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 5:
with open ("myResultt.txt","r") as f:
for line in f:
print(line)
else:
solution = ex()
with open ("myResultt.txt","r") as f:
f.close()
main()
You prompt for the operands in the sum and etc... functions. If you want those operands to appear in the result file, you either have to return them along with the answer, or do the write in the function itself. For example,
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
result = "{} + {} = {}".format(num1, num2, answer)
print("\n\t-> The result of " + result)
with open ("myResultt.txt","a") as f:
f.write(result + "\n")
return answer

Easy class questions on joining

I need to have the output look like this: "The sum of (num1) and (num2) is (num3) and (num1)>(num2)." or visa versa with which number is bigger. I cannot figure out how to append or join these strings together without getting error codes. The + and \ are not working to join them and I even tried to make another string with a new name for it and join them all together.
CODE:
num1 = int(input("Enter number 1:"))
num2 = int(input("Enter number 2:"))
num3 = num1 + num2
print (" The sum of", (num1))
print ("and", (num2))
print ("is:", (num3))
the_text = "".join([ "The sum of", (num1), "and", (num2), "=" (num3)])
if num1 > num2:
print ("The number", (num1))
print (">")
print (num2)
elif num2 > num1:
print ("The numer", (num2))
print (">")
print (num1)
else:
print (num1)
print ("=")
print (num2)
input ("Press enter to close.")
Assuming the language required is Python,
comparison_result = ""
if num1 > num2:
comparison_result = ">"
elif num1 < num2:
comparison_result = "<"
else:
comparison_result = "="
the_text = "The sum of " + str(num1) + " and " + str(num2) + " is " + str(num1 + num2) + " and " + str(num1) + comparison_result + str(num2)
You just need to typecast the int as str.
You can use formatting:
cmp_char = ""
if a > b:
cmp_char = ">"
elif a < b:
cmp_char = "<"
else:
cmp_char = "="
print "The sum of {} and {} is {} and {} {} {}".format(num1, num2, num3, num1, cmp_char, num2)

Python code not working - returning "Incorrect" [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
So, once I ran the code, the question() returns 'Incorrect', even I'm pretty sure that I put in the right answer.
P.S. The operator() function is alright I checked it; it's only the question() that needs attention.
import random
def numberRan(): # Generate a random number
return random.randint(1, 10) # No arguments needed for this
def operator():
operator = ""
number = random.randint(1, 3)
if number == 1:
operator = "+"
elif number == 2:
operator = "-"
else:
operator = "x"
return operator
def question():
num1 = numberRan()
num2 = numberRan()
realAnswer = 0
int(realAnswer)
oper = operator()
answer = input(str(num1) + str(oper) + str(num2) + "= ")
if oper == "+":
realAnswer = num1 + num2
elif oper == "-":
realAnswer = num1 - num2
elif oper == "x":
realAnswer = num1 * num2
if realAnswer == answer:
return "Correct"
else:
return "Incorrect"
question()
You never convert your answer to an int, so your answer (the result of input(...) is still a str. You're then comparing that str to realAnswer, which is an int: comparing an int and str will be always False.
Just change one line:
answer = input(str(num1) + str(oper) + str(num2) + "= ")
to
try:
answer = int(input(str(num1) + str(oper) + str(num2) + "= "))
except ValueError:
import sys
sys.stderr.write("your input was not an integer number")
return "Incorrect"
if oper == "+":
...
Note the try-except clause: now, there's an explanatory error message if the input was not a number.

Defining Functions, TypeError

Probably obvious, but for some reason, this code:
import random
import time
def tables():
global tablesUsed
tablesUsed = [int(x) for x in input("Please choose which multiplication tables you wish\nto practice, then type them like this: 2 5 10.\n").split()]
return tablesUsed
def timer():
timer = input("Do you wish to play with the timer? (yes or no)\n")
if timer == "yes":
withTimer()
else:
withoutTimer()
def withTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
start = time.time()
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
if elapsed < 2:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
else:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def withoutTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
print("Congratulations, you got it correct!\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def playAgain():
playAgain = input("Do you wish to play again? (yes or no)\n")
if playAgain == "yes":
settings()
else:
print("Thank you for practising your multiplication tables with me. Your final score was " + score + " and your average time was " + averageTime)
def settings():
settings = input("Do you wish to edit settings? (yes or no)\n")
if settings == "yes":
tables()
timer()
tables()
timer()
returns an error saying:
TypeError: 'str' object is not callable, line 66, line 10, line 35
Please could someone help and tell me what I'm doing wrong?
I gather that it's probably to do with defining functions incorrectly, but I can't find anything on that solves my problem.
You defined playAgain both as a function and a local variable in the withTimer function:
def withTimer():
playAgain = "yes"
# ...
while playAgain == "yes":
# ....
playAgain() # this is now a string, not the function
Don't do that, use meaningful names that don't shadow your function names.

Categories