What are functions, and how are they used [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 22 days ago.
Improve this question
I am a beginner and need to know what a function for a small tic tac toe project. But all I need to know is this as understood the rest. is and how to use one as well as what can they do
I was just learning from the python docs about a function and could not understand, as I was searching on google still, I could not find anything, if one could help, it would help me loads.
This is the code for my tic tac toe that the YouTuber gave as an example:
def cool(a,b):
return(a+b)
print(cool)
Thanks,
Gops

Welcome to the world of programming.
As a beginner, you should imagine functions as "reusable" part of your code, with the feature of having temporal variable that can change the behavior of the function based on the body of the function.
Calling the functions
To reuse that part of your code that you wrote in your function, you have to call it.
def python_cool():
print("Python is cool")
python_cool()
python_cool()
python_cool()
Technically, this code is the same as:
print("Python is cool")
print("Python is cool")
print("Python is cool")
At this point, if you we are talking about parameters, we have to talk about arguments too.
Parameters
Parameters are the one that you are declaring your function with:
def sample_function( paramter1, parameter2, paramterN ):
Arguments
Arguments on the other hand, are the values when you are calling the function with.
sample_function(argument1, argument2, argumenN)
Example
def print_values( value_1, value_2) :
print("The first value is: ", value_1)
print("The second value is: ", value_2)
print_values(1, 2)
print_value(True, False)
print_values("apple", "peach")
Return values
Another great benefits of functions that they are able to "become" a value that you can store in a variable in the future
For example:
def multiply_by_three( number ) :
return number * 3
This function has a return value of an integer which can be used as:
sample_variable = multiply_by_three(5)
which is technically:
sample_variable = 15

In Python, a function is a block of instructions or code that is used to perform an action. Functions provide an organized way to structure code, making it easier on the human eye. It seems as if you are tired to add a and b, however, a and b are not given values in the return statement.

I self-learned python and would look at the W3Schools stuff which is quite good.
A function is, in effect, a way of running a section of code with a keyword, if you had
def cool(a,b)
print(a+b)
cool(1, 3)
You would have the function running the code you have put inside it and so printing the value of a+b (4) using the values a and b which were passed into the function.
The code you posted would not work because to run the function, a and b need to be passed, which is not done in the question.

Related

Difference among Yield vs. Print vs. Return [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Two questions/clarifications:
Most people may ask the difference between yield and return.
def square(n):
for i in range(n):
yield i**2
for i in square(10000000000):
print(i)
I understand this is a way to run the 'function' in a generator way. If we directly run print([i**2 for i in range(10000000000)]) or this way
def square():
return [i**2 for i in range(10000000000)]
Python will run almost infinite time. However, if we run in the generator way, we will save a lot of memories, and Python can keep printing the squared numbers. In the generator, we directly print out the result we got and do not save it anywhere. However, in a function-return way, we will save the results into a list so it will waste a lot of memories and time. Am I correct about this?
My another question is yield vs. print: if we want to save memories and hope to directly print out the results, then why don't we just use print to directly print out the result, like:
def square(n):
for i in range(n):
print(i**2)
square(10000000000)
Python will do the same thing as the yield-generator way, right? So what is the difference between yield and print? Thanks!
Depends on the purpose and the caller.
When you are print-ing, you are calling a console writer in the loop. Thus print sends to a fixed and forced destination.
When you are yielding, you are not calling anything, but simply return-ing your output in gradual way to "any" caller which can take it and do whatever it like.

Bind the output of a method before using or call the method when you need its output? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
In both examples, class.method() returns a list.
Example A:
if class.method():
for i in class.method():
# do stuff
Example B
list = class.method()
if list:
for i in list:
# do stuff
Which is better? It would seem to me that in some languages (but I don't know which), example A would result in class.method() being needlessly evaluated twice, and example B would be best practice. However, perhaps other languages (again not knowing which) might retain the output of a method in memory in case that method is called again, therefore avoiding having to do the same evaluation twice and resulting in little difference between examples A and B. Is this so? If so, can you give examples of a language for each case? And the real reason for the question: which is best practice in Python?
Unless your Python interpreter has JIT capabilities, the method will be evaluated every time you call it.
And even when the JIT compilation is possible, methods have to be proven by the compiler / interpreter that they do not have any side effects, that is they are deterministic.
For example, consider a method that pulls data from a database or a method that contains a call to a random number generator:
import random
def method():
return random.uniform(0.0, 1.0)
Output of such a method cannot be saved in memory because the second time you call it, it may change.
On the other hand, getter methods that accumulate data are a great example of a deterministic method, given that they do not call a non-deterministic method in their body.
from dataclasses import dataclass
#dataclass
class Example:
a : list
b : list
def method(self):
return self.a + self.b
In practice, you are better of to not assume anything from the compiler / interpreter and do these small, easy to do optimizations yourself. You also have to consider that your code can be run on multiple platforms, which further complicates things.
So I would recommend you to call the method only once and save its output in a temporary variable:
result = class.method()
if result :
for i in result:
# do stuff
And given that it's Python, I recommend to ask for forgiveness with the try keyword if most of the time you run the method, its output is not None:
result = class.method()
try:
for i in result:
# do stuff
except TypeError:
pass

Returning values from functions in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a function in Python, and in that same function i have multiple if statements. Lets say i want to return a value from my function. I create a local variable and change it in if statements. Problem is i need it to be defined in function so it works in every if statement, but unlike in C i cant use int a, b, c; but instead i have to give them a value. Problem is that value is going to be recognized if none of the if statements are true.
One clear solution is to take in global values as parameters of the function but i dont want to do that because i dont need their value i only want to change it.
velocity = 5
distance = 6
def calc(distance):
# i would need to say velocity = 5 here
distance + velocity # this does nothing but uses velocity so code cant run
if distance < 7 : # without defining velocity first (in first comment)
velocity = 6
elif distance < 10:
velocity = 7
return velocity
If you really don't want velocity to be a parameter of the function then build an object that has velocity as member variable and calc as method.
When writing Python functions, it is a good idea to strive to follow the following design principles, which come from functional programming.
A function's output should only depend on its inputs. That means that everything that influences the result should be a parameter of the function. This is generally easy to do, and makes the function self-documenting. When you write def foo(x, y, z), it is immediately obvious that the result depends on x, y and z.
A function preferably should only return its output. So it should not use global to modify variables outside of its scope, nor should it modify mutable arguments. (This cannot always be achieved in practice, but it is good to strive for.)
The main advantage is that such functions can be tested and debugged apart from the rest of the application, making those tasks much easier.
In this case,
def calc(distance)
should be:
def calc(distance, velocity)

Why is "wrapper" is better name for a decorator than "adder"? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
A bare-bones example of a decorator is:
def strong(func):
def wrapper():
return '<strong>' + func() + '</strong>'
return wrapper
#strong
def greet():
return 'Hello!'
wrapper is an entitled name for the 'inside first-order-function' inside the Higher-Order function strong.
My question is that the word wrapper has no real meaning except to confuse newbie. Why not use 'adder', because it can be discerned intuitively?
Decorator pattern - Wikipedia
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.[1]
The keyword in Wikipedia's explanation is 'added'.
And in Cambridge English Dictionary:
to add something to an object or place, especially in order to make it more attractive:
The keyword is also 'add'.
So why is wrapper better than 'adder'?
When you use a decorator, you've wrapped your original code in another function, making the original function invisible. To continue your example,
def strong(func):
def wrapper():
return '<strong>' + func() + '</strong>'
return wrapper
#strong
def greet():
return 'Hello!'
def weak_greet():
return 'hi'
print(greet)
print(weak_greet)
If you run this, you get the following output.
<function strong.<locals>.wrapper at 0x000000000129A268>
<function weak_great at 0x000000000129A2F0>
When you used the decorator, you took your function, created a new function that wrapped code around your old function and returned that new, anonymous, function.
You can see some unpleasant effects if you try to pickle it.
if you do pickle.dumps(weak_greet), you get b'\x80\x03c__main__\nweak_great\nq\x00.'. but if you try to pickle.dumps(greet), you get AttributeError: Can't pickle local object 'strong.<locals>.wrapper'. (dealing with decorated classes and functions that must be pickled is one of the circles of hell I don't wish to revisit any time soon).
You are not adding to your function. You are wrapping your original function in a shiny new function. That new function says, "There's something I'm hiding in here and I won't tell you what it is (functools.wraps can sometimes help with this, as it would in your case). But, when you give me input, I'll alter it like so (or not at all), pass it to my secret function, (possibly) alter the output and give you that. Your original function is inaccessible (hence pickle's confusion).
NOTE: You can re-create the look of your original function by further wrapping your wrapper with #functools.wraps(original_function), which does not affect output, but wraps everything in a box to make it look exactly like the original function. so,
from functools import wraps
def strong(func):
#wraps(func)
def wrapper():
return '<strong>' + func() + '</strong>'
return wrapper
would now look like your original function and be pickle-able. It would be like wrapping a surprise present, and then wrapping the present again with wrapping paper that told you (in great detail) what the surprise was.

Defining a function in Python (There's a big catch) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So a few days ago we got this exercise where we need to make a function that takes two lists as input and calculates the difference of their averages.
Sounds simple enough, but there are a few catches:
the entire thing needs to be one line long
you can absolutely NOT use ':'
They encouraged us to use 'import', 'help()' and 'dir()'.
The thing is that I know how to make it only one line long, but the no ':' is really annoying.
The way I see it, I first need to define a function (without code) then change it's 'func_code' attr.
Any ideas on how can I do it?
And how do the params fit into this?
Any answer is appreciated!!!
Edit: thanks for all the answers and the creative minds that said char(58) is the solution, it is really creative and I haven't thought of that solution but it's not allowed since you are using ':' even though not directly.
No : means you can't use lambda. That leaves higher-order functions or eval trickery.
eval('lambda a,b{}sum(a)/len(a)-sum(b)/len(b)'.format(chr(58)))
This meets the letter of the law, but violates its spirit.
Unfortunately, without a function composition function, higher-order functions don't work very well. Implementing one without : is tricky.
Here's what should be a fairly self-contained solution, using a pickled code object. I've created it in Python 3.6, and the specific bytestring is very likely to be version specific, but you can create your own version pretty easily using the expanded code below. Anyway, here's the oneliner:
f = __import__('types').FunctionType(__import__('pickle').loads(b'\x80\x03cipykernel.codeutil\ncode_ctor\nq\x00(K\x02K\x00K\x02K\x04KCC t\x00|\x00\x83\x01t\x01|\x00\x83\x01\x1b\x00t\x00|\x01\x83\x01t\x01|\x01\x83\x01\x1b\x00\x18\x00S\x00q\x01N\x85q\x02X\x03\x00\x00\x00sumq\x03X\x03\x00\x00\x00lenq\x04\x86q\x05X\x01\x00\x00\x00aq\x06X\x01\x00\x00\x00bq\x07\x86q\x08X\x1e\x00\x00\x00<ipython-input-1-384cc87bd499>q\tX\x16\x00\x00\x00difference_of_averagesq\nK\x01C\x02\x00\x01q\x0b))tq\x0cRq\r.'), globals())
Here's what I'm doing without the one-line shenanigans:
import types # replace these import statements with calls to __import__ in the oneliner
import pickle
def difference_of_averages(a, b):
return sum(a)/len(a) - sum(b)/len(b)
payload = pickle.dumps(difference_of_averages.__code__) # embed as a literal in the oneliner
f = types.FunctionType(pickle.loads(payload), globals())
Hmm, having tried this on the few different interpreters I have at hand, it looks like my pickle string includes some nonsense from the IPython interpreter I created it in. If you get errors using my string, I'd suggest just building your own (which, if it contains any junk, will at least be junk compatible with your environment).
Not using ':' is tricky because you normally use it to define the function body, like this:
def average(number_list):
return sum(number_list) / len(number_list)
However, I know of one way to define a function that doesn't require require writing a block for its body: You can assign a lambda function (or even an already-defined function) to a function you want to define, simply by using the equal sign (=). For example, if you want to create an average() function, you might write:
average = lambda number_list: sum(number_list) / len(number_list)
average might look like a variable, but you can use it as a function. It simply calls the lambda function that takes a number_list as input and returns the average value of the number_list. You can call it like this:
value = average([10, 11, 12]) # sets value to 11
Now, lambda functions can only have one line. But that's not really a problem for you, since your task requires you to only use one line.
Do you understand what to do now? Your exercise requires you to find the average of two lists, so you might consider using a lambda function that takes two inputs (instead of just one, like in the example I gave above). Also bear in mind that you need to return the difference, and if the difference should always be positive, consider using Python's abs() function somewhere in your code.
Edit: Well, gilch's response made me realize that I can't use lambda because even they use :. So apparently you can't use my advice. It's still good to know about lambda functions, though.
The fact that you are encouraged to use import makes me wonder if it's okay for you to use an already-defined function from some module to define your own function. Kind of like this:
import math; average = math.difference_of_averages
However, that depends on you being able to find a (probably standard) function that does exactly what you want. (I've briefly checked the math and numpy modules, and haven't found anything that matches yet.)
And maybe this means that you can create a module and define it anyway you like. The module is in its own world, so it's not constrained to the rules of your exercise.
Then again, maybe not.
So unless you want to "sneak-in" a : in an eval statement (as gilch suggested), like this:
average = eval('lambda number_list' + chr(58) + ' sum(number_list) / len(number_list)')
there's no way I know of off hand to avoidi using :.

Categories

Resources