Python calculator - How can I make this better - python

im pretty new to programming. I made this calculator in python and I was wondering how can I make it more efficient because it seems a bit inefficient to me. I'm still really unfamiliar with python and some programming concepts so it would be nice to get an idea of different ways I may do this. Perhaps there is a better way for me to set up the functions or maybe a way that they can be put into different classes?
Thanks for any responses
def add():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a + b
if a + b == c:
print c
menu()
return c
def sub():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a - b
if a - b == c:
print c
menu()
return c
def mul():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a * b
if a * b == c:
print c
menu()
return c
def div():
a = float(raw_input("Enter a number!: "))
b = float(raw_input("Enter a number!: "))
c = a / b
if a / b == c:
print c
menu()
return c
def square():
a = int(raw_input("Enter a number!: \n"))
c = a * a
if a * a == c:
print c
menu()
return c
def menu():
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choices = [1, 2, 3, 4, 5, 6]
choice = int(raw_input("Enter a number!: \n"))
while True:
if choice == 1:
print add()
elif choice == 2:
print sub()
elif choice == 3:
print mul()
elif choice == 4:
print div()
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
for choose in choices:
if choice != choices:
print "Please enter a number 1 - 6!"
menu()
menu()

First, in the else case where the user entered an invalid menu number, you don't need these lines:
for choose in choices:
if choice != choices:
After all, you already know choice is not valid.
Second, when the user enters 6, rather than exit() you should just return. The program will still end. It's often considered "rude" for a function to call exit() directly--let the caller decide what to do when the function ends.
Third, you don't need to call menu() when your operators succeed. It's strange that you do, since menu() contains its own infinite loop anyway. It's just redundant.
Finally, you can collapse all the two-argument math functions into one, by passing in the actual operation as an argument. The operator module makes this easier.
Putting all these ideas together, here's the new code:
import operator
def dobinaryop(op):
a = float(raw_input("Enter a number!: \n"))
b = float(raw_input("Enter a number!: \n"))
return op(a, b)
def square():
a = float(raw_input("Enter a number!: \n"))
return a * a
def menu():
while True:
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choice = int(raw_input("Enter a number!: \n"))
if choice == 1:
print dobinaryop(operator.add)
elif choice == 2:
print dobinaryop(operator.sub)
elif choice == 3:
print dobinaryop(operator.mul)
elif choice == 4:
print dobinaryop(operator.div)
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
print "Please enter a number 1 - 6!"
menu()
You could streamline this even further by putting the various operators into a list and indexing by choice, but that's getting slightly arcane for not much benefit given you only have four such operators, plus two special cases and bounds checking.

There are couple of things which you are repeating in all the functions. Like asking user to input two numbers a & b using raw_input multiples times. They can be put into another method say getTwoNumbers() which will take two inputs from user and return the two numbers. This method (i.e getTwoNumbers())need to be invoked in the function(s) which is/are performing binary operation. Also you are storing the result into another variable c, which can be ommited and hence comparison with binary operation with the variable c is also not required. It is better if you can perform return a+b or return a-b etc, based on the current binary operation you want to perform.

Put functions and related index in a dictionary. Use that dictionary to decide which function to execute.
And get duplicated part of every function out. I think these solutions will get your code better.

Related

My function in python returns 0 if i give an input variable to the function

Today i decided to learn some python, tried to do a random choice picker just to train and did it good, but unfortunately i made a function for the choice picker, and made an variable to pick how many choices there is and requests input for it, but something doesnt work out. Let me give you an example of what i mean:
def choices(num):
if num == 3:
randchoicez = [input("What is the first choice? "), input("What is the second choice? "),
input("What is the third choice? ")]
rndchoices = random.choice([1, 2, 3])
if rndchoices == 1:
print(randchoicez[0])
if rndchoices == 2:
print(randchoicez[1])
if rndchoices == 3:
print(randchoicez[2])
elif num == 2:
randchoices = [input("What is the first choice? "), input("What is the second choice? ")]
rndchoice = random.choice([1, 2])
if rndchoice == 1:
print(randchoices[0])
if rndchoice == 2:
print(randchoices[1])
print("Hello and welcome to the random choice program. ")
print("How many choices? (Can be up to 5 and start from 2) ")
nr_choices = input()
choices(nr_choices)
if i call the function 'choices' with a number that you pick its gonna return 0 and do nothing
choices(nr_choices)
but if i call it with a number like 2 like this:
choices(2)
its gonna work.
This is what happens when i run the script with the choices(nr_choices)
You're expecting num to be a number in the function but input() returns a string.
So change your input line to:
nr_choices = int(input())
Which would make nr_choices a number.

basic calculator, multiple input and choice through functions

as you can tell by my code, i want to make a basic calculator, you get asked what you want to do first then asked 2 input 2 numbers to be worked out by the code. I am having a problem where the code returns nothing and doesnt even attempt to use the functions it is meant to.
##Simple Calculator program##
print("Welcome to my basic calculator program")
print("In this program you will be asked to input what function you want to do then")
print("select 2 numbers, where the program will then do the mathematic operation on those 2 numbers")
#Class containing the functions and basic caluclation
class calculator_class():
print("Please select a function by entering these :")
print("Addition")
print("Subtraction")
print("Multiplication")
print("Division")
#this is a function which asks the user to choose what operator to choose before choosing their number
def userchoice():
userchoices = str(input())
if userchoices in ["Addition","Subtraction","Multiplication","Division"]:
return(
if userchoices == "Addition":
print(addition())
elif userchoices == "Subtraction":
print(subtraction())
elif userchoices == "multiplication":
print(multiplication())
elif userchoices == "division":
print(division())
else:
print(invalid_choice())
print(userchoice())
#here the user chooses the 2 numbers
print("Please select 2 numbers to calculate")
usernumber1 = int(input("Please input your first number here : "))
usernumber2 = int(input("Please input your second number here : "))
#Functions of which contain addition, subtraction, multiplication and division
def addition():
print("A D D I T I O N")
print("Just calculating...")
print(usernumber1 + usernumber2)
def subtraction():
print("S U B T R A C T I O N")
print("Just calculating...")
print(usernumber1 - usernumber2)
def multipliction():
print("M U L T I P L I C A T I O N ")
print("Just calculating...")
print(usernumber1 * usernumber2)
def division():
print("D I V I S I O N ")
print("Just calculatin...")
print(usernumber1 / usernumber2)
def invalid_choice():
print("You did not pick a valid option, please try again")
You have many wrong approaches in this code.
More easier to type just a one sign (* for example) instead of typing "multiplication"
It is better to apply .lower() for every user input
input in python is always str, so str() in userchoices = str(input()) is redundant
int() for input() may lead to error (int('1.2') # error), so put such code in try/except block

Errors pertaining to the "!==" function in Python

I'm currently trying to make a program in Python that basically asks you math problems. For some reason, there's a lot of errors, and I have no idea why, such as the "!==" function, which seems to be incorrect. There might also be some other issues as I've only just started Python. Could someone direct me to how to use the !== function correctly and also my other issue: Making my input for "addition, subtraction, or multiplication" into a possible command?
# import random
import time
choice = 0
counterright = 0
counterwrong = 0
def add_question_to_file(a, b):
with open("wrong_answers.txt", 'a') as f:
f.write(f"{a} {operation} {b}\n")
def test(a,operation,b):
user_input = int(input(f"{a} {operation} {b} = "))
if user_input == a + b:
print("You got it right!")
counterright += 1
while user_input != a + b:
if user_input == a + b:
print("You got it right!")
counterwrong += 1
break
else:
add_question_to_file(a, b)
print("Try Again!")
user_input = int(input(f"{a} + {b} = "))
def get_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
with open("calc_log.txt", 'a') as f:
if a<b: #insures a is always greater than b
a, b = b, a
f.write(f"{a} {operation} {b}\n")
def check_operation():
if operation !==t "+" or "-" or "*"
print("Sorry, that's invalid. You have to choose of the three operations!")
t1=time.perf_counter() #
m = input("What mode would you like to use? Review/Normal. Choose Normal if this is your first time!")
operat ion = input("Which operation would you like to use? +,-,or *?")
if m == "review":
with open("wrong_answers.txt", 'r') as f:
for line in f:
a, operation, b = line.split()
test(int(a), int(b))
elif m == "normal":
num_questions = int(input("How many questions would you like to do? "))
for i in range(num_questions):
print(f"You are on question {i + 1}: ")
get_question()
t2=time.perf_counter() #
print("It took you", t2-t1, "seconds for you to solve this problemset") #
print ("You got",counterright,"correct and",counterwrong,"wrong.")
The reason !== isn't working is because this is not an operator in python. Try using !=. It means not equal too.
The does not equal function in python is !=. The double equal sign (==) is only used when you want to check for equality. I hope this helps!

Passing less argument to function then defined in Python

If I have a function with multiple functions, let say, calculating an area or adding three numbers.
The user chose 1 for calculating area and 2 for adding numbers via input
def func_calculate(numberOne, numberTwo, numberThree, userChoise):
if userChoise == "1":
calculate Area
do something
if userChoise == "2":
calculate addition
do something
userChoise is the input from user
If user wants to calculate area there is only two arguments to the function instead of three, if user wants to make an addition.
So, finally to the question...
What is the most appropriate way to handle it?
When I call the function, when the user wants to calculate area, should I just set the numberThree variable to zero or something or is it a more "right" way do do it?
if userChoie == "1":
inputNumberOne = input(...
inputNumberTwo = input(...
inputNumberThree == 0
func_calculate(inputNumberOne, inputNumberTwo, inputNumberThree, userChoise)
If you wan't to perform multiple operations than it is good to have different functions for different operations
choice = input("what user want's to do")
if choice == 1:
add()
elif choice == 2:
multiply()
and than take arguments from user for that operations like
def add():
num1 = input("num1")
num2 = input("num2")
num3 = input("num3")
print(num1 + num2 + num3)
and similarly for other operations
But if you don't wan't to have multiple functions the you can do
def func(choice):
#choice is the integer which user opted
if choice == 1:
num1 = input("num1")
num2 = input("num2")
num3 = input("num3")
print(num1 + num2 + num3)
elif choice == 2:
.........
A good approach to this problem will be to have multiple functions, each with a specific role. You can make two separate functions calculate_area() and add_numbers(). Then, you can simply check the input and call these functions like this:
userChoice = input("Enter choice: ")
if userChoice == "1":
inputNumberOne = input("Enter number 1: ")
inputNumberTwo = input("Enter number 2: ")
calculate_area(inputNumberOne, inputNumberTwo)
elif userChoice == "2":
inputNumberOne = input("Enter number 1: ")
inputNumberTwo = input("Enter number 2: ")
inputNumberThree = input("Enter number 3: ")
add_numbers(inputNumberOne, inputNumberTwo, inputNumberThree)
If you really want to use only one function with a variable number of parameters, you could use *args as argument. For example:
def funct_calculate(*args):
if len(args) == 2:
Calculate Area
else:
Addition
funct_calculate(radius,pi)
funct_calculate(number1,number2,number3)

Python "if" statement not working

I was writing a complex program and I was getting an if statement...
(this isn't the complex code, this is just an example)
print("The 24 game will give you four digits between one and nine")
print("It will then prompt you to enter an ewuation one digit at a time.")
import random
a = random.randint(1,9)
b = random.randint(1,9)
c = random.randint(1,9)
d = random.randint(1,9)
print(a,b,c,d)
f=input("Enter one of the above numbers")
if f==a:
print("ok")
elif f != a:
print("No")
No matter what I type it always outputs "NO".
It would work after converting the user input string to a number:
if int(f) == a:
print("ok")

Categories