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)
Related
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.
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 1 year ago.
Improve this question
I am writing a code with the purpose of calculating a math function (given as an input) and calculate it with different values of x (without defining the x).
Example: input: y=log(2x) and i have to calculate for x=3,5,8
With the math module is quite easy to calculate the value of y given x but i can't find a solution to keep the x as variable and then calculate y depending on the change of x.
Since the moment that i can't write the function as a string i tried to define a new function
Example: def function(f, x)
So i just needed to input function(f=math.log(2x),x) but the problem is still there because when i recall the function changing the x (Example : function(f,x=5)) i don't have the f defined anymore.
So briefly, how i can make the functions of the math module dipendent from x?
You simply need to define a new function.
def example(x):
return math.log(2 * x)
Then you can call the function using the usual syntax
example(x)
As correctly noted in the comments, you can also define this function using anonymous syntax
example = lambda x: math.log(2 * x)
example(x)
Although this sort of defeats the purpose of anonymous functions if you're planning on giving the function a name anyway.
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
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 2 years ago.
Improve this question
After receiving an error in the code below i ended up adding
new_list = []
summation = 0
after the second line. But i fail to understand why i had to do that. I thought variables did not have to be declared early on in python
a = int(input())
b = int(input())
while a <= b:
if a % 3 == 0:
new_list.append(a)
a += 1
for number in new_list:
summation += int(number)
print(summation / len(new_list))
In general, Python does not require variables to be declared (except for a couple of cases). In this case, you are not declaring a variable but rather initializing it. Let's imagine that variables are boxes. In python, you don't have to say, please make a box and call it x. The issue is when you come across summation += int(number). This tells python, please take out whatever is in the box called summation, add int(number) to it, and put it back in the box. But you haven't yet put anything in the box. So python says sorry, there's nothing in the box at the moment so I can't take anything out. Same for new_list.append(a), that asks python to please append a to whatever is in the box. So python looks in the box to figure out how to append something to it but it can't find anything so it shows an error.
You may ask, why doesn’t python just put 0 in the box? Well, python doesn't know that what you want in the box is an int. Maybe you wanted a fraction, a complex number, or something you make up yourself that happens to be able to be added to a number. The same goes for the list, python does not know that you wanted a list and not a set, dictionary, tuple, counter, queue, or some other collection. So rather than guess, and possibly get it wrong (which would cause all kinds of weird bugs due to the slight differences in how these work with addition), it just gives you an error.
It depends on what you're doing with the variable. If you're assigning a value to the variable, it will initialize the variable in the loop itself. But if you want to modify a variable like you did with .append(), you have to declare it first as it has to be declared to be modified.
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 6 years ago.
Improve this question
When I'm reading docs or examples, I often see the idea come up that you can assign an anonymous function to a variable. Why would I ever actually do this rather than just define a new function?
Some examples:
Clojure/Lisp
(def add2
(fn [a] (+ 2 a))
(add2 4) ;; => 6
Python
add2 = lambda e: e + 2
add2(3) # => 5
Scala
val add2 = (x: Int) => x + 2
add2(5) /* => 7 */
Obviously, these are trivial examples, but in production code, I usually think of an anonymous function being a one off function that I need for a specific use case (think higher kinded types and the like).
Can anyone explain why I would assign an anonymous function to a variable? Is it a runtime/compile time thing? Are there certain performance characteristics that make this favorable?
I think the way it is presented is more so the reader truly understands that functions are first class in said languages. Had they only used them as arguments to other functions, perhaps the point might be lost. But using them in a very value like way, as the right hand of an assignment, or calling a method on the lambda itself etc drives home the point that these are quite similar to numbers, strings, maps or any other value in the language.
Personally, I don't use this pattern because as other comments have mentioned, it makes code harder to read and debug, as well as in some me cases not having the full power of proper function declaration (Python).
However, when one is writing code which actually makes use of function arguments, one is more or less doing just that. Only the assignment happens more indirectly than the usage of the operator.
According to the Python Docs:
Semantically, they are just syntactic sugar for a normal function definition.
afaik, there are no special performance characteristics for lambda that makes it favourable. If you are thinking of using lambdas for complex tasks, think again, use functions.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
Edit: Added StefanS' suggestion
In Clojure, the reason is so you can use the function in more than one place. In fact
(defn add2 [x] (+ x 2)
is just shorthand for
(def add2 (fn [x] (+ x 2))