#๐Ÿ”’ What is function actually

52 messages ยท Page 1 of 1 (latest)

modest kettleBOT
#

@lucid stump

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

nimble jolt
#

Functions are there so you dont have to type everything again.

For example:

userinp = input("enter a num: ")
if userinp.isidigt():
print("your num is" + userinp)
else:
print("wrong input")

In the example If you have to do that "number check" multiple times in your code, instead of typing everything again, just put it in a function and call it everytime you need it.

Sry if my explanation is ass

final yarrow
#

Basically function is like a blueprint

lucid stump
final yarrow
#

You put a code in the function

#

You can use the same code in different files

#

By importing

lucid stump
#

Okay

final yarrow
#

Functions is useful if you also want structure it allows you to control what cod

#

Code runs

#

Like def a
Runs adding
Def b can be used for subtraction

lucid stump
#

I just learn python from David j malen, cs50p

final yarrow
#

And uh what else is there

final yarrow
#

They also teach functions

lucid stump
#

I am on unittest

final yarrow
#

Iirc

#

Idk when but the last time I checked I was

#

At dinner time smt

#

I quit

#

After that

final yarrow
#

Things

nimble jolt
river zinc
#

A function is a part of code that you write once and use many times in the future

For example, consider this simple example:

# Assume that this numbers is got from a user
a = 2
b = 3
result = a + b
print(f"{a} + {b} = {result}")

# And again
a = 10
b = 5
result = a + b
print(f"{a} + {b} = {result}")

# And again...
a = 42
b = 42
result = a + b
print(f"{a} + {b} = {result}")

There's so many repeats. And a function can help here:

def sum(a: int, b: int) -> int:
    return a + b

a = 2
b = 3
result = sum(a, b)
print(f"{a} + {b} = {sum}")

a = 10
b = 5
result = sum(a, b)
print(f"{a} + {b} = {sum}")

a = 42
b = 42
result = sum(a, b)
print(f"{a} + {b} = {sum}")

Looks like that it's not helping, because we're just replaced an adding operator to a correspond function and all. But a main idea here that we're reusing the same login through all cases where we need to add numbers

Consider this more complex case:

# Keys is user IDs
users = [
    {
        "username": "john",
        "password": "my_secret_password",
    },
]


def authorize(username: str, password: str) -> bool:
    """
    Authorize a user with a username and a password.

    :returns: A boolean indicating that a user have been authorized or not
    """
    for user_cred in users:
        if username == user_cred["username"] and password == user_cred["password"]:
            return True

    return False


def authorize_user(username: str, password: str) -> str:
    is_passed = authorize(username, password)
    
    if not is_passed:
        return "Wrong credentials"

    return "Welcome!"


if __name__ == "__main__":
    result = authorize_user("john", "my_secret_password")
    print(result)

Here we're split an auth process from a decide of which a message to return. We're using here only once this function, but it can be use in various components where you need to authorize a user with a username and a password

#

oh

#

its big one

final yarrow
nimble jolt
lucid stump
nimble jolt
lucid stump
final yarrow
lucid stump
#

Brocode and cs50p which is really a complete course???

final yarrow
#

Said here too

river zinc
#

!resources

modest kettleBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

river zinc
#

Here's a good collection of material

nimble jolt
lucid stump
#

@nimble jolt is brocode have explain full python?

dull berry
#

@lucid stump
similar to loops, where you'd want to repeat a few lines of code.

except, that with functions, you can "assign" a name to said code, and reuse it wherever in the project.

they also allow more flexibility and functionality than loops; by having arguments, and special breaks (/return).

in python specifically, they also have a few other features as well; like decorators or acting as a generator.
they also store some attributes just like an object. like docstrings, code, arguments, and annotations.
-# which can be accessed to customize behaviors even more...

river zinc
#

๐Ÿ‘€

modest kettleBOT
#
Print and return

Here's a handy animation demonstrating how print and return differ in behavior.

See also: /tag return

river zinc
nimble jolt
dense iris
# final yarrow You should try leetcode if you wanna learn more

leetcode is not very good for learning programming, if anything it can give you bad habits when you are too new of a programmer, leetcode is more for learning DSA (for OP of the thread which might not know this, DSA stands for Data Structures and Algorithms)
codewars is probably better for learning more general programming that isn't primary about DSA

modest kettleBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.