What are blocks of code in Python? The definitions are all confusing - python

I have looked up definitions, but all of them seem confusing.
Sorry I am a very new to this and I would improve it if there were a simpler way of putting it.

A code block is a group of statements that will be run as a unit.
For example:
if (condition):
# Statement 1
# Statement 2
# Statement 3
else:
# Statement 4
# Statement 5
# Statement 6
You will find that statements 1,2,3 will have the same indentation and therefore is of the same block.
And similarly, statements 4,5,6 is of a another block.
You may refer to:
Execution model
Flow of Control in Python

When we say "block" we mean an element of code nested inside another syntactical element, like a method or function, or a structure like if or for.
The exact definition depends on your language's syntax tree, something that's formally defined.

All of your programs, consist of too many blocks.
A block is just a concept and you can't see it like as function. A block is the structure of code to separate part of the code from another part of the code.
A function is a block, and classes are blocks and self consist of many blocks inside.

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.

What is the technically correct meaning of a 'nested IF statement'?

A very quick (and hopefully easy) question.
A colleague and I had a disagreement when discussing a nested IF statement. I assumed that it meant the IF statement was nested in another control structure/statement (e.g. a FOR loop, IF statement, CASE statement etc). My colleague thought it meant the IF statement needed to be nested in another IF statement.
Which of us is correct and why (might not be easy to answer)?
Your colleague is correct.
Nesting if statements refers to the logic tree thats gets created by adding branches, its location within the rest of your code bears no interest to this.
Similarly, the following wouldn't be a nested if because its creating a seperate logic tree within the for loop.
if i:
for x in i:
if x:
nested "if" statements means it's one after the other, for instance:
if(shouldLogin) {
if(isUser) {
if(userIsAdmin) {
console.log('some code')
}
}
}
Ideally, depending on the situation, you'd want only 1 if:
if (shouldLogin && isUser && userIsAdmin)
Not a great example but hope it helps
A nested if statement means that it is one after another, just like nested for loop (maybe you are more familiar with that).
A nested if statement looks like this:
if some condition:
if something:
# do something
Just like a nested for loop:
for i in something:
for some in something:
# do something
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
if statement:
if another_statement:
do_something()
else:
do_another_thing()
elif not statement:
if another_statement:
do_something()
else:
do_another_thing()
else:
yet_nother_func()

loop is taking data from outside of loop

full code is here: https://repl.it/repls/UnevenLovingDecagons
line 29 with colony_size=(randrange(50,150)) is outside of loop
then at line 42 loop starts.
colony_size is in line 45 as well.
I would like the colony_size to be influenced by line 29 only once. With second run of loop I'd like the colony_size to be influenced only by what is going on inside of the loop. How can I do so?
part code below:
colony_size=(randrange(50,150))
the one above is still outside of loop
colony_size=(colony_size+immigrants)-died
this one is inside
enter code here
enter code here
enter code here
The concept you're looking at is scope. Loops do not have their own scope in python, the why of this was asked in this question: Scoping in Python 'for' loops
After the following code is executed:
x = 1
i = 1
for i in (2,3,4,5):
x = i
both x and i will contain 5. And the same would be true if they were set or changed in any other kind of loop.
There are several ways to control the scope.. and the most common is functions, which you aren't using in your code. Their variables are contained in their own scope, and you must explicitly pass variables to and from them (using the return keyword). You could also consider comprehensions, although their variables were not contained in the same way in earlier versions of python.
More specifically, in your code.. you may consider putting everything in the while True loop into a function.. (my_function as an example)
while True:
my_function(colony_size)
Or something like that. Then it will use the original colony_size the next time it runs (since you did not return it)
Of course, perhaps the easier option here is to just use a different variable name.
You should have another variable to define a default colony_size at line 29 like:
default_colony_size = (randrange(50,150))
Then define colony_size as a an empty int or just 0 before the loop.
At the start the loop you want to want to do something like this:
if colony_size == 0
colony_size = default_colony_size
Pardon syntax errors as I do not know Python very well

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.

Python "with" statement but no "as" [duplicate]

I just realized there is something mysterious (at least for me) in the way you can add vertex instructions in Kivy with the with Python statement. For example, the way with is used goes something like this:
... some code
class MyWidget(Widget)
... some code
def some_method (self):
with self.canvas:
Rectangle(pos=self.pos, size=self.size)
At the beginning I thought that it was just the with Python statement that I have used occasionally. But suddenly I realize it is not. Usually it looks more like this (example taken from here):
with open('output.txt', 'w') as f:
f.write('Hi there!')
There is usually an as after the instance and something like and alias to the object. In the Kivy example we don't define and alias which is still ok. But the part that puzzles me is that instruction Rectangle is still associated to the self.canvas. After reading about the with statement, I am quite convinced that the Kivy code should be written like:
class MyWidget(Widget)
... some code
def some_method (self):
with self.canvas as c:
c.add (Rectangle(pos=self.pos, size=self.size))
I am assuming that internally the method add is the one being called. The assumption is based that we can simply add the rectangles with self.add (Rectangle(pos=self.pos, size=self.size))
Am I missing something about the with Python statement? or is this somehow something Kivy implements?
I don't know Kivy, but I think I can guess how this specific construction work.
Instead of keeping a handle to the object you are interacting with (the canvas?), the with statement is programmed to store it in some global variable, hidden to you. Then, the statements you use inside with use that global variable to retrieve the object. At the end of the block, the global variable is cleared as part of cleanup.
The result is a trade-off: code is less explicit (which is usually a desired feature in Python). However, the code is shorter, which might lead to easier understanding (with the assumption that the reader knows how Kivy works). This is actually one of the techniques of making embedded DSLs in Python.
There are some technicalities involved. For example, if you want to be able to nest such constructions (put one with inside another), instead of a simple global variable you would want to use a global variable that keeps a stack of such objects. Also, if you need to deal with threading, you would use a thread-local variable instead of a global one. But the generic mechanism is still the same—Kivy uses some state which is kept in a place outside your direct control.
There is nothing extra magical with the with statement, but perhaps you are unaware of how it works?
In order for any object to be used in a with statement it must implement two methods: __enter__ and __exit__. __enter__ is called when the with block is entered, and __exit__ is called when the block is exited for any reason.
What the object does in its __enter__ method is, of course, up to it. Since I don't have the Kivy code I can only guess that its canvas.__enter__ method sets a global variable somewhere, and that Rectangle checks that global to see where it should be drawing.

Categories