Python program for a simple calculatorFinding the lowest terms for fractions in C#TDD: String Calculator KataN-Bonnaci sequence calculatorTiny calculator using dependency injection and inversion of controlA simple pocket calculatorPseudo Random Number GeneratorJavaScript OOP calculatorComputing the total property management fee for propertiesMultiplying/Dividing before Adding/SubtractingA Java Calculator that could perform basic Mathematical Operations
Is my plasma cannon concept viable?
How to patch glass cuts in a bicycle tire?
Count all vowels in string
Freedom of Speech and Assembly in China
Heat lost in ideal capacitor charging
How does the Earth's center produce heat?
Why does Bran want to find Drogon?
Manager questioning my time estimates for a project
Why did Theresa May offer a vote on a second Brexit referendum?
Is there a single word meaning "the thing that attracts me"?
How to melt snow without fire or body heat?
Are black holes spherical during merger?
Did this character show any indication of wanting to rule before S8E6?
Find this cartoon
Gravitational Force Between Numbers
“Quand même” to mean “anyway”
On San Andreas Speedruns, why do players blow up the Picador in the mission Ryder?
Is it legal to meet with potential future employers in the UK, whilst visiting from the USA
Why did Drogon spare this character?
Why A=2 and B=1 in the call signs for Spirit and Opportunity?
My players want to grind XP but we're using landmark advancement
How was Daenerys able to legitimise this character?
Co-author wants to put their current funding source in the acknowledgements section because they edited the paper
Expected maximum number of unpaired socks
Python program for a simple calculator
Finding the lowest terms for fractions in C#TDD: String Calculator KataN-Bonnaci sequence calculatorTiny calculator using dependency injection and inversion of controlA simple pocket calculatorPseudo Random Number GeneratorJavaScript OOP calculatorComputing the total property management fee for propertiesMultiplying/Dividing before Adding/SubtractingA Java Calculator that could perform basic Mathematical Operations
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.
Here is my code:
# 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")
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")
So, I would like to know whether I could make this code shorter and more efficient.
Also, any alternatives are greatly welcome.
Any help would be highly appreciated.
python performance python-3.x calculator
$endgroup$
add a comment |
$begingroup$
I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.
Here is my code:
# 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")
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")
So, I would like to know whether I could make this code shorter and more efficient.
Also, any alternatives are greatly welcome.
Any help would be highly appreciated.
python performance python-3.x calculator
$endgroup$
add a comment |
$begingroup$
I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.
Here is my code:
# 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")
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")
So, I would like to know whether I could make this code shorter and more efficient.
Also, any alternatives are greatly welcome.
Any help would be highly appreciated.
python performance python-3.x calculator
$endgroup$
I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.
Here is my code:
# 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")
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")
So, I would like to know whether I could make this code shorter and more efficient.
Also, any alternatives are greatly welcome.
Any help would be highly appreciated.
python performance python-3.x calculator
python performance python-3.x calculator
edited 4 hours ago
Mast
7,74463788
7,74463788
asked 7 hours ago
JustinJustin
371116
371116
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.
You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).
Here is the improved code:
# 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")
functions_dict =
'1': [add, '+'],
'2': [subtract, '-'],
'3': [multiply, '*'],
'4': [divide, '/']
while True:
choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
if choice == 'q':
break
elif choice in ['1', '2', '3', '4']:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(' = '.format(
num1,
functions_dict[choice][1],
num2,
functions_dict[choice][0](num1, num2)
))
else:
print('Invalid number')
New contributor
$endgroup$
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
add a comment |
$begingroup$
One issue I see is with casting the user's input to int
:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.
I suggest either surrounding the input with a try/except block to catch that possibility:
try:
num1 = int(input("Enter first number: "))
except ValueError:
print("RuhRoh")
Or using str.isdigit()
:
num1 = input("Enter first number: ")
if not num1.isdigit():
print("RuhRoh")
New contributor
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220732%2fpython-program-for-a-simple-calculator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.
You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).
Here is the improved code:
# 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")
functions_dict =
'1': [add, '+'],
'2': [subtract, '-'],
'3': [multiply, '*'],
'4': [divide, '/']
while True:
choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
if choice == 'q':
break
elif choice in ['1', '2', '3', '4']:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(' = '.format(
num1,
functions_dict[choice][1],
num2,
functions_dict[choice][0](num1, num2)
))
else:
print('Invalid number')
New contributor
$endgroup$
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
add a comment |
$begingroup$
You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.
You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).
Here is the improved code:
# 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")
functions_dict =
'1': [add, '+'],
'2': [subtract, '-'],
'3': [multiply, '*'],
'4': [divide, '/']
while True:
choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
if choice == 'q':
break
elif choice in ['1', '2', '3', '4']:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(' = '.format(
num1,
functions_dict[choice][1],
num2,
functions_dict[choice][0](num1, num2)
))
else:
print('Invalid number')
New contributor
$endgroup$
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
add a comment |
$begingroup$
You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.
You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).
Here is the improved code:
# 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")
functions_dict =
'1': [add, '+'],
'2': [subtract, '-'],
'3': [multiply, '*'],
'4': [divide, '/']
while True:
choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
if choice == 'q':
break
elif choice in ['1', '2', '3', '4']:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(' = '.format(
num1,
functions_dict[choice][1],
num2,
functions_dict[choice][0](num1, num2)
))
else:
print('Invalid number')
New contributor
$endgroup$
You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict.
You run your program, it calculates something once and quits. Why not letting the user have many calculations? You can run the neverending loop with some break statement (old console programs, like in DOS, usually quitted on Q).
Here is the improved code:
# 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")
functions_dict =
'1': [add, '+'],
'2': [subtract, '-'],
'3': [multiply, '*'],
'4': [divide, '/']
while True:
choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")
if choice == 'q':
break
elif choice in ['1', '2', '3', '4']:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(' = '.format(
num1,
functions_dict[choice][1],
num2,
functions_dict[choice][0](num1, num2)
))
else:
print('Invalid number')
New contributor
New contributor
answered 6 hours ago
vurmuxvurmux
2709
2709
New contributor
New contributor
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
add a comment |
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
$begingroup$
I was about to post my answer and saw this. Upvote for bringing out a case for dictionaries. Might I add, it may be good to add a bit on input validation.
$endgroup$
– perennial_noob
20 mins ago
add a comment |
$begingroup$
One issue I see is with casting the user's input to int
:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.
I suggest either surrounding the input with a try/except block to catch that possibility:
try:
num1 = int(input("Enter first number: "))
except ValueError:
print("RuhRoh")
Or using str.isdigit()
:
num1 = input("Enter first number: ")
if not num1.isdigit():
print("RuhRoh")
New contributor
$endgroup$
add a comment |
$begingroup$
One issue I see is with casting the user's input to int
:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.
I suggest either surrounding the input with a try/except block to catch that possibility:
try:
num1 = int(input("Enter first number: "))
except ValueError:
print("RuhRoh")
Or using str.isdigit()
:
num1 = input("Enter first number: ")
if not num1.isdigit():
print("RuhRoh")
New contributor
$endgroup$
add a comment |
$begingroup$
One issue I see is with casting the user's input to int
:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.
I suggest either surrounding the input with a try/except block to catch that possibility:
try:
num1 = int(input("Enter first number: "))
except ValueError:
print("RuhRoh")
Or using str.isdigit()
:
num1 = input("Enter first number: ")
if not num1.isdigit():
print("RuhRoh")
New contributor
$endgroup$
One issue I see is with casting the user's input to int
:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly.
I suggest either surrounding the input with a try/except block to catch that possibility:
try:
num1 = int(input("Enter first number: "))
except ValueError:
print("RuhRoh")
Or using str.isdigit()
:
num1 = input("Enter first number: ")
if not num1.isdigit():
print("RuhRoh")
New contributor
New contributor
answered 6 hours ago
Clay RecordsClay Records
1313
1313
New contributor
New contributor
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220732%2fpython-program-for-a-simple-calculator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown