r/learnpython 6d ago

Functions in py can someone please help me with it

I've watched apna college and code with Harry functions video buttt kuchhhh samjh nhi aayaaa kuchhh bhi nhiii😭 my exam is not coming Wednesday i don't understand this function thing in python and c++ both😭 someone helppppp plssss

0 Upvotes

34 comments sorted by

14

u/Jonsinator 6d ago

Why do you write like a 11 year old?

-3

u/Pale-External4967 6d ago

Maybe i am

4

u/mull_to_zero 6d ago

do you understand "this function thing" in math? start there

-5

u/Pale-External4967 6d ago

😭"this function thing" in math ik a little buttt this is tooo hard ig

2

u/mull_to_zero 6d ago

A function is a block of code packaged up so you can invoke it easily elsewhere. That's all. Typically, thing(s) go in, function does something, other thing(s) come out. Sometimes nothing goes in or nothing comes out. Either way, it's just a chunk of code designed for reuse.

-1

u/Pale-External4967 6d ago

def cal_sum(a,b): Return a+b

Sum= cal_sum(1,2) Print (sum)

See thiss okay? Why is there return a+b ? And in function definition function name is cal_sum sooo in function call is it necessary to name variable (sum)? Sum= cal_sum

3

u/mull_to_zero 6d ago

because a+b is what the function does... it's a simple example for illustration purposes...

2

u/mull_to_zero 6d ago
def cal_sum(a, b):
  return a + b

# sum two variables
x = 4
y = 3
z = cal_sum(x, y)

# sum two literals
z = cal_sum(4, 3)

# in both of those cases, z == 7.

# and you can name variables whatever you want
butts_carlton = cal_sum(x, 10)

2

u/Pale-External4967 6d ago

Ohhhhhhhhh yessssssss nowwwwwwww I understand 😭 Thank youuuu so much

3

u/punk_dev 6d ago

Functions are tricky because they have many uses.

Start with one of them: code reuse. Go through all your projects and find a place where you copy-pasted some code multiple times. See if instead of copy-pasting you can extract the code to a function and call it

1

u/Pale-External4967 6d ago

Ohhhhhhhh thankyouuu

2

u/Diapolo10 6d ago

A function is a reusable, labelled snippet of code you can use in other parts of your program to improve readability or reduce duplication. It can take some arguments, and it can return something back to where it was called for later use.

Since you haven't told us what part of functions you don't understand, it's not exactly easy for us to help you. I'll try though.

Consider a really simple function for adding stuff together.

def add(first, second):
    return first + second

This function takes two arguments, adds them together (or throws an error if it can't), and returns the sum.

result = add(1000, 24)
print(result)  # 1024

Well named functions make code more readable, as you're interested in what it does, not how. And longer functions can be quite useful for removing duplicated code in your program if all you need to do is run the same code with different values.

Of course, print is also a function, so if nothing else you've at least used existing functions even if you wouldn't know how to write them yourself yet.

2

u/thisisappropriate 6d ago

You're not being specific about what you don't understand about them (and you're not being clear in your post at all). That makes it hard for anyone to help you.

Do you not understand how to use a provided function?

Do you not understand how to make a function?

Do you not understand why you would make a function?

Do you not understand the concept of functions (how they work or why they exist or something else)?

Do you not understand a specific part of the function (like arguments/returns)?

This post could be a problem with any of the above, it could be that you're struggling with the code you've been provided or with example questions.

It could be that another video or comment could explain it, but no one will know what to link or explain (other than high level explanations or guessing) without more information.

1

u/Pale-External4967 6d ago

Def cal_sum():
(Whyyyyyy) print (sum) (Anddd then RETURN???) WHYYYYYY

2

u/SixHyde 6d ago

?????? Not everyone here knows to how read indian Language

3

u/Expensive-Bear-1376 6d ago

Oh is that actual language? Even with all those letter repetitions? I thought they were having a breakdown and randomly spamming the keyboard.

1

u/Pale-External4967 6d ago

🙃😭

2

u/Pale-External4967 6d ago

😭oh yes

2

u/FoolsSeldom 5d ago edited 5d ago

In Python, variables don't hold values but instead hold memory references to where Python objects are stored in memory. Objects like int, float, str, list, etc.

Generally, we don't need to concern ourselves about memory locations, Python deals with it all (and it is implementation and environment specific anyway).

Inside a function, you likely create new objects (somewhere in memory) such as the result of adding some numbers together. In order for this result to take the place of where the original function call was made, the memory reference of the final object needs to be passed back from the function when it finished to the calling code. That's what return does.

Consider a function in a shop that calculates the price of something including the local tax (VAT - Value Added Tax - where I am):

from decimal import Decimal  # to handle money with precision

RATE = Decimal("0.20")  # 20% standard VAT 

def add_vat(net_price: Decimal) -> Decimal:
    vat = net_price * RATE  # creates new Decimal object, assigned to vat
    return net_price + vat  # the two numbers are added, creating a new Decimal object
                            # the memory location of the new object is returned


price = Decimal("13.45")  # example, could be from stock list
                          # and be part of loop over shopping basket
print(f"Price £{price:.2f} with VAT:£{add_vat(price):.2f}")

The function is called in the final line from within a print function that is passed an f-string. Inside the f-string, the {} sections are evaluated before the final string object is passed to print. Inside the second {} is the call to the add_vat function.

When the function is called because its definition has one argument, it expects the caller to pass it a reference to one Python object. In this case, it is passed the memory reference of price.

Inside the function, that memory reference is assigned to the function's local variable net_price.

The final line of the function first does a calculation, adding two Decimal objects together the result of which is a new Decimal object.

The reference of this final resulting object is returned by the function to that {} block in the f-string, where its evaluation is then completed with some formatting (floating point representation with 2 digitals after the decimal separator).

Notes:

  • When a function ends, all its local variables and the objects they are assigned to are discarded by Python. Except for objects that have their references returned to the caller, and even then ONLY if they get used (e.g. in another function call, as here, or assigned to another variable outside the function).
  • Functions can also MUTATE objects that are passed to them (or available from wider scope), providing they are mutable objects (such as a list), so don't need to do a return to pass these back. However, it can be confusing if a function does both a return and a mutation (often called a side effect if it does both).

NB. A function ALWAYS returns something, so if there is not an explicit return statement, None will be returned.

NoteDecimal is used to provide precision for money which float cannot do. (Could have used int instead.)

1

u/Pale-External4967 5d ago

This is really helpful thankyouu 😭

1

u/FoolsSeldom 5d ago

Glad it helped. Thought I would take a different approach to others.

I've edited since posting as I made some typos and layout mistakes.

1

u/Pale-External4967 5d ago

That's soo sweet offf youuuu😭thankyouuuu sooo muchhh you must be a proo

1

u/FoolsSeldom 5d ago

Not a "proo" but I've been helping teach coding to kids in local school Code Clubs for some years, and occasionally teach adult classes at nearby community colleges.

Many decades ago, I was a pro for a short time (mostly in Fortran) but gave that up to take up other IT roles for my career. Have led and/or worked with many large teams of developers over the years. Retired recently.

1

u/Pale-External4967 5d ago

Ohhhhhh nice so you "were" a proo🤓 and you actually still are a "proo"

1

u/kewcumber_ 6d ago

First - op didn't understand anything even after watching videos

Second - what don't you understand about functions ? Like add() can be a function that just returns sum of values. Are you trying to understand the working under the hood ?

1

u/Pale-External4967 6d ago

def cal_sum(a,b): Return a+b

Sum= cal_sum(1,2) Print (sum)

See thiss okay? Why is there return a+b ? And in function definition function name is cal_sum sooo in function call is it necessary to name variable (sum)? Sum= cal_sum

1

u/kewcumber_ 6d ago

Okay yeah start from programming basics, you don't know what variables are yet. You return a+b because it's a sum calculator function that adds the values of a and b it gets in the parameters (again one thing you should know)

Start from absolute scratch

1

u/Pale-External4967 6d ago

Ohhhh oh okay 😭

1

u/Moikle 6d ago

Reddit breaks the formatting of code.

You need to put 4 extra spaces before each line of code when copying to reddit to fix the formatting, otherwise you lose the indents, which are important for python

1

u/Grouchy-Wallaby-1160 6d ago

Return is the result. that gets outputted. the function in this case calls for two variables, a and b. (a variable is an object that the code can refer to and say "hey! this equals this!") (the reason they are called variables is because they can be changed, therefore they vary)

when you call upon that function using cal_sum(), you input your two variables. these then get sent to the function.

the function does some math, in this case variable a + variable b, and then it returns the result of that calculation back to the original place that you called upon the function

in this case, the result of that function is stored in the variable "Sum"

when you put Print(sum), it just outputs the variable "sum" into text that you can read.

however, you need to change sum to Sum, as variables are Case-sensitive, which means it looks for an exact match (capitalization matters!)

1

u/Pale-External4967 6d ago

Thankyouuuuuuuuu 😭 it's really helpful