What is a DEF function for Python [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to coding Python and I just can't seem to understand what a Def function is! I have looked and read many tutorials on it and I still don't quite understand. Can somebody explain to me what it is, what I use it for, and give me some examples. For the examples please make them easy and understandable for a newb to Python. Thanks!

def isn't a function, it defines a function, and is one of the basic keywords in Python.
For example:
def square(number):
return number * number
print square(3)
Will display:
9
In the above code we can break it down as:
def - Tells python we are declaring a function
square - The name of our function
( - The beginning of our arguments for the function
number - The list of arguments (in this case just one)
) - The end of the list of arguments
: - A token to say the body of the function starts now
The following newline and indent then declare the intentation level for the rest of the function.
It is just as valid (although uncommon) to see:
def square(number): return number * number
In this case, as there is no indentation the entirety of the function (which in this case is just one line) runs until the end of line. This is uncommon in practise and not considered a good coding style.

Related

Invoking python functions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Trying to invoke the pay. I am doing something wrong on the "computepay()" invocation?
hrs = input("Enter Hours:")
hours = float(hrs)
def computepay():
p = computepay((hours>=40*10.5) + (hours>40*(10.5*1.5))
computepay()
pay = float(p)
print("Pay",pay)
Your overall code logic doesn't make sense. Your function declaration and definition - the way you call the function inside the function don't match.
def computepay():
The above code says computepay() doesn't take any argument.
p = computepay((hours>=40*10.5) + (hours>40*(10.5*1.5))
In this line of code, you are trying to call the function itself, but with arguments which it doesn't accept and hence you are getting the error.
Apart from this, neither does the argument that you are passing on that line makes much sense. You have called computepay() with argument - (hours>=40*10.5) + (hours>40*(10.5*1.5) but that won't work. (hours>=40*10.5) and (hours>40*(10.5*1.5) will evaluate to booleans and you can't add two boolean values.
I don't know what the logic is that you are trying to implement, but these are some major and obvious faults in your code that I could find.
def computepay():
This function does not accept any parameters and has not been overloaded in any point of the code, so
computepay((hours>=40*10.5) + (hours>40*(10.5*1.5))
will not work. You can overload it in another section of the code as:
def computepay(argument):
but unless you do it so, it will never work. In addition
(hours>=40*10.5)
this is a boolean value meaning that it is either true or false. You are trying to sum 2 boolean values, that also does not make sense. As far as I can see you are trying to implement recursion, hence your function invokes an instance of itself (or another unimplemented overloaded version) that will also not work because you do not have a base case. For more information: https://www.youtube.com/watch?v=nxiObVwQ8MM

Python:Why i can't put in e.g. (x+1) inside def function(here)? [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 4 years ago.
Improve this question
def function(x+4):
return (x*5)+3
SyntaxError: invalid syntax
Why is that? i don't get the logic behind it?
(i know that it is a simple question but i couldn't find an answer to it.
i got many unclear feedbacks about my question,i am sorry about that as english is not my first language i couldn't clarify my question in short:
While i was learning about what return does,i compromised the logic with the logic behind f(x)= codomain as def function(x) = return codomain
but as you know there are functions in maths like f(x+2) = 5x+3. I thought maybe i could do the same on def function,the problem was it was giving a syntax error ,and i was curious about the design idea behind it and if there was an alternative solution to implement this in code.Thanks for answers!
This is a rather uncommon syntax you are suggesting and it is simply not part of Python's syntax, or any language that I know.
Although, what you want to do boils down to updating an argument before it is passed to a function. This can be done with a decorator.
def add_four_to_argument(f):
return lambda x: f(x + 4)
#add_four_to_argument
def func(x):
return (x*5)+3
print(func(1)) # 28
Since you asked about the logic behind that design decision, how would you expect that syntax to behave? Note that it is not the same x being shared everywhere. The following are the same:
x = 5
def f(x):
return x
print(f(x)) # Prints 5
x = 5
def f(y):
return y
print(f(x)) # Prints 5
This allows you to scope your variables and not have to debug the confusing shared state that exclusive use of global variables can cause.
Back to your question though, nowhere else in Python does the addition operator cause assignment (barring abuse of dunder methods...don't do that). So, in your hypothetical f(x+4), what happens to the x+4? Is that supposed to be a placeholder for x=x+4, or is that supposed to be assigned to some new variable representing some ethereal notion of "argument 1" for the function?
Let's dive into it a little further. What about the following example:
def f(x+y):
return x
Suddenly things got a whole lot more ambiguous. How do we call this function? Do we use f(1,2)? Do we only pass a single argument f(3) and guess which portion corresponds to x and which corresponds to y? Even if we figure out the semantics for calling such a function, what does the statement x+y actually do? Does it stand for x=x+y? For y=x+y? For arg1=x+y?
By not allowing the behavior you're describing, Python makes your intent clear. To do a thing, you have to tell Python to actually do that thing. From the Zen of Python,
explicit is better than implicit.

python .apply calling function error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
def awesome_count():
if 'awesome' in dict:
return 1
else:
return 0
products['awesome']= products['word_count'].apply(awesome_count)
TypeError: awesome_count() takes no arguments (1 given)
what is the issue with calling the function. can somebody help?
Looks like your awesome_count function should take one argument, dict:
def awesome_count(dict):
....
You should really call it something besides dict though as that is a built-in data type. For something simple like this d would be fine.
Another thing to keep in mind is that Python is not javascript -- there is no apply method on dicts unless you have subclassed and added it yourself.

Python: wrong assignment of default argument in a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have the following Python function which is definying a method of a class:
def SomeMethods(self,j=0)
According to the Python documentation, if any argument j is assigned when the function is called the default value of it should be 0. However, the variable j assumes the boolean value "True" (checked out in Debug session and actually raising an error because the value "True" goes to the index of a list).
What can this problem be due to?
The call is executed when a button on a PyQt GUI is toggled, and the connection between the button and the function is made here:
QtCore.QObject.connect(checkBox,QtCore.SIGNAL("toggled(bool)"),self.SomeMethods)
Please, share your code. See below - it works fine:
def SomeMethods(self, j=0):
print j
SomeMethods('a')
0
SomeMethods('a', True)
True
default argument is useful - among other cases - because it allows you to omit most common values used in your code. If you provide the actual value - that value will be used instead of default. Obviously, the method is called with argument True
EDIT:
Let me clarify - you may call your method either as SomeMethods() - and then j will be 0 inside the method; if you call it as SomeMethods(True) or SomeMethods(j=True), then j value will be True.

Class instance attributes won't seem to initialize [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This seems like such a simple question, but there don't seem to be any answers that address my particular issue, which is why the init method never actually initiates the class instance variable 'listlist'.
class PointsList():
def _init_(self):
self.listlist = [None]
def addtolist(self,item):
self.listlist.append(item)
def getlist(self):
return self.listlist
a = PointsList()
a.addtolist('Scarlet')
print a.getlist()
Running the above code gives me:
AttributeError: PointsList instance has no attribute 'listlist'
The error is traced to line 5 when the 'addtolist' method attempts to add an item to the evidently nonexistent 'listlist' instance variable.
I've checked the indentation many times but it appears to be sound. Is there something wrong with my Python installation? I am using Python v2.7.5 (haven't gotten around to 2.7.6 yet) and the Spyder IDE v2.2.0
Python special methods use two underscores at the start and end; you need to name the initializer __init__, not _init_:
class PointsList():
def __init__(self):
self.listlist = [None]
Underscore characters are usually shown connecting up forming a longer line, but there are two underscores before init, and two after.

Categories