I am currently taking a course to learn Python and I am currently stuck. The task I am trying to accomplish is to be able to have the user input 2 numbers and an operator and to have the program make the appropriate calculation. for example:
if the user inputs: "2,3,+"
the output should be: 5
Instead, I am getting the output of: "['2', '3', '+']
Here is the code that I am currently using:
def Add(num1, num2):
return num1 + num2
def Subtract(num1, num2):
return num1 - num2
def Multiply(num1, num2):
return num1 * num2
def Divide(num1, num2):
try:
return num1 / num2
except ZeroDivisionError:
print("Sorry, A number can't be divided by 0")
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
Add(num1, num2)
elif astring[2] == "-":
Subtract(num1, num2)
elif astring[2] == "*":
Multiply(num1, num2)
elif astring[2] == "/":
Divide(num1, num2)
p1 = input("Enter two numbers and an operator with each separated by a comma: ")
scalc(p1)
I am very new to programming and taking this course online has been challenging since I cant have an instructor present to look over my shoulder as I am trying to work through a problem. This is also my first time posting on this website so I hope I got the formatting correct and that this isn't too difficult to read. Any help here would be greatly appreciated.
Your code works perfectly. You've received your results after calling the functions but have never printed them.
if astring[2] == "+":
print(Add(num1, num2))
elif astring[2] == "-":
print(Subtract(num1, num2))
You could also return those values, and print(scale(p1)).
I tried doing this:
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
return Add(num1, num2)
elif astring[2] == "-":
return Subtract(num1, num2)
elif astring[2] == "*":
return Multiply(num1, num2)
elif astring[2] == "/":
return Divide(num1, num2)
p1 = input("Enter two numbers and an operator with each separated by a comma: ")
scalc(p1)
but the result is still the same, where the output is a list instead of the desired function being run.
Related
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator.")
except ValueError:
print("Enter valid inputs.")
Want to write a statement to continue running the calculator after the answer is shown as output. Example, 2.0 + 2.0 = 4.0
I want the code to ask 'Do you want to continue operations with 4? Type 'y' for yes and 'n' for no.'
And then let's say I enter the multiply operator again, and another number to do the calculation with, it should show, 4.0 * 2.0 = 8.0
Okay, as stated in the comments to your original question, you were super close. All you needed to do is wrap your logic in a loop so you can iterate over the items, which I do in my example below with a while True loop. Then outside of that loop, you needed to track a value that the user creates...for example:
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
try:
# track this value out of loop so it isn't reset
tracked_value = None
# make a continuous loop...
while True:
# anything here will reiterate unless broken
# tracked_value will always be none unless the user opts to reuse it below...
if tracked_value is None:
num1 = float(input("Enter first number: "))
else:
# now we can turn num1 into the tracked value, the user wishes to reuse it
num1 = tracked_value
print(f'You opted to reuse the tracked value for number 1, which was: "{num1}"')
# always will be asked.
num2 = float(input("Enter second number: "))
# print options
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
# honestly I would alter your dict to remove the need for
# this huge conditional, but I didn't want to change too much
# ex: method = operations.get(operator, None)... if method not None: answer = method(num1, num2)
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator. Try again...")
# 'continue' so you don't hit the code below, this starts the loop again
continue
# now logic is done, ask if they wish to continue or break
should_continue = input(f"Do you want to continue your calculation with your current answer: '{answer}'? "
"Type 'y' for yes and anything else for no. ")
# logic to continue or not, remember continue starts the iteration over
if should_continue.lower() in ['y', 'yes']:
# assign the tracked value now the user wants it.
tracked_value = answer
continue
else:
print('Thanks for using my calulator. See you next time.')
# break out of the while loop, the user opts to exit.
break
except ValueError as ex:
print(f"Enter valid inputs: {ex}")
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return(n1 * n2)
def div(n1, n2):
return n1 / n2
def pow(n1, n2):
return n1 ** n2
operations = {
"+ = Add": add,
"- = Subtract": sub,
"* = Muliply": mul,
"/ = Division": div,
"** = Power": pow
}
def calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
for sym in operations:
print(sym)
operator = input("Pick an operator from the line above: ")
if operator == "+":
answer = add(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "-":
answer = sub(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "*":
answer = mul(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "/":
answer = div(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
elif operator == "**":
answer = pow(num1, num2)
print(f"{num1} {operator} {num2} = {answer}")
else:
print("Enter a valid operator.")
except ValueError:
print("Enter valid inputs.")
calculator()
should_continue = input("Do you want to continue your calculation with your current answer? Type 'y' for yes and 'n' for no. ")
if should_continue == 'y':
should_continue = True
else:
should_continue = False
print("Thank you for using the calculator.")
while should_continue:
calculator()
break
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
print(num1*num2)
elif op == "/":
print(num1/num2)
elif op == "-":
print(num1-num2)
elif op == "+":
print(num1+num2)
else:
print("Error 404")
print(cal(num1, num2))
this code runs right but says "none" at the end why?
Your code actually works. The problem with your code is that when you call calc() inside the print function, it tries to look for value that might be provided within the calc function (via the return statement). Since you did not return any value within your function, the interpreter cannot find the correct "value" to print. Note that none is a data type in Python. To solve the problem you can just change the print statements inside the if...else statement to a return statement. This way, when the operator is provided by the user, it will compute the result and return the result to the calc()'s function caller.
Here is the complete version of what you are trying to achieve:
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "":
input("Nothing entered. Please enter an operator. ")
elif op == "/":
return num1/num2
elif op == "-":
return num1-num2
elif op == "+":
return num1+num2
else:
return "Error 404")
print(cal(num1, num2))
As you have not provided a value for your function to return the Python interpreter returns a value for you. So when your print() calls your function cal the function returns nothing or put another way returns a value of None and that's what your print() statement prints.
Compare your code with the following where a value is returned to the print() statement,
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2, op):
if op == "*":
cal_val = num1 * num2
elif op == "/":
cal_val = num1 / num2
elif op == "-":
cal_val = num1-num2
elif op == "+":
cal_val = num1 + num2
else:
cal_val = "Error 404"
return cal_val
print(cal(num1, num2, op))
Alternatively you could leave your code as it is and just call your cal() function without the print() wrapped around it. As below,
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
print(num1*num2)
elif op == "/":
print(num1/num2)
elif op == "-":
print(num1-num2)
elif op == "+":
print(num1+num2)
else:
print("Error 404")
cal(num1, num2)
Change your print statements in function to return statements, otherwise the function will be implemented, and it will print the result in console, but at your print statement you will get none.
because - when you use "Print" - you simply print a value in the console.
When you use "Return" - you get a value from a function.
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
return(num1*num2)
elif op == "/":
return(num1/num2)
elif op == "-":
return(num1-num2)
elif op == "+":
return(num1+num2)
else:
return("Error 404")
print(cal(num1, num2))
Try this instead
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
def cal(num1, num2):
if op == "*":
return num1*num2
elif op == "/":
return num1/num2
elif op == "-":
return num1-num2
elif op == "+":
return num1+num2
else:
return "Error 404"
print(cal(num1, num2))
I have made a calculator in python3.
class simple_oper:
def __init__(self):
pass
#staticmethod
def add(num1, num2):
return num1 + num2
#staticmethod
def subtract(num1, num2):
return num1 - num2
#staticmethod
def mul(num1, num2):
return num1 * num2
#staticmethod
def div(num1, num2):
return num1 / num2
def get_int(input_message, tm):
num = input(input_message)
try:
return int(num)
except:
return get_int(tm, tm)
if __name__ == '__main__':
num1 = get_int("Please enter the first number : ", "Please enter the correct number : ")
l = ["+", "-", "*", "/"]
#c = simple_oper
while True:
oper = str(input("Please enter the operand to do : "))
if oper == "=":
print("You typed = printing result")
break
elif oper not in l:
print("Ypu typed incorrect operand. aborting and printing result")
break
num2 = get_int("please enter the number : ", "please enter the correct number")
if oper == "+":
num1 = simple_oper.add(num1, num2)
if oper == "-":
num1 = simple_oper.subtract(num1, num2)
if oper == "*":
num1 = simple_oper.mul(num1, num2)
if oper == "/":
num1 = simple_oper.div(num1, num2)
print(num1)
Now I want to write unit test for it. But the problem here is that my code takes many user inputs. So how do I write such a unit test that it can give inputs to my code.
In general, when you write classes in any language, you would generally leave the user input outside of the class, in a separate file. For unit testing, you wouldn't test input, you'd test the logic of the class itself. Your unit test would look something like this:
import unittest
from simple_oper import simple_oper
class Test_Simple_oper(unittest.TestCase):
def test_add(self):
self.assertEqual(simple_oper.add(3,3), 9)
self.assertEqual(simple_oper.add(-10,4), 6)
if __name__ == '__main__':
unittest.main()
You get it, something like that. You'd add more methods until you test all your methods in simple_oper. The unit test tests the program's logic, where you test many possibilities that the user can put, not user input.
So I'm building my first calculator.
import math
# Adding two numbers
def add(num1, num2):
return num1 + num2
#Substract two numbers
def subst(num1, num2):
return num1 - num2
#Multiply two numbers
def multi(num1, num2):
return num1 * num2
#Divide two numbers
def divide(num1, num2):
return num1 / num2
#Exponentiation of number
def expont(num1, num2):
return pow(num1, num2)
#Square root
def sqrt(num1):
return math.sqrt(num1)
#Sin
def sin(num1):
return math.sin(num1)
#Cosinus
def cos(num1):
return math.cos(num1)
#Tangent
def tan(num1):
return math.tg(num1)
print("Select your operation: \n"
"1.Add\n"
"2.Substract\n"
"3.Multiply\n"
"4.Divide\n"
"5.Exponentiation\n"
"6.Square root\n"
"7.Sine\n"
"8.Cosine\n"
"9.Tangent")
operation = input("Select your operation 1, 2, 3, 4, 5, 6, 7, 8 ,9: ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operation == "1":
print(add(num1,num2))
elif operation == "2":
print(subst(num1,num2))
elif operation == "3":
print(multi(num1,num2))
elif operation == "4":
print(divide(num1, num2))
elif operation == "5":
print(expont(num1,num2))
elif operation == "6":
print(sqrt(num1))
elif operation == "7":
print(sin(num1))
elif operation == "8":
print(cos(num1))
else:
print(tan(num1))
But I have a problem when I try to sine, cosine and tanget. As you see I want to take only one value, which is num1, but program is asking me to enter num2.
How can I prevent or maybe disable/delete the num2 for operation >= 7
I've tried using if, while statements, as well as del. But it doesn't work.
What should I do to disable num2 variable for operations that are bigger or equal to 7?
import random # imports the random module
user_class = "" # Global variable
question_counter = int(0) # sets counter
amount_correct = int(0) # sets score
possible_operators = ("+","-","x") # creates a list of operators
while user_class == "": # Indefinite iteration - Runs until a valid class is given
user_class = str(input("Please enter your class"))
if user_class == "Rainbow": # Testing variable class - Will not crash the program
class_file = open("RainbowClass.txt","a")
elif user_class == "Sun":
class_file = open("SunClass.text","a")
elif user_class == "Moon":
class_file = open("MoonClass.text","a")
else:
print("Not quite. Try again:")
user_class = ""
name = str(input("Please enter your name"))
while question_counter < 10: # Indeffinate iteration – number of questions
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators) # Chooses one of the operators from the list
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
print("What is the answer to ", num1," "+operator+"" ,num2,"?")
user_answer = int(input())
if user_answer == answer:
question_counter = question_counter + 1
amount_correct = amount_correct + 1
print("Correct!")
else:
print("Incorrect")
question_counter = question_counter + 1
final_score = amount_correct
print("Well Done! You scored",amount_correct,"out of",question_counter,".")
amount_correct = str(amount_correct)
class_file.write(user_class)
class_file.write(name)
class_file.write(amount_correct + "\n")
class_file.close
This is my code. It does not get any errors when I run it but I am trying to get the user's class and open a text file according to the input. The file is opening but when it comes to the bottom it is not writing the data from the quiz that is inside the variables that I want it to.
What is the solution to this?
Untested crack at this (sorry, Python is on another system). Ill break it up into chunks:
import random
# Got rid of your global 'user_class'
# Moved the counter(s) to local function variables
# Moved the operator options to local function variables
Now to tackle your first while, I would do:
def get_class_file():
while True:
# Don't need to call str(); input() returns a 'str'
user_class = input("Please enter your class: ")
if user_class == "Rainbow":
class_file = "RainbowClass.txt"
break
elif user_class == "Sun":
class_file = "SunClass.txt"
break
elif user_class == "Moon":
class_file = "MoonClass.txt"
break
else:
print("Not quite. Try again...")
return class_file
Keep this:
# Don't need to call str(); input() returns a 'str'
name = input("Please enter your name: ")
Now for the second while, a similar function:
def get_score():
# Don't need to call int()
question_counter = 0
amount_correct = 0
# Make this a tuple sequence; they are immutable
possible_operators = ("+","-","x",)
while True:
if question_counter < 10:
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators)
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
user_answer = int(input("What is the answer to: "
+ str(num1) + operator + str(num2) + "?\n"))
# Take out of the if/else since we always increment
question_counter += 1
if user_answer == answer:
amount_correct += 1
print("Correct!")
else:
print("Incorrect!")
else:
break
return amount_correct
Lets put it all together, and see how we get the variables and then how to write them to your files:
import random
def get_class_file():
while True:
# Don't need to call str(); input() returns a 'str'
user_class = input("Please enter your class: ")
if user_class == "Rainbow":
class_file = "RainbowClass.txt"
break
elif user_class == "Sun":
class_file = "SunClass.txt"
break
elif user_class == "Moon":
class_file = "MoonClass.txt"
break
else:
print("Not quite. Try again...")
return class_file, user_class
def get_score():
# Don't need to call int()
question_counter = 0
amount_correct = 0
# Make this a tuple sequence; they are immutable
possible_operators = ("+","-","x",)
while True:
if question_counter < 10:
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators)
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
user_answer = int(input("What is the answer to: "
+ str(num1) + operator + str(num2) + "?\n"))
# Take out of the if/else since we always increment
question_counter += 1
if user_answer == answer:
amount_correct += 1
print("Correct!")
else:
print("Incorrect!")
else:
break
return amount_correct, question_counter
class_file, user_class = get_class_file()
name = input("Please enter your name: ")
final_score, num_asked = get_score()
print("Well Done!\n"
"You scored " + str(final_score) + " out of " + str(num_asked) + ".")
# In all methods you called 'a' mode so set that here
# Using 'with open()' automatically closes the file after completion
with open(class_file, 'a') as f:
f.write(user_class + "\n")
f.write(name + "\n")
f.write(str(final_score) + "\n")
Let me know if anything comes up, errors and such. Again, wasn't able to test.