sum
you use sum as a variable name, shadowing the builtin, which is generally a bad idea
function
Divide the program into functions with their own goal. Here you have following part
- get the 2 numbers
- get the operation
- do the calculation
- present the result
Get the numbers
you ask for an input, which you get returned as a str. You convert this to a number with int. If the input is not an integer value, this will crash the program, so you'll need some sort of input validation.
For the input validation, I will borrow a bit from this answer to another question
def ask_number(message='please enter a number', number_types=None):
if number_types is None:
number_types = (int, float, complex)
while True:
number = input(message)
for converter in number_types:
try:
return converter(number)
except ValueError:
pass
else:
print('Please enter a valid number')
In this way, you can specify which types are valid, and in which order they should be tried. You can even use custom types if you want.
This will keep asking until you have a valid number, and can be stopped with ctrl+c, which will raise a KeyboardInteruptError
Get the operation
To make it easy for ourselves, we define the default options for operators
DEFAULT_OPERATIONS = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'//': operator.floordiv,
'/': operator.truediv,
'**': operator.pow,
'^': operator.pow,
}
This way we can call the function without arguments most of the times
def ask_operator(operators=None):
if operators is None:
operators = DEFAULT_OPERATIONS
message = f'Please select an operator from [{','.join(map(str, operators)))}]'
while True:
operator = input(message)
if operator in operators:
return operator
else:
print('Please enter a valid operator')
putting it together
def main():
operators = DEFAULT_OPERATIONS
number1 = ask_number('Please enter the first number:')
number2 = ask_number('Please enter the second number:')
operator_str = ask_operator(operators)
operator = operators[operator_str]
result = operator(number1, number2)
print(f'{number1} {operator_str} {number2} = {result}')
which you can put behing a if __name__ == '__main__'-guard
if __name__ == '__main__':
main()
sumas a variable name since it shadows a builtin. \$\endgroup\$//), I don't have a non-if/else solution for that. At least without resorting toeval, which should be avoided. \$\endgroup\$sum =number1//number2, sure this totally represent a sum. \$\endgroup\$