shortening a calculator in python - python

I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
I am not able to do two operations at once either.

Use functions from the operator module or simple functions you define yourself to the calculation work, then map the operation name from the queencommand string to those functions:
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
operator.add could be replaced by lambda a, b: a + b, etc. if you don't want to use a module for those operations.

Here is a fully fledged calculator. See if it helps:
def multiplication():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 * num2
print(ans)
def addition():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 + num2
print(ans)
def subtraction():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 - num2
print(ans)
def division():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 / num2
print(ans)
def Help():
print("""Welcome to Calculator P1!!!
Type "x" for multiplication.
Type "+" for addition.
Type "-" for subtraction.
Type "/" for division.""")
while True:
print("Type 'help' for introduction or instructions")
choice = input("Operator: ")
if choice == "x" or choice == "muliplication":
multiplication()
elif choice == "+" or choice == "addition":
addition()
elif choice == "-" or choice == "subtraction":
subtraction()
elif choice == "/" or choice == "division":
division()
elif choice == "help":
Help()
answer = input('Run again? (y/n): ')
if answer == 'n':
break
elif answer == 'y':
continue
else:
print("""Unrecognized Input.
<<<<RESTARTING PROGRAM>>>>""")
continue

Related

I wonder if there's a way to skip a specific line so it just doesn't get executed

I am building a calculator and I want to know if i can make num2 input be skipped when "root" option is chosen.
This is my code:
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
if op not in operators:
print("Invalid operator")
start()
num2 = float(input("Enter a number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "^":
print(pow(num1, num2))
elif op == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
I want this to get ignored:
num2 = float(input("Enter a number: "))
When this is the case:
elif op == "root":
print(math.sqrt(num1))
Put the second number input statement behind an if:
op = input("Enter a operator: ")
if op != "root":
num2 = float(input("Enter a number: "))
To do this, you could do:
if op != "root":
num2 = float(input("Enter a number: "))
This would skip the num2 input if op == "root"
There can be many different ways. One suggestion would be as below.
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
# HERE
if op != "root" and op in operators:
num2 = float(input("Enter a number: "))
elif op not in operators:
print("Invalid operator")
start()
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "^":
print(pow(num1, num2))
elif op == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
or
# HERE
if op in operators:
if op != "root":
num2 = float(input("Enter a number: "))
else:
print("Invalid operator")
start()

stuck with a simple python program "elif"

Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

NameError: name '' is not defined with multiple define functions

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

Simpel Python Calculator - Syntax Error - Indentation errors

I recently started learning Python. I have never coded before, but it seemed like a challenge. The first thing I have made is this calculator. However, I can't seem to get it to work.
while True:
print("Typ 'plus' to add two numbers")
print("Typ 'min' to subtract two numbers")
print("Typ 'multiplication' multiply two numbers")
print("Typ 'division' to divide two numbers")
print("Typ 'end' to abort the program")
user_input = input(": ")
if user_input == "end"
break
elif user_input == "plus":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
elif user_input == "min":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 - num2)
print("The anwser is: " + str(result))
elif user_input == "maal":
num1 = float(input("Give a number:"))
num2 = float(input("Give another number: "))
result = str(num1 * num2)
print("The anwser is: " + str(result))
elif user_input == "deel":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
else:
print ("I don't understand!")
I know it will probably something stupid, I am still very much learning. Just trying to pickup a new skill instead of bothering my friends who do know how to code.
You missed a colon after an this if statement
if user_input == "end"
break
Should Be:
if user_input == "end":
break

Repeating code 3 times, and making sure input is only a number in Python 2.7

I am trying to find out how to make my code repeat its self 3 times at the end of the set of questions and also I'm trying to make sure my validation is correct so that the input to the questions is only a number.
This is my code...
import random
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in range(10):
num1 = float(random.randint(1, 10))
num2 = float(random.randint(1, 10))
Math = random.choice(["+", "-", "*","/"])
print("Please solve:", num1, Math, num2)
user = int(input(""))
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = num1 / num2
if answer!= int:
print ("Please reenter a number")
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, " You Got", correct, "Out Of 10")
Your answer != int should be if not isinstance(answer, int)
Furthermore, you will get ValueError each time user tries to insert characters.
Because of this, you should edit your code to look like this:
from __future__ import division
import random
for i in xrange(3):
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in xrange(3):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
Math = random.choice(["+", "-", "*","/"])
print("Please solve: {} {} {}".format(num1, Math, num2))
while True:
try:
user = int(raw_input(""))
except ValueError:
print ("Please reenter a number")
continue
break
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = round(num1 / num2, 1)
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print("{} You Got {} Out Of 10".format(name, correct))
As you can see there was a lot things that you needed to change.

Categories