简体   繁体   中英

Python 3 how to properly return a value in function for later use

I'm a python newbie. I created a calculator program that will accept 2 number and a type of operation from user. I already have a working code for this but I want to further simplify the code by exploring and using function. Here's the portion of the code:

def addition(num1,num2):
    sum = num1 + num2
    print('The sum is ', sum)
def subtraction(num1,num2):
    sub = num1 - num2
    print('The difference is ', sub)
def inputNumber():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return num1,num2
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = input('Select operation > ').lower()
    if operation == 'q':
        break
    elif operation == '1':
        addition(inputNumber())
    elif operation == '2':
        subtraction(inputNumber())
    else:
        print('Not valid. Try again.')
except:
    print('Invalid!')

My problem is after entering 2 numbers it doesn't perform the operation. I think the problem is the 2 input values didn't return properly.

Thanks

This should help. inputNumber function is returning a single tuple of both your float.

def addition(num):    #--->Update
    sum = num[0] + num[1]     #--->using index to get first and second number.
    print('The sum is ', sum)
def subtraction(num):    #--->Update
    sub = num[0] - num[1]      #--->using index to get first and second number.

    print('The difference is ', sub)
def inputNumber():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return num1,num2                 #-----> Returns a tuple. EX: (3.0, 4.0)
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = input('Select operation > ').lower()
        if operation == 'q':
            break
        elif operation == '1':
            addition(inputNumber())
        elif operation == '2':
            subtraction(inputNumber())
        else:
            print('Not valid. Try again.')
    except Exception, e:
        print('Invalid!', e)
def addition((num1,num2)):
    sum = num1 + num2
    print('The sum is ', sum)
def subtraction((num1,num2)):
    sub = num1 - num2
    print('The difference is ', sub)
def inputNumber():
    num1 = float(raw_input('Enter the first number: '))
    num2 = float(raw_input('Enter the second number: '))
    return num1,num2
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = raw_input('Select operation > ').lower()
        if operation == 'q':
            break
        elif operation == '1':
            import pdb;pdb.set_trace()
            addition(inputNumber())
        elif operation == '2':
            subtraction(inputNumber())
        else:
            print('Not valid. Try again.')
    except:
        print('Invalid!')
  1. Use raw_input to take inputs from user containing string as well as int (applicable for python 2 only)
  2. Check Try except indentation.

  3. return keyword returns in a tuple, so modify addition and subtraction.

The problem is that your functions expect two inputs, but get a tuple (that is what a function return when you use return foo, bar )

you can expand the tuple using an astrix like this (also fixed indentation issue):

def addition(num1,num2):
    sum = num1 + num2
    print('The sum is ', sum)
def subtraction(num1,num2):
    sub = num1 - num2
    print('The difference is ', sub)
def inputNumber():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return num1,num2
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = input('Select operation > ').lower()
        if operation == 'q':
            break
        elif operation == '1':
            addition(*inputNumber())
        elif operation == '2':
            subtraction(*inputNumber())
        else:
            print('Not valid. Try again.')
    except:
        print('Invalid!')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM