Here are the instructions I received for my assignment:
4) Add the following function into Mylib
scalc(p1)
p1 will be a string like this "N1, N2, operator"
examples
scalc("20,30,*")
the result will be 600
scalc("50,20,+")
the result will be 70
scalc("50,20,-")
the result will be 30
scalc("60,20,/")
the result will be 30
use string functions to parse the first number, the second number, and the operator from the input string.
use the prior functions (add, subtract, divide and multiply ) to do the calculations.
And here is my attempt that is not working. I have the add() sub() mult() div() functions, I'm just not showing them here.
I know it's something very simple that likely has to do with where I call the function scalc(p1). What is the proper way to do that?
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[3] == "+":
add()
elif astring[3] == "-":
sub()
elif astring[3] == "*":
mult()
elif astring[3] == "/":
div()
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
EDIT: Here is the Answer. I did not have arguments being passed to my functions. By adding num1 and num2 to every instance of my arithmetic functions, they were able to receive the new variable values.
#Define the main program function
def main():
#Define input function
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
print("You must enter a number!")
else:
break
#Declare variables
rangeLower = float_input("Enter your Lower range: ")
rangeHigher = float_input("Enter your Higher range: ")
num1 = float_input("Enter your First number: ")
num2 = float_input("Enter your Second number: ")
#Define formula functions
def add(num1, num2):
sum = num1 + num2
print("The Result of",num1,"+",num2,"=", sum)
def sub(num1, num2):
diff = num1 - num2
print("The Result of",num1,"-",num2,"=", diff)
def mult(num1, num2):
product = num1 * num2
print("The Result of",num1,"*",num2,"=", product)
def div(num1, num2):
if num2 == 0:
print("The Result of",num1,"/",num2,"= You cannot divide by Zero")
else:
quotient = num1 / num2
print("The Result of",num1,"/",num2,"=", quotient)
#If-else
if num1 < rangeLower or num1 > rangeHigher or num2 < rangeLower or num2 > rangeHigher:
print("The input values are outside the input ranges.")
print("Please check the number and try again.")
print("Thanks for using our calculator")
else:
#Call functions
add(num1, num2)
sub(num1, num2)
mult(num1, num2)
div(num1, num2)
print("Thanks for using this calculator!")
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1, num2)
elif astring[2] == "-":
sub(num1, num2)
elif astring[2] == "*":
mult(num1, num2)
elif astring[2] == "/":
div(num1, num2)
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
This does it. There were a couple errors. First, in Python you start counting at 0, so you wanted to use astring[2] instead of astring[3]. Also you needed a value to be returned:
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] == "-":
sub(num1,num2)
elif astring[2] == "*":
mult(num1,num2)
elif astring[2] == "/":
div(num1,num2)
return value
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
Example:
input: "20,30,+"
Out[2]: 50.0
Related
I am new to Python. I tried to make a simple calculator, but what is the problem?
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main()
You call main from inside itself. Set this outside the function like this:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main() # Added main outside the function
Your main() has a Tab behind (before) it.
It didn't run for me at first.
The other things seem fine to me.
You could also have it in a loop if you want to make it nicer.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
if __name__ == '__main__':
while(True):
main()
if input('If you are done with calculating, type q: ') == 'q':
break
newbie to python and I was creating a basic calculator with functions and variables and such, was wondering if there was a way for python to skip the two lines that you enter num1 and num2 in. Currently if you make the opr == cube/square it doesn't ask for a number to cube/square it just goes straight to the lines asking for num1 and num2.
opr = input("Would you like to multiply (*), Divide (/), Subtract (-), Add (+), Cube (cube) or Square (square):")
if opr == "cube":
cube1 = int(input("Enter Number To Cube"))
elif opr == "square":
square1 = int(input("Enter Number To Square"))
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
def cube(num):
return num * num * num
def square(num):
return num * num
if opr == "*":
result = float(num1) * float(num2)
if opr == "/":
result = float(num1) / float(num2)
if opr == "-":
result = float(num1) - float(num2)
if opr == "+":
result = float(num1) + float(num2)
if opr == "cube":
result = cube(cube1)
if opr == "square":
result = square(square1)
print(result)
Any help is greatly appreciated!
You can simply add them in a condition :
elif opr == "*" or opr == "-" or opr == "+" or opr == "/":
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
This question already has answers here:
Formatting floats without trailing zeros
(21 answers)
Closed 4 years ago.
A beginner python programming learner here.
I'm making a very simple two number calculator in python. Although it runs perfectly, I can't fix the issue with floating numbers ending with ".0". I want to remove this ending. I tried a few things but they didn't work. What condition do I need to add inside the code? Could you please take a look at it below:
def calculator():
num1 = float(input('First number: '))
operator = input('+, -, / or * ? ')
num2 = float(input('Second Number: '))
if operator == '+':
return print(num1, '+', num2, '=', num1 + num2)
elif operator == '-':
return print(num1, '-', num2, '=', num1 - num2)
elif operator == '/':
return print(num1, '/', num2, '=', num1 / num2)
elif operator == '*':
return print(num1, '*', num2, '=', num1 * num2)
calculator()
Thank you in advance!
I exactly did what #water-winter suggested but whenever I execute the program and enter numbers and operator I get this error: if result.is_integer():
AttributeError: 'int' object has no attribute 'is_integer'
Update: Looks like that only "/" operator works perfectly. The other 3 operators give the same error above. :/
New Update: Finally I managed to make the calculator programming flawlessly!
def calculator():
num1 = float(input("First number: "))
operator = input("Choose: +, -, /, or *")
num2 = float(input("Second number: "))
num1 = int(num1) if num1.is_integer() else num1
num2 = int(num2) if num2.is_integer() else num2
add = (num1 + num2)
subtract = (num1 - num2)
divide = (num1 / num2)
multiply = (num1 * num2)
if operator == "+" and add % 1 == 0:
print(num1, "+", num2, "is equal to:", int(add))
elif operator == "+" and not add % 1 == 0:
print(num1, "+", num2, "is equal to:", add)
elif operator == "-" and subtract % 1 == 0:
print(num1, "-", num2, "is equal to:", int(subtract))
elif operator == "-" and not subtract % 1 == 0:
print(num1, "-", num2, "is equal to:", subtract)
elif operator == "/" and divide % 1 == 0:
print(num1, "/", num2, "is equal to:", int(divide))
elif operator == "/" and not divide % 1 == 0:
print(num1, "/", num2, "is equal to:", divide)
elif operator == "*" and multiply % 1 == 0:
print(num1, "*", num2, "is equal to:", int(multiply))
elif operator == "*" and not multiply % 1 == 0:
print(num1, "*", num2, "is equal to:", multiply)
calculator()
Thank you guys, for the help and suggestions. They helped a lot! :)
First, there's a built-in function for float to check for integer and there's int() to trip off decimal places.
>> float(0.5).is_integer()
>> False
>> float(3.0).is_integer()
>> True
>> int(float(5.5))
>> 5
>> int(float(3))
>> 3
Second, if you simply want to print, the return keyword is unnecessary.
def calculator():
num1 = float(input('First number: '))
operator = input('+, -, / or * ? ')
num2 = float(input('Second Number: '))
num1 = int(num1) if num1.is_integer() else num1
# This line is equivalent to:
# if num1.is_integer():
# num1 = int(num1)
# else:
# num1 = num1
num2 = int(num2) if num2.is_integer() else num2
if operator == '+':
result = num1 + num2
result = int(result) if result.is_integer() else result
print(num1, '+', num2, '=', result)
elif operator == '-':
...
calculator()
I just want to start off by saying I know this code is wrong, I'm just testing
this is meant to be a calculator, as you may be able to see from the code I am trying to make the number they end with e.g.
10 + 10 = 20, they will keep the number 20 and can carry on with 20, I want to keep repeating that option
Code:
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main():
operation = input("Do you want to(+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
num2 = float(input("Choose another number: "))
if(operation == "+"):
answer = (add(num1, num2))
print(answer)
elif(operation == "-"):
answer = (sub(num1, num2))
print(answer)
elif(operation == "*"):
answer = (mul(num1, num2))
print(answer)
elif(operation == "/"):
answer = (div(num1, num2))
print(answer)
else:
print("Syntax error!")
def multiple(multiple):
multiple = input("would you like to carry the number(Y or N): ")
if(multiple == "Y" or multiple == "y"):
carry = input("(+,-,*,/): ")
num3 = int(input("choose a number: "))
if(carry == "+"):
print(answer + num3)
elif(carry == "-"):
print(answer - num3)
elif(carry == "*"):
print(answer * num3)
elif(carry == "/"):
print(answer / num3)
else:
print("Syntax Error!")
multiple = True
while multiple == True:
multiple()
choice = input("would you like multiple calculations? (Y or N): ")
while(choice == "y" or choice == "Y"):
main()
multiple()
multiple()
main()
error message:
line 56, in <module>
multiple()
NameError: name 'multiple' is not defined
p.s There may be some indentation errors in this as it pasted strange
You're trying to call the function multiple outside of the scope of the main function while it is only defined in it. Assuming that your indentation is as presented here, you need to move the definition of multiple outside of main so that it can be called.
Additionally, you're defining a variable named multiple which might create some problems. You should change it to something else.
I optimized your code a little and fixed it. It works fine so take a look at it.
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main(carry):
operation = input("Do you want to (+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
if carry == None:
num2 = float(input("Choose another number: "))
else:
num2 = carry
if(operation == "+"):
answer = add(num1, num2)
elif(operation == "-"):
answer = sub(num1, num2)
elif(operation == "*"):
answer = mul(num1, num2)
elif(operation == "/"):
answer = div(num1, num2)
print(answer)
return answer
if input("would you like multiple calculations? (Y or N): ") in ("y", "Y"):
domultiple = True
else:
domultiple = False
carry = None
while 1:
carry = main(carry)
if domultiple:
if input("would you like to carry the number (Y or N): ") in ("n", "N"):
break
else:
break
I am trying to build a simple calculator. I just want the user to enter two numbers and an operation, then for the calculation to be shown, then to loop back to entering two numbers again. If the user enters an operation that is not recognized I want to loop back to 'enter operation'.
Why is this not working:
def add (a,b):
return a + b
def minus (a,b):
return a - b
def multi (a,b):
return a * b
def div (a,b):
return a / b
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
def opPic():
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic ()
print ("Hello User")
numPic()
opPic()
You have a few bugs. First, num1 and num2 are local to numPic--not
global. So you need to return them to the caller, and the caller has to pass
them to opPic():
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic (num1, num2)
num1, num2 = numPic()
opPic (num1, num2)
To make it loop-based, you could do something like:
def opPic(num1, num2):
while True:
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
continue
break
Hopefully, you can figure out the other bit on your own, as this looks like a school assignment.
The num1 and num2 you define in numPic are local to that function. You need to return them and pass them to the opPic function for them to be used.
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
#the same code as before
#except changing opPic() to opPic(num1, num2)
print ("Hello User")
num1, num2 = numPic()
opPic(num1, num2)
There are better ways of doing what you seem to be aiming for though. You haven't actually used a loop and have used recursion instead.