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
Related
first project beginner here! I just finished my first project, a somewhat working calculator i know it is not that great but as i said beginner. I would like to limit the options for number = input meaning if you write anything else than add,substract,divide or multiply you receive an error like " please try again" and afterwards the programm is restarted
Help very much appreciated Thank you.
list = ("add", "substract", "divide" , "multiply" )
number = input("do you want to add substract divide or multiply? ")
if number in list:
print("ok")
else:
print("try again")
number_one = float(input("enter your first number "))
number_two = float(input("enter your second number "))
if number == "add":
solution_one = number_one + number_two
print(solution_one)
if number == "substract":
solution_two = number_one - number_two
print(solution_two)
if number == "divide":
solution_three = number_one / number_two
print(solution_three)
if number == "multiply":
solution_four = number_one * number_two
print(solution_four)
i could only find solutions regarding while loops but i did not know how to use them in this case as these weren't strings but integers.
The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.
while True:
number = input("do you want to add substract divide or multiply? ")
if number in ("add", "substract", "divide" , "multiply" ):
print("ok")
break
print("try again")
Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!
You could consider using the operator module.
Build a dictionary that maps the user's selected operation with the relevant function.
import operator
OMAP = {
'add': operator.add,
'subtract': operator.sub,
'divide': operator.truediv,
'multiply': operator.mul
}
while (op := input('Do you want to add, subtract, multiply, divide or end? ')) != 'end':
try:
if (func := OMAP.get(op)):
x = float(input('Enter your first number: '))
y = float(input('Enter your second number: '))
print(func(x, y))
else:
raise ValueError(f'"{op}" is not a valid choice')
except ValueError as e:
print(e)
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")
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.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm making a calculator on python for a school assignment but the trouble is, my teacher knows nothing. I've made the calculator, but I need to add some code so the user cannot input a number larger than 999, and if they do it creates a loop where the software asks what the users inputs are. Any help?
# Program make a simple calculator
# that can add, subtract, multiply
# and divide using functions
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
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")
I've tried a variety of things but nothing works
P.S. I'm a bit of a novice so go easy
Thanks
while True:
num = int(raw_input('enter an integer <= 999: '))
if num <= 999:
break
print('invalid input, please try again!')
print('you entered: {}'.format(num))
MAX_VALUE = 999
def read_number(message):
n = MAX_VALUE
while (n >= MAX_VALUE):
n = int(raw_input(message))
return n
num1 = read_number("Enter first number:")
num2 = read_number("Enter second number:")
Example run:
Enter first number: 1000
Enter first number: 56
Enter second number: 800
I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction, etc. I am also trying to make Q or q quit the program.
Any ideas for how to allow the user to type operators to represent the operation?
Note: I know I still need to define my remainder operation.
import math
loop = 1
choice = 0
while loop == 1:
print("your options are:")
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
print("% Remainder")
print("Q Quit")
print("***************************")
choice = str(input("Choose your option: "))
if choice == +:
ad1 = float(input("Add this: "))
ad2 = float(input("to this: "))
print(ad1, "+", ad2, "=", ad1 + ad2)
elif choice == -:
su2 = float(input("Subtract this: "))
su1 = float(input("from this: "))
print(su1, "-", su2, "=", su1 - su2)
elif choice == *:
mu1 = float(input("Multiply this: "))
mu2 = float(input("with this: "))
print(mu1, "*", mu2, "=", mu1 * mu2)
elif choice == /:
di1 = float(input("Divide this: "))
di2 = float(input("by this: "))
print(di1, "/", di2, "=", di1 / di2)
elif choice == Q:
loop = 0
print("Thank-you for using calculator")
First off, you don't need to assign choice to zero
Second, you have your code right, but you need to put quotes around the operators in your if statements like this
if choice == '+':
to show that you are checking for a string
make your loop like this:
while 1: #or while True:
#do stuff
elif choice == 'Q': #qoutes around Q
break #use the `break` keyword to end the while loop
then, you don't need to assign loop at the top of your program
You should try replacing if choice == + by if choice == "+".
What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator.