Home > Net >  I have a question about functions in a simple code
I have a question about functions in a simple code

Time:10-03

def computepay(h, r):
    if h > 40:
        pay = 40 * r   (h - 40) * r * 1.5
        return pay
    else:
        pay = h * r
        return pay


hrs = input("Enter Hours:")
h = float(hrs)
rph = input("Enter Rate:")
r = float(rph)

computepay(h ,r) 

so I wrote this function but it doesn't execute; if I change the last line to

p = computepay(h ,r)
print("pay:", p)

OR if I change the function definition to

def computepay(h, r):
    if h > 40:
        pay = 40 * r   (h - 40) * r * 1.5
        print(pay)
    else:
        pay = h * r
        print(pay)


hrs = input("Enter Hours:")
h = float(hrs)
rph = input("Enter Rate:")
r = float(rph)

computepay(h ,r)

then the fuction works properly. Can anyone tell me why it happens? I thought in order to execute a function, just to put the function there and then it executes. Also, what's the difference btw print and return? Thank you!

CodePudding user response:

I am new to programming. I hope I can be a little helpful with this. I ran both the functions in pycharm with the latest version of both pycharm and python.

So I think you are saying that the first portion of the code you have here does not display the pay at the end after you run it without changing the last two lines.

If this is what you are wondering about, it does indeed execute the code but the issue is you never told it to show you what 'pay' is. Since python is a very literal programming language it actually store the value of 'pay' but doesnt show you what it is because you never asked it to. Sometimes just returning a value might work in some software like Jupyter Notebook but if you want it to work every time you must say print(computepay(h,r)) Otherwise, the computer just does it in the background and keeps the value of 'pay' to its self.

If it still doesnt make sense think of the difference between: x = 'hello world' x versus x = 'hello world' print(x) the return function is basically the first one. It knows that 'hello world' is stored in variable x but you never told it to print while the second one you did.

Man after writing this post I hope I actually interpreted the question you had right.

So the difference between 'print()' and 'return' is 'return' is that when you return something from a function you are storing the output of the 'def computepay' function in a variable that is functionally the same as "computepay(h, r) = 'pay'".

Cheers and good luck with your coding.

CodePudding user response:

I would recommend this video if you need more help:

https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=16604s&ab_channel=ProgrammingwithMosh

  • Related