Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
beginner math
#11
Sorry guys for all this mess... I guess my teacher is an idiot. I WANT SO MUCH TO LEARN PYTHON but I`m in a stage where even google doesn't help me and my parents won't pay for my extra hours with a teacher, anyway thanks for everything, and sorry for wasting your time. I hope one day I will be able to help others too Smile cheers.
Reply
#12
No, your teacher is not an idiot and YOU clearly refuse to listen and prefer to whine instead. I have provided you with a link that visualise the execution line by line in order to understand it.
given that a=4 and b=2, what will happen when you call hi(a, b+1)? what are the arguments you pass when call hi? what value will hi return with these arguments?
Larz60+ likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#13
I took the "Hour of code" and I now understand your question. To those who didn't follow the link, the OP is about a question in a Python quiz. This explains why the original post was missing colons after the function def. We were looking at code copied from an online test, not running Python code.
def hi(a, b):
    return a * b
 
def hello(a, b):
    return hi(a, b + 1)
 
hello(4, 2)
The test presents some code and you select the answer from multiple choices. I got one wrong when they changed from int addition to string addition. The question above has a correct answer of 12 and the OP is asking why the answer isn't 9. I missed that the first time through. I need to pay better attention.

The OP thinks the answer is 9 because he/she treated function calls like a math equation.
4 * 2 + 1 = 9
9 is the correct answer if you unwind the function calls like they are an equation and use operator precedence.

The correct answer is:
4 * (2 + 1) = 12
12 is the correct answer because Python evaluates arguments before calling the function. When hello(4, 2) calls hi(4, 2+1), the 2+1 is evaluated and replaced with 3.

We can see this if I print out the arguments inside the functions.
def hi(a, b):
    print(f'hi({a}, {b})')
    return a*b

def hello(a, b):
    print(f'hello({a}, {b})')
    return hi(a, b+1)

hello(4, 2)
Output:
hello(4, 2) hi(4, 3)
Inside function hi(a, b), the value for argument b is 3, not 2+1.
MarioM likes this post
Reply
#14
Thank you so much deanhystad , I couldn't find any answer until now, you have made it so clear now , thanks so much.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  *Ultra beginner math question Markg2 2 2,251 Apr-21-2019, 11:24 PM
Last Post: Markg2

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020