Why is there a syntax error in my Python function? - python

number=list(map(lambda x:int(x), input().split()))
first=".|."
second='-'
median=((number[0]-1)//2)+1
def Door(number[0],number[1]): # <<-- this one is resulting in a syntax error.
So I still fail to understand what is wrong with this code.
Can you please help me?
Thank you.

In this line:
def Door(...):
you are defining a function. You define a function with variables as parameters. When you call the function you pass it values.
What I think you are planning to do is first define Door() and then later call it with the values number[0] and number[1].
So begin your definition of the function like this:
def Door(a,b):
and when you want to call it, then you pass it the values number[0] and number[1], like this:
mydoor = Door(number[0],number[1])
Then, inside Door(), when your code refers to a and b, it is using the values of
number[0] and number[1]. This disconnect is so that the function can be called from different places with different parameters.
This applies even if you are defining the function just to modularize your code, and you only ever plan to call it from one place.

Related

function at the end of code- why do i have to place it?

I'm just starting my adventure with Python. Unfortunately, I can't figure out why, at the end of my code, I have to add myfunc(). Without it my code doesn't display.
How is it if I use more than one definition then I have to put each definition at the end of the code?
def myfunc(a=4,b=6):
sum = a + b
print(sum)
myfunc()
The thing throwing you off is that you don't need to put all your code into a function. Your code could (and should) be rewritten as this:
sum = a + b
print(sum)
This code will do the exact same thing. A function, by definition, is a block of code that is given a name, so you can use it multiple times without having to rewrite the whole block of code every time you want to use it. Because you are putting your code into a function, you must tell Python that you want to run that code too.
When you define a function with def, all you're doing is telling Python that your function exists. If you only had that def block and didn't call myFunc() at the end, Python would simply have gone, "Okay, your function exists. Neat."
What you want is not only to tell Python about the function but instruct Python to run the function. That's where the function call comes from.

Running function code only when NOT assigning output to variable?

I am looking for a way in python to stop certain parts of the code inside a function but only when the output of the function is assigned to a variable. If the the function is run without any assignment then it should run all the inside of it.
Something like this:
def function():
print('a')
return ('a')
function()
A=function()
The first time that I call function() it should display a on the screen, while the second time nothing should print and only store value returned into A.
I have not tried anything since I am kind of new to Python, but I was imagining it would be something like the if __name__=='__main__': way of checking if a script is being used as a module or run directly.
I don't think such a behavior could be achieved in python, because within the scope of the function call, there is no indication what your will do with the returned value.
You will have to give an argument to the function that tells it to skip/stop with a default value to ease the call.
def call_and_skip(skip_instructions=False):
if not skip_instructions:
call_stuff_or_not()
call_everytime()
call_and_skip()
# will not skip inside instruction
a_variable = call_and_skip(skip_instructions=True)
# will skip inside instructions
As already mentionned in comments, what you're asking for is not technically possible - a function has (and cannot have) any knowledge of what the calling code will do with the return value.
For a simple case like your example snippet, the obvious solution is to just remove the print call from within the function and leave it out to the caller, ie:
def fun():
return 'a'
print(fun())
Now I assume your real code is a bit more complex than this so such a simple solution would not work. If that's the case, the solution is to split the original function into many distinct one and let the caller choose which part it wants to call. If you have a complex state (local variables) that need to be shared between the different parts, you can wrap the whole thing into a class, turning the sub functions into methods and storing those variables as instance attributes.

Calling a python function

I am trying to make a python library that allows me to make custom tkinter widgets that are more aesthetically pleasing than the built-in ones. However, I have run into a problem while defining a few functions.
The problem stems from the difference between functions like append() and str(). While the append function works as follows...
somelist = ['a', 'b', 'c']
somelist.append('d')
The str() function works like this...
somenumber = 99
somenumber_text = str(some_number)
You 'call upon' the append function by (1) stating the list that you are modifying (somelist), (2) adding a period, and (3) actually naming the append funtion itself (append()). Meanwhile you 'call upon' the str function by placing a positional argument (somenumber) within its argument area. I have no idea why there is this difference, and more importantly if there is a way to specify which method to use to 'call upon' a function that I define myself?
Thanks...
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
You really don't need to create a class, or any methods. You can make a plain-old function that's similar to bind, and just take the widget to bind as a normal parameter. For example:
def bind_multi(widget, callback, *events):
for event in events:
widget.bind(event, callback)
That means you have to call this function as bind_multi(mybutton, callback, event1, event2) instead of mybutton.bind_multi(callback, event1, event2), but there's nothing wrong with that.

Parentheses in Python's functions and decorators(wrappers)

Thanks for reading my question. As I'm still new to Python, I would like to ask about the () in Python.
def addOne(myFunc):
def addOneInside():
return myFunc() + 1
return addOneInside # <-----here is the question
#addOne
def oldFunc():
return 3
print oldFunc()
Please note that on line four, although the programme returns a function, it does not need parentheses(). Why does it NOT turn out with an error for syntax error? Thank you very much for your answers in advance!
The parentheses are used to run a function, but without them the name still refers to the function just like a variable.
return myFunc() + 1
This will evaluate the myFunc function, add 1 to its value and then return that value. The brackets are needed in order to get the function to run and return a numeric value.
return addOneInside
This is not actually running addOneInside, it is merely returning the function as a variable. You could assign this to another name and store it for later use. You could theoretically do this:
plusOne = addOneInside
plusOne()
And it will actually call the addOneInside function.
The particular instance in your initial question is known as a Decorator, and it's a way for you to perform code on the parameters being passed to your function. Your example is not very practical, but I can modify it to show a simple use case.
Let's say that you want to only have positive numbers passed to your function. If myFunc is passed a negative number, you want it to be changed to 0. You can manage this with a decorator like this.
def addOne(myFunc):
def addOneInside(num):
if num < 0:
num = 0
return myFunc(num)
return addOneInside # <-----here is the question
#addOne
def oldFunc(number):
return number
To explain, the #addOne is the decorator syntax, and it's attaching the addOneInside function to be called on the argument/s of oldFunc whenever you call it. So now here's some sample output:
oldFunc(-12)
>>> 0
oldFunc(12)
>>> 12
So now you could add logic to oldFunc that operates independently of the parameter parsing logic. You could also relatively easily change what parameters are permitted. Maybe there's also a maximum cap to hit, or you want it to log or note that the value shouldn't be negative. You can also apply this decorator to multiple functions and it will perform the same on all of them.
This blogpost explained a lot for me, so if this information is too brief to be clear, try reading the long detailed explanation there.
Your indentation in function addOne() was incorrect (I have fixed it), but I don't think that this was your problem.
If you are using Python3, then print is a function and must be called like this:
print(oldFunc())

Can the same parameters be used in 2 different definitions? Python

Say I had a function in Python:
def createCube(no_of_cubes):
This function creates cubes and the number of cubes it creates is set by the parameter: no_of_cubes
If i then wanted to create another function:
def moveCubes():
and I wanted the parameter no_of_cubes to be used in this function, and for the parameter to use the same integer that has been inputted for the first function. How would I do so? Or is it not possible?
A parameter is merely an argument to a function, much like you'd have in a maths function, e.g. f(x) = 2*x. Also like in maths, you can define infinite questions with the same arguments, e.g. g(x) = x^2.
The name of the parameter doesn't change anything, it's just how your function is gonna call that value. You could call it whatever you wanted, e.g. f(potato) = 2 * potato. However, there are a few broad naming conventions—in maths, you'd give preference to a lowercase roman letter for a real variable, for example. In programming, like you did, you want to give names that make sense—if it refers to the number of cubes, calling it no_of_cubes makes it easier to read your program than calling it oquhiaisnca, so kudos on that.
I'm not sure how that bit fits into your program. A few of the other answers suggested ways to do it. If it's just two loose functions (not part of a class), you can define a variable outside the functions to do what you want, like this:
1: n = 4 # number of cubes, bad variable name
2: def createCube(no_of_cubes):
3: # things
4: def moveCubes(no_of_cubes):
5: # different things
6: createCube(n)
7: moveCubes(n)
What happens here is that line 6 calls the function createCube and gives it n (which is 4) as a parameter. Then line 7 calls moveCubes giving it the same n as a parameter.
This is a very basic question, so I'm assuming you're new to programming. It might help a lot if you take some python tutorial. I recommend Codecademy, but there are several others you can choose from. Good luck!
It is possible. But that two definitions get that parameter as their own one. I mean that parameter works only the definition scope. It may not be harmful for another same name parameter on different definitions.
If you cannot, probably you shouldn't do it.
If they're two separate functions (not nested or so), they should not share parameters.
If they do have connection in some way, a better way is to define a class:
class Cube:
def __init__(self, no_of_cubes):
self.no_of_cubes = no_of_cubes
def create_cube(self):
# use self.no_of_cubes
pass
def move_cubes(self):
# use self.no_of_cubes
pass
c = Cube(no_of_cubes)
c.create_cube()
c.move_cubes
Unless you know what you're doing, don't define global variable.
You can load the function moveCubes() inside createCube(). For example:
def createCube(no_of_cubes):
# Do stuff
moveCubes(no_of_cubes)
def moveCubes(no_of_cubes):
# Do more stuff
Or you could define no_of_cubes out of the functions so it is accessible to all.
no_of_cubes = 5
def createCube():
global no_of_cubes
# Do stuff
def moveCubes():
global no_of_cubes
# Do stuff

Categories