简体   繁体   中英

Regarding passing variables to an argument

I am working in python 2.7.8.

I'm currently learning about parameters and methods. What I'm trying to accomplish is have a user enter two different variables then pass them to an argument within different methods, sum() and difference().

My following code is something like this:

def computeSum(x, t):
    x = int(raw_input('Please enter an integer: '))
    t = int(raw_input('Please enter a second integer: '))
    x+t
return Sum

def computeDif(y, j):
    y = int(raw_input('Please enter an integer: '))
    j = int(raw_input('Please enter a second integer: '))
    y+j
return Dif

def main():
    raw_input('Would you like to find the sum of two numbers or the difference of two numbers?: ')
    answer = 'sum'
while True:
    computeSum()
else:
    computeDif()

For some reason my compiler (pyScriptor) isn't running and I cannot see any output nor error messages, its just blank. Can anyone possibly help me with any syntax/logic errors?

There are a few problems with your code

  • Your indentation is way off

  • computeSum and computeDif expect the two numbers as parameters, but then also ask for them from the terminal

  • You return the variables Sum and Dif , but never assign values to them

  • You call either computeSum or computeDif , but never do anything with the returned value

  • You never call main . Do you know that you don't need a main function? You can just put the code in line after the function definitions

This is probably a little closer to what you had in mind

def computeSum(x, t):
    return x + t

def computeDif(y, j):
    return y - j

def main():
    while True:
        answer = raw_input('Would you like to find the "sum" of two numbers or the "dif"ference of two numbers? ')
        a = int(raw_input('Please enter an integer: '))
        b = int(raw_input('Please enter a second integer: '))

        if answer == 'sum':
            print(computeSum(a, b))
        elif answer == 'dif':
            print(computeDif(a, b))
        else:
            print('Please enter "sum" or "dif"')

main()

The problem is that you don't need a main() function. Just put the code, unindented, by itself, and it will run when you run the program.

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