Good practice making a calculator!
What if you want more than 2 numbers?
A while loop is useful. Also, you need to deal with the operand.
I did this when I began to learn some python. (Still haven't got very far!)
#! /usr/bin/python3
# a function to get the numbers
def getNums():
numbers = []
while True:
print('Positive numbers don\'t need a + symbol in front.')
print('If you want a negative number, just enter -4 or -15, like that.')
print('Decimal numbers as normal: 1.35, 12.78 etc.\n\n')
num = input('Enter a number, or q to quit/stop entering numbers ... ')
if num == 'q':
break
numbers.append(float(num))
return numbers
# a function to get the operand
def getOperand():
# maybe add some other operands
operands = ['+', '-', '*', '/']
operand = 'X'
while not operand in operands:
print('\n\nPlease choose + - * or / ')
operand = input('Enter what you want to do" + - * / ... ')
return operand
# a function to add the numbers
def add(numbs):
result = 0
for num in numbs:
result = result + num
return result
# you make the other functions
# a function to multiply the numbers
def multiply(numbs):
result = 1
print('len numbers is', len(numbs))
for i in range(len(numbs)):
print('i is', i)
# do something here
#
print('result =', result)
return result
def main():
while True:
message = input('\n\n Enter q to quit using the calculator, anything else to keep calculating ... ')
if message == 'q':
print('再见, see you again!')
break
the_nums = getNums()
operand = getOperand()
if operand == '+':
this_result = add(the_nums)
print('\n\nResult of addition is', this_result)
# you can figure out the other functions for - * and /
if operand == '-':
this_result = subtract(the_nums)
print('\n\nResult of subtraction is', this_result)
if operand == '*':
this_result = multiply(the_nums)
print('\n\nResult of multiplication is', this_result)
if operand == '/':
this_result = multiply(the_nums)
print('\n\nResult of division is', this_result)
if __name__ == "__main__":
main()
Actually, you only need 2 functions, 1 for addition and 1 for subtraction. Those are really the only 2 operations in arithmetic.
Internally, how computers handle numbers is quite complicated. Somewhere, I have a series of videos "Advanced Python Everything is Bits and Bytes"
Too complicated for me! Have fun!