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
SQL counting distinct over partition
Active low-pass filters --- good to what frequencies?
A IP can traceroute to it, but can not ping
Does a scale have more than seven chords?
Can Rydberg constant be in joules?
Why didn't Voldemort recognize that Dumbledore was affected by his curse?
What to do when surprise and a high initiative roll conflict with the narrative?
Fixing obscure 8080 emulator bug?
How is water heavier than petrol, even though its molecular weight is less than petrol?
Why can my keyboard only digest 6 keypresses at a time?
Does Disney no longer produce hand-drawn cartoon films?
I have a problem assistant manager, but I can't fire him
What ways have you found to get edits from non-LaTeX users?
is it possible for a vehicle to be manufactured witout a catalitic converter
How to communicate to my GM that not being allowed to use stealth isn't fun for me?
English word for "product of tinkering"
How come the nude protesters were not arrested?
Winning Strategy for the Magician and his Apprentice
How to handle self harm scars on the arm in work environment?
How to manually rewind film?
Playing a Character as Unobtrusive and Subservient, Yet Not Passive
Teaching a class likely meant to inflate the GPA of student athletes
Does the Long March-11 increase its thrust after clearing the launch tower?
How can this tool find out registered domains from an IP?
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 May 22 at 16:16
Mast
7,80363790
7,80363790
asked May 22 at 14:04
JustinJustin
1,318427
1,318427
add a comment |
add a comment |
3 Answers
3
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 functions_dict:
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')
$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
May 22 at 20:54
$begingroup$
Maybe addprint ("Q. Quit")
afterprint ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
1
$begingroup$
A few things: There should be no space after theprint
function. You can also useelif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
Thank you!elif choice in functions_dict
is really better than my version.
$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
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")
$endgroup$
add a comment |
$begingroup$
I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.
Hopefully this code will show you about regex and such. Findall is quite useful.
import re
while True:
my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
if not my_operation:
print("Goodbye!")
break
numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
if len(numstrings) == 1:
print("I need an operation.")
continue
if len(numstrings) != 2: #2*3*4 bails
print("I can only do a single operation right now.")
continue
for my_num in numstrings:
if not my_num.isdigit(): #e.g. if you try z * 12
print(my_num, "is not a digit.")
continue
numbers = [int(x) for x in numstrings] # convert strings to integers
my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
out_string = my_operation + " = "
if my_operator == '-': out_string += str(numbers[0] - numbers[1])
elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
else: print("unknown")
print(out_string)
Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).
$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
3 Answers
3
active
oldest
votes
3 Answers
3
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 functions_dict:
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')
$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
May 22 at 20:54
$begingroup$
Maybe addprint ("Q. Quit")
afterprint ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
1
$begingroup$
A few things: There should be no space after theprint
function. You can also useelif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
Thank you!elif choice in functions_dict
is really better than my version.
$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
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 functions_dict:
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')
$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
May 22 at 20:54
$begingroup$
Maybe addprint ("Q. Quit")
afterprint ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
1
$begingroup$
A few things: There should be no space after theprint
function. You can also useelif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
Thank you!elif choice in functions_dict
is really better than my version.
$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
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 functions_dict:
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')
$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 functions_dict:
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')
edited May 23 at 13:14
answered May 22 at 14:32
vurmuxvurmux
1,225214
1,225214
$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
May 22 at 20:54
$begingroup$
Maybe addprint ("Q. Quit")
afterprint ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
1
$begingroup$
A few things: There should be no space after theprint
function. You can also useelif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
Thank you!elif choice in functions_dict
is really better than my version.
$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
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
May 22 at 20:54
$begingroup$
Maybe addprint ("Q. Quit")
afterprint ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
1
$begingroup$
A few things: There should be no space after theprint
function. You can also useelif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
Thank you!elif choice in functions_dict
is really better than my version.
$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
$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
May 22 at 20:54
$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
May 22 at 20:54
$begingroup$
Maybe add
print ("Q. Quit")
after print ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
$begingroup$
Maybe add
print ("Q. Quit")
after print ("4. Divide")
$endgroup$
– Stobor
May 23 at 1:55
1
1
$begingroup$
A few things: There should be no space after the
print
function. You can also use elif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
A few things: There should be no space after the
print
function. You can also use elif choice in functions_dict
$endgroup$
– Ben
May 23 at 12:42
$begingroup$
Thank you!
elif choice in functions_dict
is really better than my version.$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
Thank you!
elif choice in functions_dict
is really better than my version.$endgroup$
– vurmux
May 23 at 13:13
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
$begingroup$
No if main guard?
$endgroup$
– D. Ben Knoble
May 23 at 15:38
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")
$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")
$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")
$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")
answered May 22 at 14:33
Clay RecordsClay Records
1613
1613
add a comment |
add a comment |
$begingroup$
I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.
Hopefully this code will show you about regex and such. Findall is quite useful.
import re
while True:
my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
if not my_operation:
print("Goodbye!")
break
numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
if len(numstrings) == 1:
print("I need an operation.")
continue
if len(numstrings) != 2: #2*3*4 bails
print("I can only do a single operation right now.")
continue
for my_num in numstrings:
if not my_num.isdigit(): #e.g. if you try z * 12
print(my_num, "is not a digit.")
continue
numbers = [int(x) for x in numstrings] # convert strings to integers
my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
out_string = my_operation + " = "
if my_operator == '-': out_string += str(numbers[0] - numbers[1])
elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
else: print("unknown")
print(out_string)
Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).
$endgroup$
add a comment |
$begingroup$
I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.
Hopefully this code will show you about regex and such. Findall is quite useful.
import re
while True:
my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
if not my_operation:
print("Goodbye!")
break
numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
if len(numstrings) == 1:
print("I need an operation.")
continue
if len(numstrings) != 2: #2*3*4 bails
print("I can only do a single operation right now.")
continue
for my_num in numstrings:
if not my_num.isdigit(): #e.g. if you try z * 12
print(my_num, "is not a digit.")
continue
numbers = [int(x) for x in numstrings] # convert strings to integers
my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
out_string = my_operation + " = "
if my_operator == '-': out_string += str(numbers[0] - numbers[1])
elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
else: print("unknown")
print(out_string)
Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).
$endgroup$
add a comment |
$begingroup$
I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.
Hopefully this code will show you about regex and such. Findall is quite useful.
import re
while True:
my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
if not my_operation:
print("Goodbye!")
break
numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
if len(numstrings) == 1:
print("I need an operation.")
continue
if len(numstrings) != 2: #2*3*4 bails
print("I can only do a single operation right now.")
continue
for my_num in numstrings:
if not my_num.isdigit(): #e.g. if you try z * 12
print(my_num, "is not a digit.")
continue
numbers = [int(x) for x in numstrings] # convert strings to integers
my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
out_string = my_operation + " = "
if my_operator == '-': out_string += str(numbers[0] - numbers[1])
elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
else: print("unknown")
print(out_string)
Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).
$endgroup$
I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more.
Hopefully this code will show you about regex and such. Findall is quite useful.
import re
while True:
my_operation = input("Enter a simple arithmetic operation (-+*/), no parentheses:")
if not my_operation:
print("Goodbye!")
break
numstrings = re.split("[*+/-]", my_operation) #x*y, for instance
if len(numstrings) == 1:
print("I need an operation.")
continue
if len(numstrings) != 2: #2*3*4 bails
print("I can only do a single operation right now.")
continue
for my_num in numstrings:
if not my_num.isdigit(): #e.g. if you try z * 12
print(my_num, "is not a digit.")
continue
numbers = [int(x) for x in numstrings] # convert strings to integers
my_operator = re.findall("[*+/-]", my_operation)[0] #this finds the first incidence of the operators
out_string = my_operation + " = "
if my_operator == '-': out_string += str(numbers[0] - numbers[1])
elif my_operator == '+': out_string += str(numbers[0] + numbers[1])
elif my_operator == '*': out_string += str(numbers[0] * numbers[1])
elif my_operator == '/': out_string += str(numbers[0] / numbers[1])
else: print("unknown")
print(out_string)
Possible improvements would be to create a string r'[-+/*]' so it would be easy to add, say, 3^3 or 5%3 or even 5&3 (bitwise and) or 5|3(bitwise or).
answered May 23 at 13:14
aschultzaschultz
1731211
1731211
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