404
-Page not found
- -Lorem markdownum magnae prosternite omnes alveus vimine transcribere timuere -penetrale; ambrosia marinas abruptaque corpora telum. Non admotum foret; -domo, nova veniam pondere; incipit.
-Toto una miser spondet mutataeque obsedit hederae murmure Penthea gerebat -solebat tradidit! Perque sua caput genis terram vidit: di arces vidit inopes -caelo defendere harundo causa. Rota possit herbis bello peregit auctor rursus -habebimus nubibus maxima. Et et dicere, cultor, tamen arva Periclymeni -caelum saepe sunt emicat vidit.
-Esse patior virga sit feruntur arva palustres prohibebar -vultusque audiri turbantur visum, gelidos? -Luctus et fabricata esse temptant molliri admonitorque dare currunt, -dedit? Amoris mihi properabat petit, -salve supremo haec rumoribus fine. Esse et futuri oculos duos Pandion?
---Quis Vidi: ferox sub incenduntque Lycopen estque pennae iactat! Hanc corpus -neve Hecate Herculeis vacuum! Res illa fortunata iuvencae summa!
-
Venilia oscula; ora felicior metus hospita. Visendae -molitur. Iuvat non umerique -nostraque accipitris Somnia retentis ceciderunt adero mutatus? Est deum occiduo -odoro adnuit et omnibus ponunt, natalibus tecta, amanti. Ipse in perdere -Cyllenide opibus Aiaci calculus est exegi, in ergo altis monitis ore -quattuor enim.
-Timore et genitor virum Apolline relicta e in nemus erant, ulla hunc pro, -quaeque caducifer supra et. Amicas tigno toris: incustoditae mora est, -requiritur nostra. Pronusque caret tegumenque Iovis, Tartara hos viri ignis, -aconiton praebuit Pithecusas sumo. Omne illo; contigit de quod est cara -suo, Ceres spatio et vetus haeserat, de.
-volume_rootkit_tag += pcb_bar(packet_wildcard, document);
-if (token_dos / repeater * opacity_bar /
- ddrProgressiveStreaming.clipboardTimeInternal(dllCameraCable)) {
- peripheral_index += 1;
-}
-newbie += favorites_integrated - operatingDacProcess + 4 +
- hypermedia_link_output + fiosGnuCut;
-data(tweetFormatData.sync_software(packetDirectDrive, duplex.openglDrive(
- cable, compression_clean, 3), chip_trojan(1, type,
- minisite_printer)), -1, dvi_leaf * maximizeDriveCaps);
-
-Achivam undas filum parte sustulit, tellure aderam Mavortis carens! Pro in si -illa amor neget iurasse morsus. Temeraria potuit. Nec stipite, terris sed invito -est nimia nam, in sis tum naufragus ipse vota gramina auferat dixit: dies. -Sit ulciscitur navis, navita duplex voveas, tui potest versa, aequora ut -numine fidelius pudet.
Context managers (PEP 343) are pretty important in Python. You probably use one every time you open a file:
+with open('cake.txt') as c: + gobble_gobble(c) +
But how well do you understand what’s going on behind the scenes?
+It’s actually quite simple. A context manager is a class that implements an __enter__ and an __exit__ method.
Let’s imagine you want to you print a line of text to the console surrounded with asterisks. Here’s a context manager to do it:
+class asterisks(): + def __enter__(self): + print('*' * 32) + + def __exit__(self, exc_type, exc_val, exc_tb): + print('*' * 32) +
The __exit__ method takes three arguments apart from self. Those arguments contain information about any errors that occurred inside the with block.
You can use asterisks in the same way as any of the built-in context managers:
>>> with asterisks(): +>>> print("Context Managers Rock!") +******************************** +Context Managers Rock! +******************************** +
If you need to get something back and use it inside the with block – such as a file descriptor – you simply return it from __enter__:
class myopen(): + def __init__(self, filename, filemode): + self.filename = filename + self.filemode = filemode + + def __enter__(self): + self.file = open(self.filename, self.filemode) + return self.file + + def __exit__(self, exc_type, exc_val, exc_tb): + self.file.close() +
myopen works identically to the built-in open:
with myopen("beer.txt") as b: + guzzle_guzzle(b) +
Thankfully, you don’t have to implement a class every time. The contextlib package has a contextmanager decorator that you can apply to generators to automatically transform them into context managers:
from contextlib import contextmanager + +@contextmanager +def spoiler(): + print('<spoiler>') + yield + print('</spoiler>') +
The code before yield corresponds to __enter__ and the code after yield corresponds to __exit__. A context manager generator should have exactly one yield in it.
It works the same as the class version:
+>>> with spoiler(): +>>> print("Jon Snow is Luke's father.") +<spoiler> +Jon Snow is Luke's father. +</spoiler> +
The implementation in contextlib is complicated, but it’s not hard to write something that works similarly with the exception of a few edge cases:
def contextmanager(gen): + class CMWrapper(object): + def __init__(self, wrapped): + self.generator = wrapped + + def __enter__(self): + return next(self.generator) + + def __exit__(self, ex_type, value, traceback): + try: + next(self.generator) + except StopIteration: + pass + + def inner(*args, **kwargs): + return CMWrapper(gen(*args, **kwargs)) + + return inner +
It’s not as robust as the real implementation, but it should be understandable. Here are the key points:
+- The inner function instantiates a copy of the nested CMWrapper class with a handle on the generator passed into the decorator.
+- __enter__ calls next() on the generator and returns the yielded value so it can be used in the with block.
+- __exit__ calls next() again and catches the StopIteration exception that the generator throws when it finishes.
That’s it for now. If you want to learn more about context managers, I recommend you take a look at the code for contextlib.
++Source:
+
+ https://www.smallsurething.com/how-exactly-do-context-managers-work/
++ + + + + + + +https://rszalski.github.io/magicmethods/
+
This quick tip gives a brief overview of what we mean by a metaclass in Python and shows some examples of the concept.
+Before delving into this article, I should point out an important point about classes in Python which makes it easier for us to grasp the concept of metaclasses.
+If you've used a programming language other than Python, the concept you understood about classes is most likely that it is a way used to create new objects. This is also true in Python, but Python even takes it one more step further—classes are also considered objects!
+So, if you created the following class in Python:
+class myClass(object): + pass +
This simply means that an object with the name myClass has been created in memory. Since this object is able to create new objects, it is considered a class. This means we can apply object operations on classes in Python, as classes are objects themselves.
+We can thus do operations on classes like assigning the class to a variable, as follows:
+class_object = myClass() +print class_object +
Which returns:
+<__main__.myClass object at 0x102623610> +
You can even pass the class myClass as a parameter to a method, as follows:
def class_object(object): + print object + +class_object(myClass) +
Which returns the following output:
+<class '__main__.myClass'> +
In addition to other operations you can normally apply on objects.
+Maybe you have come across the type keyword in Python? You most likely used it to check the type of some object, as shown in the following examples:
print type('abder') +print type(100) +print type(100.0) +print type(int) +
In which case you would get the following output:
+<type 'str'> +<type 'int'> +<type 'float'> +<type 'type'> +
Looking at the output, everything seems pretty clear until you come to the type type. To see what this might mean, let's go back to our class we defined at the beginning of this article:
+class myClass(object): + pass +
Now, do the following:
+print type(myClass) +
What would be the output of this statement? It will surprisingly be:
+<type 'type'> +
So, we can conclude that the type of classes in Python is type!
What is the relation between a type and a metaclass? Well, a type is a metaclass, provided that the default metaclass is type. I know this might be confusing, especially that type can be used to return the class of some object as shown above, but this is due to the backward compatibility in Python. So, if you write:
print type(type) +
You will get:
+<type 'type'> +
Meaning that a type is a type!
The term metaclass simply means something used to create classes. In other words, it is the class of a class, meaning that the instance of a class in this case is a class. Thus, type is considered a metaclass since the instance of a type is a class.
For instance, when we mentioned the following statement above:
+class_object = myClass() +
This simply builds an object/instance of the class myClass. In other words, we used a class to create an object.
In the same way, when we did the following:
+class myClass(object): + pass +
The metaclass was used to create the class myClass (which is considered a type). So, like the object being an instance of a class, a class is an instance of a metaclass.
In this section, we are going to see how we can use a metaclass to create a class, rather than using the class statement as we saw in the classes and objects tutorial. As we saw above, the default metaclass is type. Thus, we can use the following statement to create a new class:
new_class = type('myClass',(),{}) +
If you want to make things simpler, you can assign the same class name myClass to the variable name.
+The dictionary { } here is used to define the attributes of the class. So, having the following statement:
myClass = type('myClass',(),{'a':True}) +
Is similar to:
+class myClass(object): + a = True +
Say that we created the class myClass as follows:
class myClass(object): + __metaclass__ = myMetaClass + pass +
In this case, class creation will occur using myMetaClass instead of type, as follows:
+myClass = myMetaClass(className, bases, dictionary) +
If you want to have control on how you create and initialize a class after its creation, you can simply use the metaclass new method and init constructor, respectively. So, when myMetaClass above is called, this is what will be happening behind the scenes:
+myClass = myMetaClass.__new__(myMetaClass, name, bases, dictionary) +myMetaClass.__init__(myClass, name, bases, dictionary) +
++Source:
+
+ https://code.tutsplus.com/tutorials/quick-tip-what-is-a-metaclass-in-python--cms-26016
A high level explanation is necessary before we get down to the details.
+A class is an object, and just like any other object, it's an instance of something: a metaclass. The default metaclass is type. Unfortunately, due to backwards compatibility, type is a bit confusing: it can also be used as a function that return the class [13] of an object:
+>>> class Foobar: +... pass +... +>>> type(Foobar) +<class 'type'> +>>> foo = Foobar() +>>> type(foo) +<class '__main__.Foobar'> +
If you're familiar with the isinstance builtin then you'll know this:
+>>> isinstance(foo, Foobar) +True +>>> isinstance(Foobar, type) +True +
To put this in picture:
+
But lets go back to making classes ...
+We can use type directly to make a class, without any class statement:
+>>> MyClass = type('MyClass', (), {}) +>>> MyClass +<class '__main__.MyClass'> +
The class statement isn't just syntactic sugar, it does some extra things, like setting an adequate qualname and doc properties or calling prepare.
+We can make a custom metaclass:
+>>> class Meta(type): +... pass +
And then we can use it :
+>>> class Complex(metaclass=Meta): +... pass +>>> type(Complex) +<class '__main__.Meta'> +
Now we got a rough idea of what we'll be dealing with ...
+One distinctive feature of Python is magic methods: they allow the programmer to override behavior for various operators and behavior of objects. To override the call operator you'd do this:
+>>> class Funky: +... def __call__(self): +... print("Look at me, I work like a function!") +>>> f = Funky() +>>> f() +Look at me, I work like a function! +
Metaclasses rely on several magic methods so it's quite useful to know a bit more about them.
+When you define a magic method in your class the function will end up as a pointer in a struct that describes the class, in addition to the entry in dict. That struct [7] has a field for each magic method. For some reason these fields are called type slots.
+Now there's another feature, implemented via the slots attribute. A class with slots will create instances that don't have a dict (they use a little bit less memory). A side-effect of this is that instances cannot have other fields than what was specified in slots: if you try to set an unexpected field you'll get an exception.
+For the scope of this article when slots are mentioned it will mean the type slots, not slots.
+Now this is something that's easy to get wrong because of the many slight differences to old-style objects in Python 2.
+Assuming Class is the class and instance is an instance of Class, evaluating instance.foobar roughly equates to this:
+Still not clear? Perhaps a diagram normal attribute lookup helps:
+
++To avoid creating confusions with the “.” operator doing crazy things I've used “:” in this diagram to signify the location.
+
Because classes needs to be able support the classmethod and staticmethod properties [6] when you evaluate something like Class.foobar the lookup is slightly different than what would happen when you evaluate instance.foobar.
+Assuming Class is an instance of Metaclass, evaluating Class.foobar roughly equates to this:
+The whole shebang would look like this in a diagram:
+
++To avoid creating confusions with the “.” operator doing crazy things I've used “:” in this diagram to signify the location.
+
For magic methods the lookup is done on the class, directly in the big struct with the slots:
+++In C internals parlance: + - object->ob_type is the class of the object.
+
+ - ob_type->tp_is the type slot.
This looks much simpler, however, the type slots are filled with wrappers around your functions, so descriptors work as expected:
+>>> class Magic: +... @property +... def __repr__(self): +... def inner(): +... return "It works!" +... return inner +... +>>> repr(Magic()) +'It works!' +
Thats it. Does that mean there are places that don't follow those rules and lookup the slot differently? Sadly yes, read on ...
+One of the most common point of confusion with both classes and metaclasses is the new method. It has some very special conventions.
+The new method is the constructor (it returns the new instance) while init is just a initializer (the instance is already created when init is called).
+Suppose have a class like this:
+class Foobar: + def __new__(cls): + return super().__new__(cls) +
Now if you recall the previous section, you'd expect that __new__ would be looked up on the metaclass, but alas, it wouldn't be so useful that way so it's looked up statically.
+When the Foobar class wants this magic method it will be looked up on the same object (the class), not on a upper level like all the other magic methods. This is very important to understand, because both the class and the metaclass can define this method:
+This method is called before the class body is executed and it must return a dictionary-like object that's used as the local namespace for all the code from the class body. It was added in Python 3.0, see PEP-3115.
+If your __prepare__ returns an object x then this:
+class Class(metaclass=Meta): + a = 1 + b = 2 + c = 3 +
Will make the following changes to x:
+x['a'] = 1 +x['b'] = 2 +x['c'] = 3 +
This x object needs to look like a dictionary. Note that this x object will end up as an argument to Metaclass.__new and if it's not an instance of dict you need to convert it before calling super().__new.
+Interestingly enough this method doesn't have __new__'s special lookup. It appears it doesn't have it's own type slot and it's looked up via the class attribute lookup, if you read back a bit.
+To start things off, a diagram of how instances are constructed:
+
How to read this swim lane diagram:
+Creating a class is quite similar:
+
Few more notes: +- Metaclass.prepare just returns the namespace object (a dictionary-like object as explained before). +- Metaclass.new returns the Class object. +- MetaMetaclass.call returns whatever Metaclass.new returned (and if it returned an instance of Metaclass it will also call Metaclass.init on it).
+So you see, metaclasses allow you to customize almost every part of an object life-cycle.
+If you look again at the diagrams, you'll notice that making an instance goes through Metaclass.call. This means you can use any callable as the metaclass:
+>>> class Foo(metaclass=print): # pointless, but illustrative +... pass +... +Foo () {'__module__': '__main__', '__qualname__': 'Foo'} +>>> print(Foo) +None +
If you use a function as the metaclass then subclasses won't inherit your function metaclass, but the type of whatever that function returned.
+One advantage compared to class decorators is the fact that subclasses inherit the metaclass.
+This is a consequence of the fact that Metaclass(...) returns an object which usually has Metaclass as the class.
+In the same tone of classes allowing you to have multiple baseclasses, each one of those baseclasses may have a different metaclass. But with a twist: everything has to be linear - the inheritance tree must have a single leaf.
+For example, this is not accepted because there would be two leafs (Meta1 and Meta2):
+>>> class Meta1(type): +... pass +... +>>> class Meta2(type): +... pass +... +>>> class Base1(metaclass=Meta1): +... pass +... +>>> class Base2(metaclass=Meta2): +... pass +... +>>> class Foobar(Base1, Base2): +... pass +... +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases +
This will work (and will use the leaf as the metaclass):
+>>> class Meta(type): +... pass +... +>>> class SubMeta(Meta): +... pass +... +>>> class Base1(metaclass=Meta): +... pass +... +>>> class Base2(metaclass=SubMeta): +... pass +... +>>> class Foobar(Base1, Base2): +... pass +... +>>> type(Foobar) +<class '__main__.SubMeta'> +
There are still few important details missing, like the method signatures. Lets look at class and metaclass with all the important stuff implemented.
+Note the extra **kwargs - those are the extra keywords arguments you can pass in the class statement.
+>>> class Meta(type): +... @classmethod +... def __prepare__(mcs, name, bases, **kwargs): +... print(' Meta.__prepare__(mcs=%s, name=%r, bases=%s, **%s)' % ( +... mcs, name, bases, kwargs +... )) +... return {} +
As mentioned before, __prepare can return objects that are not dict instances, so you need to make sure your __new handles that.
+... def __new__(mcs, name, bases, attrs, **kwargs): +... print(' Meta.__new__(mcs=%s, name=%r, bases=%s, attrs=[%s], **%s)' % ( +... mcs, name, bases, ', '.join(attrs), kwargs +... )) +... return super().__new__(mcs, name, bases, attrs) +
It's uncommon to see init being implemented in a metaclass because it's not that powerful - the class is already constructed when init is called. It roughly equates to having a class decorator with the difference that init would get run when making subclasses, while class decorators are not called for subclasses.
+... def __init__(cls, name, bases, attrs, **kwargs): +... print(' Meta.__init__(cls=%s, name=%r, bases=%s, attrs=[%s], **%s)' % ( +... cls, name, bases, ', '.join(attrs), kwargs +... )) +... return super().__init__(name, bases, attrs) +
The __call__ method will be called when you make instances of Class.
+... def __call__(cls, *args, **kwargs): +... print(' Meta.__call__(cls=%s, args=%s, kwargs=%s)' % ( +... cls, args, kwargs +... )) +... return super().__call__(*args, **kwargs) +... +
Using Meta, note the extra=1:
+>>> class Class(metaclass=Meta, extra=1): +... def __new__(cls, myarg): +... print(' Class.__new__(cls=%s, myarg=%s)' % ( +... cls, myarg +... )) +... return super().__new__(cls) +... +... def __init__(self, myarg): +... print(' Class.__init__(self=%s, myarg=%s)' % ( +... self, myarg +... )) +... self.myarg = myarg +... return super().__init__() +... +... def __str__(self): +... return "<instance of Class; myargs=%s>" % ( +... getattr(self, 'myarg', 'MISSING'), +... ) + Meta.__prepare__(mcs=<class '__main__.Meta'>, name='Class', bases=(), + **{'extra': 1}) + Meta.__new__(mcs=<class '__main__.Meta'>, name='Class', bases=(), + attrs=[__qualname__, __new__, __init__, __str__, __module__], + **{'extra': 1}) + Meta.__init__(cls=<class '__main__.Class'>, name='Class', bases=(), + attrs=[__qualname__, __new__, __init__, __str__, __module__], + **{'extra': 1}) +
Note that Meta.__call__ is called when we make instance of Class:
+>>> Class(1) + Meta.__call__(cls=<class '__main__.Class'>, args=(1,), kwargs={}) + Class.__new__(cls=<class '__main__.Class'>, myarg=1) + Class.__init__(self=<instance of Class; myargs=MISSING>, myarg=1) +<instance of Class; myargs=1> +
++ + + + + + + +Source:
+
+ https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
In order to write useful programs, we almost always need the ability to check conditions +and change the behavior of the program accordingly. Conditional statements give us this +ability. The simplest form is the if statement:
+if x > 0: + print 'x is positive' +
The boolean expression after if is called the condition. If it is true, then the indented +statement gets executed. If not, nothing happens. +if statements have the same structure as function definitions: a header followed by an +indented body. Statements like this are called compound statements. +There is no limit on the number of statements that can appear in the body, but there has +to be at least one. Occasionally, it is useful to have a body with no statements (usually +as a place keeper for code you haven’t written yet). In that case, you can use the pass +statement, which does nothing.
+if x < 0: + pass # need to handle negative values! +
A second form of the if statement is alternative execution, in which there are two +possibilities and the condition determines which one gets executed. The syntax looks +like this:
+if x%2 == 0: + print 'x is even' +else: + print 'x is odd' +
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program +displays a message to that effect. If the condition is false, the second set of statements is +executed. Since the condition must be true or false, exactly one of the alternatives will +be executed. The alternatives are called branches, because they are branches in the flow +of execution.
+Sometimes there are more than two possibilities and we need more than two branches. +One way to express a computation like that is a chained conditional:
+if x < y: + print 'x is less than y' +elif x > y: + print 'x is greater than y' +else: + print 'x and y are equal' +
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is +no limit on the number of elif statements. If there is an else clause, it has to be at the +end, but there doesn’t have to be one.
+if choice == 'a': + draw_a() +elif choice == 'b': + draw_b() +elif choice == 'c': + draw_c() +
Each condition is checked in order. If the first is false, the next is checked, and so on. If +one of them is true, the corresponding branch executes, and the statement ends. Even +if more than one condition is true, only the first true branch executes.
+One conditional can also be nested within another. We could have written the tri +chotomy example like this:
+if x == y: + print 'x and y are equal' +else: + if x < y: + print 'x is less than y' + else: + print 'x is greater than y' +
The outer conditional contains two branches. The first branch contains a simple state
+ment. The second branch contains another if statement, which has two branches of its
+own. Those two branches are both simple statements, although they could have been
+conditional statements as well.
+Although the indentation of the statements makes the structure apparent, nested
+conditionals become difficult to read very quickly. In general, it is a good idea to avoid
+them when you can.
+Logical operators often provide a way to simplify nested conditional statements. For
+example, we can rewrite the following code using a single conditional:
if 0 < x: + if x < 10: + print 'x is a positive single-digit number.' +
The print statement is executed only if we make it past both conditionals, so we can +get the same effect with the and operator:
+if 0 < x and x < 10: + print 'x is a positive single-digit number.' +
++Source:
+
+ Think Python by Allen B. Downey - 2012
The if-else statement is a staple of most programming languages. It is used to test different conditions and execute code accordingly. You can think of it as a ‘map’ used to make decisions in the program.
+The basic syntax is as follows:
+if condition1 = True: + execute code1 +else: + execute code2 +
In plain English, this can be described as follows:
+If condition1 is true, then execute the code included in code1. If it is not true, then run code2
A few things to note about the syntax: +- Each if/else statement must close with a colon (:) +- Code to be executed as part of any if/else statement must be indented by four spaces, equivalent to one press of the Tab key. +- Although not explicitly required, every if statement must also include an else statement – it just makes for a better program.
+You use if-else statements a lot in your every day. Virtually every decision you make involves some form of if-else statements. “If the bacon is cheap, I’ll buy a pound. If not, I’ll grab some mac and cheese”, “if I wake up before 6, I’ll head out for a jog. Otherwise, I’ll head straight to work”, and “if the traffic is light, we’ll make the movie theater in time. Else, we’ll just have to grab dinner and go back home” – these are some simple if-else decisions we’ve all made in our everyday life. Thus, by using if-else statements in Python, you give the program the ability to make decisions depending on the user input.
+But enough talk; let’s try to understand if-else statements with an example:
+x = 5 +if x > 5: + print "X is larger than five!" +else: + print "X is smaller than or equal to five!" +
this program basically instructs Python to: +- Check the value of x. +- If the value of x is more than 5, print that “X is larger than five”. +- If the value of x is less than or equal to 5, print “X is smaller than or equal to five”.
+As we’ll learn below, the decision making capabilities of if-else conditions will come very handy when you want to create complicated programs.
+The above if-else syntax is great if you want to test just one condition, but what happens when you want to check multiple conditions?
+This is where the Elif statement comes in handy.
+Elif is a shortened form of Else-If. The syntax can be seen as follows:
if condition1 = True: + execute code1 +elif condition2 = True: + execute code2 +else: + execute code3 +
In plain English, you can read this as follows:
+If condition1 is true, execute code1. Else, if condition2 is true, execute code2. If neither condition1 or condition2 are true, execute code3.
There is no limit to the number of elif statements you can include in a Python program. You can test dozens of conditions using multiple elif statements as long as you close with an else statement.
+Let’s try to understand this with an example:
x = 5 +if x == 5: + print "Wow, X is EXACTLY five!" +elif x > 5: + print "X is now MORE than five!" +else: + print "X is now LESS than five!" +
So what exactly is happening here? Let’s break it down into individual steps:
+As mentioned above, an if-else conditional block can include as many elif statements as you want.
+So far, we’ve used just a single level of if-else statements. But what if you want to make decisions within decisions? That’s like saying: “if the oranges are fresh, buy a dozen if they are more than $5/lb, and two dozen if they are less than $5/lb”
+In programmer-speak (i.e. algorithmically) this can be written as follows:
+orange_quality = “fresh” +orange_price = 4.0 +if orange_quality == “fresh”: + if orange_price < 5: + buy 24.0 + else: + buy 12.0 +else: + don’t_buy_oranges +
This is an example of a nested if-else statement – an if-else statement inside another if-else statement. These can help you make more complex decisions and give you even finer control over the program flow. In terms of syntax, they can be written as follows:
+if condition1 = True: + if condition2 = True: + execute code1 + elif condition3 = True: + execute code2 + else: + execute code3 +else: + execute code4 +
Thus, the syntax rules are the same as a standard if-statement – i.e. nested statements must be tabbed in. Theoretically, you can nest as many if-else statements as you want, but it is poor practice to go more than two levels deep.
+++Source:
+
+ https://blog.udemy.com/python-if-else/
Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.
+When we fully execute each statement of a program, moving from the top to the bottom with each line executed in order, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.
+Let’s look at some examples where we would use conditional statements:
+Through evaluating conditions and assigning code to run based on whether or not those conditions are met, we are writing conditional code.
+This tutorial will take you through writing conditional statements in the Python programming language.
+We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.
+In a plain text editor, open a file and write the following code:
+grade = 70 + +if grade >= 65: + print("Passing grade") +
With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65. If it does meet this condition, we are telling the program to print out the string Passing grade.
+In this case, the grade of 70 does meet the condition of being greater than or equal to 65, so you will receive the following output once you run the program:
+Output +Passing grade +
Let’s now change the result of this program by changing the value of the grade variable to 60:
+grade = 60 + +if grade >= 65: + print("Passing grade") +
When we save and run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.
+To give one more example, let us calculate whether a bank account balance is below 0. Let’s create a file called account.py and write the following program:
balance = -5 + +if balance < 0: + print("Balance is below 0, add funds now or you will be charged a penalty.") +
When we run the program with python account.py, we’ll receive the following output:
+Output +Balance is below 0, add funds now or you will be charged a penalty. +
In the program we initialized the variable balance with the value of -5, which is less than 0. Since the balance met the condition of the if statement (balance < 0), once we save and run the code, we will receive the string output. Again, if we change the balance to 0 or a positive number, we will receive no output.
It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example, we will want output whether the grade is passing or failing.
To do this, we will add an else statement to the grade condition above that is constructed like this:
+grade = 60 + +if grade >= 65: + print("Passing grade") + +else: + print("Failing grade") +
Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do something anyway.
+When we save and run the program, we’ll receive the following output:
+Output +Failing grade +
If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade.
To add an else statement to the bank account example, we rewrite the code like this:
+balance = 522 + +if balance < 0: + print("Balance is below 0, add funds now or you will be charged a penalty.") + +else: + print("Your balance is 0 or above.") +
Here, we changed the balance variable value to a positive number so that the else statement will print. To get the first if statement to print, we can rewrite the value to a negative number.
+By combining an if statement with an else statement, you are constructing a two-part conditional statement that will tell the computer to execute certain code whether or not the if condition is met.
+So far, we have presented a Boolean option for conditional statements, with each if statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Python as elif. The elif or else if statement looks like the if statement and will evaluate another condition.
+In the bank account program, we may want to have three discrete outputs for three different situations:
+The elif statement will be placed between the if statement and the else statement as follows:
. . . +if balance < 0: + print("Balance is below 0, add funds now or you will be charged a penalty.") + +elif balance == 0: + print("Balance is equal to 0, add funds soon.") + +else: + print("Your balance is 0 or above.") +
Now, there are three possible outputs that can occur once we run the program: +- If the variable balance is equal to 0 we will receive the output from the elif statement (Balance is equal to 0, add funds soon.) +- If the variable balance is set to a positive number, we will receive the output from the else statement (Your balance is 0 or above.). +- If the variable balance is set to a negative number, the output will be the string from the if statement (Balance is below 0, add funds now or you will be charged a penalty).
+What if we want to have more than three possibilities, though? We can do this by writing more than one elif statement into our code.
+In the grade.py program, let’s rewrite the code so that there are a few letter grades corresponding to ranges of numerical grades:
To run this code, we will need one if statement, three elif statements, and an else statement that will handle all failing cases.
Let’s rewrite the code from the example above to have strings that print out each of the letter grades. We can keep our else statement the same.
+. . . +if grade >= 90: + print("A grade") + +elif grade >=80: + print("B grade") + +elif grade >=70: + print("C grade") + +elif grade >= 65: + print("D grade") + +else: + print("Failing grade") +
Since elif statements will evaluate in order, we can keep our statements pretty basic. This program is completing the following steps:
+Once you are feeling comfortable with the if, elif, and else statements, you can move on to nested conditional statements. We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:
+if statement1: #outer if statement + print("true") + + if nested_statement: #nested if statement + print("yes") + + else: #nested else statement + print("no") + +else: #outer else statement + print("false") +
A few possible outputs can result from this code:
+- If statement1 evaluates to true, the program will then evaluate whether the nested_statement also evaluates to true. If both cases are true, the output will be:
Output +true +yes +
Output +true +no +
Output +false +
We can also have multiple if statements nested throughout our code:
+if statement1: #outer if + print("hello world") + + if nested_statement1: #first nested if + print("yes") + + elif nested_statement2: #first nested elif + print("maybe") + + else: #first nested else + print("no") + +elif statement2: #outer elif + print("hello galaxy") + + if nested_statement3: #second nested if + print("yes") + + elif nested_statement4: #second nested elif + print("maybe") + + else: #second nested else + print("no") + +else: #outer else + statement("hello universe") +
In the above code, there is a nested if statement inside each if statement in addition to the elif statement. This will allow for more options within each condition.
+Let’s look at an example of nested if statements with our grade.py program. We can check for whether a grade is passing first (greater than or equal to 65%), then evaluate which letter grade the numerical grade should be equivalent to. If the grade is not passing, though, we do not need to run through the letter grades, and instead can have the program report that the grade is failing. Our modified code with the nested if statement will look like this:
+. . . +if grade >= 65: + print("Passing grade of:") + + if grade >= 90: + print("A") + + elif grade >=80: + print("B") + + elif grade >=70: + print("C") + + elif grade >= 65: + print("D") + +else: + print("Failing grade") +
If we run the code with the variable grade set to the integer value 92, the first condition is met, and the program will print out Passing grade of:. Next, it will check to see if the grade is greater than or equal to 90, and since this condition is also met, it will print out A.
+If we run the code with the grade variable set to 60, then the first condition is not met, so the program will skip the nested if statements and move down to the else statement, with the program printing out Failing grade.
We can of course add even more options to this, and use a second layer of nested if statements. Perhaps we will want to evaluate for grades of A+, A and A- separately. We can do so by first checking if the grade is passing, then checkingto see if the grade is 90 or above, then checkingto see if the grade is over 96 for an A+ for instance:
+. . . +if grade >= 65: + print("Passing grade of:") + + if grade >= 90: + if grade > 96: + print("A+") + + elif grade > 93 and grade <= 96: + print("A") + + elif grade >= 90: + print("A-") +. . . +
In the code above, for a grade variable set to 96, the program will run the following:
+The output of the program for a grade of 96 therefore looks like this:
+Output +Passing grade of: +A +
Nested if statements can provide the opportunity to add several specific levels of conditions to your code.
+By using conditional statements like the if statement, you will have greater control over what your program executes. Conditional statements tell the program to evaluate whether a certain condition is being met. If the condition is met it will execute specific code, but if it is not met the program will continue to move down to other code.
+++ + + + + + + +Source:
+
+ https://www.digitalocean.com/community/tutorials/how-to-write-conditional-statements-in-python-3-2
In Python, like in all programming languages, data types are used to classify one particular type of data. This is important because the specific data type you use will determine what values you can assign to it and what you can do to it (including what operations you can perform on it).
+In this tutorial, we will go over the important data types native to Python. This is not an exhaustive investigation of data types, but will help you become familiar with what options you have available to you in Python.
+One way to think about data types is to consider the different types of data that we use in the real world. An example of data in the real world are numbers: we may use whole numbers (0, 1, 2, …), integers (…, -1, 0, 1, …), and irrational numbers (π), for example.
+Usually, in math, we can combine numbers from different types, and get some kind of an answer. We may want to add 5 to π, for example:
+5 + π
We can either keep the equation as the answer to account for the irrational number, or round π to a number with a brief number of decimal places, and then add the numbers together:
+5 + π = 5 + 3.14 = 8.14
But, if we start to try to evaluate numbers with another data type, such as words, things start to make less sense. How would we solve for the following equation?
+sky + 8
For computers, each data type can be thought of as being quite different, like words and numbers, so we will have to be careful about how we use them to assign values and how we manipulate them through operations.
+Any number you enter in Python will be interpreted as a number; you are not required to declare what kind of data type you are entering. Python will consider any number written without decimals as an integer (as in 138) and any number written with decimals as a float (as in 138.0).
Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …). An integer can also be known as an int. As with other programming languages, you should not use commas in numbers of four digits or more, so when you write 1,000 in your program, write it as 1000.
We can print out an integer in a simple way like this:
+print(-25) + +#Output : -25 +
Or, we can declare a variable, which in this case is essentially a symbol of the number we are using or manipulating, like so:
+my_int = -25 +print(my_int) + +#Output : -25 +
We can do math with integers in Python, too:
+int_ans = 116 - 68 +print(int_ans) + +#Output : 48 +
Integers can be used in many ways within Python programs, and as you continue to learn more about the language you will have a lot of opportunities to work with integers and understand more about this data type.
+A floating-point number or a float is a real number, meaning that it can be either a rational or an irrational number. Because of this, floating-point numbers can be numbers that can contain a fractional part, such as 9.0 or -116.42. Simply speaking, for the purposes of thinking of a float in a Python program, it is a number that contains a decimal point.
Like we did with the integer, we can print out a floating-point number in a simple way like this:
+print(17.3) + +#Output : 17.3 +
We can also declare a variable that stands in for a float, like so:
+my_flt = 17.3 +print(my_flt) + +#Output : 17.3 +
And, just like with integers, we can do math with floats in Python, too:
+flt_ans = 564.0 + 365.24 +print(flt_ans) + +#Output : 929.24 +
With integers and floating-point numbers, it is important to keep in mind that 3 ≠ 3.0, as 3 refers to an integer while 3.0 refers to a float.
The Boolean data type can be one of two values, either True or False. Booleans are used to represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science.
+Whenever you see the data type Boolean, it will start with a capitalized B because it is named for the mathematician George Boole. The values True and False will also always be with a capital T and F respectively, as they are special values in Python.
Many operations in math give us answers that evaluate to either True or False:
+* **greater than** + * 500 > 100 `True` + * 1 > 5 `False` +* **less than** + * 200 < 400 `True` + * 4 < 2 `False` +* **equal** + * 5 = 5 `True` + * 500 = 400 `False` +
Like with numbers, we can store a Boolean value in a variable:
+my_bool = 5 > 8 +
We can then print the Boolean value with a call to the print() function:
print(my_bool) +
Since 5 is not greater than 8, we will receive the following #Output : :
+#Output : False
+As you write more programs in Python, you will become more familiar with how Booleans work and how different functions and operations evaluating to either True or False can change the course of the program.
+A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Strings exist within either single quotes ' or double quotes " in Python, so to create a string, enclose a sequence of characters in quotes:
'This is a string in single quotes.' + +"This is a string in double quotes." +
You can choose to use either single quotes or double quotes, but whichever you decide on you should be consistent within a program.
+The simple program “Hello, World!” demonstrates how a string can be used in computer programming, as the characters that make up the phrase Hello, World! are a string.
print("Hello, World!") +
As with other data types, we can store strings in variables:
+hw = "Hello, World!" +
And print out the string by calling the variable:
+print(hw) + +#Ouput : Hello, World! +
Like numbers, there are many operations that we can perform on strings within our programs in order to manipulate them to achieve the results we are seeking. Strings are important for communicating information to the user, and for the user to communicate information back to the program.
+A list is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].
A list of integers looks like this:
+[-3, -2, -1, 0, 1, 2, 3] +
A list of floats looks like this:
+[3.14, 9.23, 111.11, 312.12, 1.05] +
A list of strings:
+['shark', 'cuttlefish', 'squid', 'mantis shrimp'] +
If we define our string list as sea_creatures:
sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp'] +
We can print them out by calling the variable:
+print(sea_creatures) +
And we see that the #Output : looks exactly like the list that we created:
+#Output : ['shark', 'cuttlefish', 'squid', 'mantis shrimp']
+Lists are a very flexible data type because they are mutable in that they can have values added, removed, and changed. There is a data type that is similar to lists but that can’t be changed, and that is called a tuple.
+A tuple is used for grouping data. It is an immutable, or unchangeable, ordered sequence of elements.
+Tuples are very similar to lists, but they use parentheses ( ) instead of square brackets and because they are immutable their values cannot be modified.
A tuple looks like this:
+('blue coral', 'staghorn coral', 'pillar coral') +
We can store a tuple in a variable and print it out:
+coral = ('blue coral', 'staghorn coral', 'pillar coral') +print(coral) + +Ouput('blue coral', 'staghorn coral', 'pillar coral') +
Like in the other data types, Python prints out the tuple just as we had typed it, with parentheses containing a sequence of values.
+The dictionary is Python’s built-in mapping type. This means that dictionaries map keys to values and these key-value pairs are a useful way to store data in Python. A dictionary is constructed with curly braces on either side { }.
Typically used to hold data that are related, such as the information contained in an ID, a dictionary looks like this:
+{'name': 'Sammy', 'animal': 'shark', 'color': 'blue', 'location': 'ocean'} +
You will notice that in addition to the curly braces, there are also colons throughout the dictionary. The words to the left of the colons are the keys. Keys can be made up of any immutable data type. The keys in the dictionary above are: 'name', 'animal', 'color', 'location'.
The words to the right of the colons are the values. Values can be comprised of any data type. The values in the dictionary above are: 'Sammy', 'shark', 'blue', 'ocean'.
Like the other data types, let’s store the dictionary inside a variable, and print it out:
+sammy = {'name': 'Sammy', 'animal': 'shark', 'color': 'blue', 'location': 'ocean'} +#Ouput : {'color': 'blue', 'animal': 'shark', 'name': 'Sammy', 'location': 'ocean'} +
If we want to isolate Sammy’s color, we can do so by calling sammy['color']. Let’s print that out:
print(sammy['color']) + +#Output : blue +
As dictionaries offer key-value pairs for storing data, they can be important elements in your Python program.
+At this point, you should have a better understanding of some of the major data types that are available for you to use in Python. Each of these data types will become important as you develop programming projects in the Python language.
+You can learn about each of the data types above in more detail by reading the following specific tutorials:
+ +Once you have a solid grasp of data types available to you in Python, you can learn how to convert data types.
+++Source:
+
+ https://www.digitalocean.com/community/tutorials/understanding-data-types-in-python-3
++Source:
+
+ Dive into Python 3 by Mark Pilgrim
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.
+Python has five standard data types :
+Numbers
+String
+List
+Tuple
+Dictionary
+Number data types store numeric values. Number objects are created when you assign a value to them. For example −
+var1 = 1 +var2 = 10 +
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
+del var1[,var2[,var3[....,varN]]]] +
You can delete a single object or multiple objects by using the del statement.
+For example −
+del var +del var_a, var_b +
Python supports three different numerical types − +- int (signed integers)
+float (floating point real values)
+complex (complex numbers)
+All integers in Python3 are represented as long integers. Hence, there is no separate number type as long.
+| int | +float | +complex | +
|---|---|---|
| 10 | +0.0 | +3.14j | +
| 100 | +15.20 | +45.j | +
| -786 | +-21.9 | +9.322e-36j | +
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are real numbers and j is the imaginary unit.
+Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 to the end.
+The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −
+#!/usr/bin/python3 + +str = 'Hello World!' + +print (str) # Prints complete string +print (str[0]) # Prints first character of the string +print (str[2:5]) # Prints characters starting from 3rd to 5th +print (str[2:]) # Prints string starting from 3rd character +print (str * 2) # Prints string two times +print (str + "TEST") # Prints concatenated string +
This will produce the following result −
+Hello World! +H +llo +llo World! +Hello World!Hello World! +Hello World!TEST +
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One of the differences between them is that all the items belonging to a list can be of different data type.
+The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
+#!/usr/bin/python3 + +list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] +tinylist = [123, 'john'] + +print (list) # Prints complete list +print (list[0]) # Prints first element of the list +print (list[1:3]) # Prints elements starting from 2nd till 3rd +print (list[2:]) # Prints elements starting from 3rd element +print (tinylist * 2) # Prints list two times +print (list + tinylist) # Prints concatenated lists +
This produces the following result −
+['abcd', 786, 2.23, 'john', 70.200000000000003] +abcd +[786, 2.23] +[2.23, 'john', 70.200000000000003] +[123, 'john', 123, 'john'] +['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john'] +
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.
+The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −
+#!/usr/bin/python3 + +tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) +tinytuple = (123, 'john') + +print (tuple) # Prints complete tuple +print (tuple[0]) # Prints first element of the tuple +print (tuple[1:3]) # Prints elements starting from 2nd till 3rd +print (tuple[2:]) # Prints elements starting from 3rd element +print (tinytuple * 2) # Prints tuple two times +print (tuple + tinytuple) # Prints concatenated tuple +
This produces the following result −
+('abcd', 786, 2.23, 'john', 70.200000000000003) +abcd +(786, 2.23) +(2.23, 'john', 70.200000000000003) +(123, 'john', 123, 'john') +('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john') +
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −
+#!/usr/bin/python3 + +tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) +list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] +tuple[2] = 1000 # Invalid syntax with tuple +list[2] = 1000 # Valid syntax with list +
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
+Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −
+#!/usr/bin/python3 + +dict = {} +dict['one'] = "This is one" +dict[2] = "This is two" + +tinydict = {'name': 'john','code':6734, 'dept': 'sales'} + + +print (dict['one']) # Prints value for 'one' key +print (dict[2]) # Prints value for 2 key +print (tinydict) # Prints complete dictionary +print (tinydict.keys()) # Prints all the keys +print (tinydict.values()) # Prints all the values +
This produces the following result −
+This is one +This is two +{'name': 'john', 'dept': 'sales', 'code': 6734} +dict_keys(['name', 'dept', 'code']) +dict_values(['john', 'sales', 6734]) +
Dictionaries have no concept of order among the elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.
+++ + + + + + + +Source:
+
+ https://www.tutorialspoint.com/python3/python_variable_types.htm
Using loops in computer programming allows us to automate and repeat similar tasks multiple times. In this tutorial, we’ll be covering Python’s for loop.
+A for loop implements the repeated execution of code based on a loop counter or loop variable. This means that for loops are used most often when the number of iterations is known before entering the loop, unlike while loops which are conditionally based.
+In Python, for loops are constructed like so:
+for [iterating variable] in [sequence]: + [do something] +
The something that is being done will be executed until the sequence is over.
+Let’s look at a for loop that iterates through a range of values:
+for i in range(0,5): + print(i) +
When we run this program, the output looks like this:
+Output +0 +1 +2 +3 +4 +
This for loop sets up i as its iterating variable, and the sequence exists in the range of 0 to 5.
+Then within the loop we print out one integer per loop iteration. Keep in mind that in programming we tend to begin at index 0, so that is why although 5 numbers are printed out, they range from 0-4.
+You’ll commonly see and use for loops when a program needs to repeat a block of code a number of times.
+One of Python’s built-in immutable sequence types is range(). In loops, range() is used to control how many times the loop will be repeated.
+When working with range(), you can pass between 1 and 3 integer arguments to it:
We’ll look at some examples of passing different arguments to range().
First, let’s only pass the stop argument, so that our sequence set up is range(stop):
for i in range(6): + print(i) +
In the program above, the stop argument is 6, so the code will iterate from 0-6 (exclusive of 6):
+Output +0 +1 +2 +3 +4 +5 +
Next, we’ll look at range(start, stop), with values passed for when the iteration should start and for when it should stop:
+for i in range(20,25): + print(i) +
Here, the range goes from 20 (inclusive) to 25 (exclusive), so the output looks like this:
+Output +20 +21 +22 +23 +24 +
The step argument of range() is similar to specifying stride while slicing strings in that it can be used to skip values within the sequence.
+With all three arguments, step comes in the final position: range(start, stop, step). First, let’s use a step with a positive value:
+for i in range(0,15,3): + print(i) +
In this case, the for loop is set up so that the numbers from 0 to 15 print out, but at a step of 3, so that only every third number is printed, like so:
+Output +0 +3 +6 +9 +12 +
We can also use a negative value for our step argument to iterate backwards, but we’ll have to adjust our start and stop arguments accordingly:
+for i in range(100,0,-10): + print(i) +
Here, 100 is the start value, 0 is the stop value, and -10 is the range, so the loop begins at 100 and ends at 0, decreasing by 10 with each iteration. We can see this occur in the output:
+Output +100 +90 +80 +70 +60 +50 +40 +30 +20 +10 +
When programming in Python, for loops often make use of the range() sequence type as its parameters for iteration.
Lists and other data sequence types can also be leveraged as iteration parameters in for loops. Rather than iterating through a range(), you can define a list and iterate through that list.
+We’ll assign a list to a variable, and then iterate through the list:
+sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem'] + +for shark in sharks: + print(shark) +
In this case, we are printing out each item in the list. Though we used the variable shark, we could have called the variable any other valid variable name and we would get the same output:
+Output +hammerhead +great white +dogfish +frilled +bullhead +requiem +
The output above shows that the for loop iterated through the list, and printed each item from the list per line.
+Lists and other sequence-based data types like strings and tuples are common to use with loops because they are iterable. You can combine these data types with range() to add items to a list, for example:
+sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem'] + +for item in range(len(sharks)): + sharks.append('shark') + +print(sharks) +
Output +['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem', 'shark', 'shark', 'shark', 'shark', 'shark', 'shark'] +
Here, we have added a placeholder string of 'shark' for each item of the length of the sharks list.
+You can also use a for loop to construct a list from scratch:
+integers = [] + +for i in range(10): + integers.append(i) + +print(integers) +
In this example, the list integers is initialized empty, but the for loop populates the list like so:
+Output +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +
Similarly, we can iterate through strings:
+sammy = 'Sammy' + +for letter in sammy: + print(letter) +
Output +S +a +m +m +y +
Iterating through tuples is done in the same format as iterating through lists or strings above.
+When iterating through a dictionary, it’s important to keep the key : value structure in mind to ensure that you are calling the correct element of the dictionary. Here is an example that calls both the key and the value:
+sammy_shark = {'name': 'Sammy', 'animal': 'shark', 'color': 'blue', 'location': 'ocean'} + +for key in sammy_shark: + print(key + ': ' + sammy_shark[key]) +
Output +name: Sammy +animal: shark +location: ocean +color: blue +
When using dictionaries with for loops, the iterating variable corresponds to the keys of the dictionary, and dictionary_variable[iterating_variable] corresponds to the values. In the case above, the iterating variable key was used to stand for key, and sammy_shark[key] was used to stand for the values.
+Loops are often used to iterate and manipulate sequential data types.
+Loops can be nested in Python, as they can with other programming languages.
+A nested loop is a loop that occurs within another loop, structurally similar to nested if statements. These are constructed like so:
+for [first iterating variable] in [outer loop]: # Outer loop + [do something] # Optional + for [second iterating variable] in [nested loop]: # Nested loop + [do something] +
The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion. Then the program returns back to the top of the outer loop, completing the second iteration and again triggering the nested loop. Again, the nested loop runs to completion, and the program returns back to the top of the outer loop until the sequence is complete or a break or other statement disrupts the process.
+Let’s implement a nested for loop so we can take a closer look. In this example, the outer loop will iterate through a list of integers called num_list, and the inner loop will iterate through a list of strings called alpha_list.
+num_list = [1, 2, 3] +alpha_list = ['a', 'b', 'c'] + +for number in num_list: + print(number) + for letter in alpha_list: + print(letter) +
When we run this program, we’ll receive the following output:
+Output +1 +a +b +c +2 +a +b +c +3 +a +b +c +
The output illustrates that the program completes the first iteration of the outer loop by printing 1, which then triggers completion of the inner loop, printing a, b, c consecutively. Once the inner loop has completed, the program returns to the top of the outer loop, prints 2, then again prints the inner loop in its entirety (a, b, c), etc.
+Nested for loops can be useful for iterating through items within lists composed of lists. In a list composed of lists, if we employ just one for loop, the program will output each internal list as an item:
+list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]] + +for list in list_of_lists: + print(list) +
Output +['hammerhead', 'great white', 'dogfish'] +[0, 1, 2] +[9.9, 8.8, 7.7] +
In order to access each individual item of the internal lists, we’ll implement a nested for loop:
+list_of_lists = [['hammerhead', 'great white', 'dogfish'],[0, 1, 2],[9.9, 8.8, 7.7]] + +for list in list_of_lists: + for item in list: + print(item) +
Output +hammerhead +great white +dogfish +0 +1 +2 +9.9 +8.8 +7.7 +
When we utilize a nested for loop we are able to iterate over the individual items contained in the lists.
+This tutorial went over how for loops work in Python and how to construct them. For loops continue to loop through a block of code provided a certain number of times.
+From here, you can continue to learn about looping by reading tutorials on while loops and break, continue, and pass statements.
+ + + + + + + +In the context of programming, a function is a named sequence of statements that +performs a computation. When you define a function, you specify the name and the +sequence of statements. Later, you can “call” the function by name. We have already seen +one example of a function call:
+>>> type(32) +<type 'int'> +
The name of the function is type. The expression in parentheses is called the argument
+of the function. The result, for this function, is the type of the argument.
+It is common to say that a function “takes” an argument and “returns” a result. The result
+is called the return value.
Python provides built-in functions that convert values from one type to another. The +int function takes any value and converts it to an integer, if it can, or complains +otherwise:
+>>> int('32') +32 +>>> int('Hello') +ValueError: invalid literal for int(): Hello +
int can convert floating-point values to integers, but it doesn’t round off; it chops off +the fraction part:
+>>> int(3.99999) +3 +>>> int(-2.3) +-2 +
float converts integers and strings to floating-point numbers:
+>>> float(32) +32.0 +>>> float('3.14159') +3.14159 +
Finally, str converts its argument to a string:
+>>> str(32) +'32' +>>> str(3.14159) +'3.14159' +
So far, we have only been using the functions that come with Python, but it is also possible
+to add new functions. A function definition specifies the name of a new function and
+the sequence of statements that execute when the function is called.
+Here is an example:
def print_lyrics(): + print "I'm a lumberjack, and I'm okay." + print "I sleep all night and I work all day." +
def is a keyword that indicates that this is a function definition. The name of the function
+is print_lyrics. The rules for function names are the same as for variable names: letters,
+numbers and some punctuation marks are legal, but the first character can’t be a number.
+You can’t use a keyword as the name of a function, and you should avoid having a variable
+and a function with the same name.
+The empty parentheses after the name indicate that this function doesn’t take any
+arguments.
+The first line of the function definition is called the header; the rest is called the body.
+The header has to end with a colon and the body has to be indented. By convention, the
+indentation is always four spaces; see “Debugging” (page 33). The body can contain any
+number of statements.
+The strings in the print statements are enclosed in double quotes. Single quotes and
+double quotes do the same thing; most people use single quotes except in cases like this
+where a single quote (which is also an apostrophe) appears in the string.
+If you type a function definition in interactive mode, the interpreter prints ellipses (...)
+to let you know that the definition isn’t complete:
def print_lyrics(): + print "I'm a lumberjack, and I'm okay." + print "I sleep all night and I work all day." +
To end the function, you have to enter an empty line (this is not necessary in a script). +Defining a function creates a variable with the same name.
+>>> print print_lyrics +<function print_lyrics at 0xb7e99e9c> +>>> type(print_lyrics) +<type 'function'> +
The value of print_lyrics is a function object, which has type 'function'. +The syntax for calling the new function is the same as for built-in functions:
+>>> print_lyrics() +I'm a lumberjack, and I'm okay. +I sleep all night and I work all day. +
Once you have defined a function, you can use it inside another function. For example, +to repeat the previous refrain, we could write a function called repeat_lyrics:
+def repeat_lyrics(): + print_lyrics() + print_lyrics() +
And then call repeat_lyrics:
+>>> repeat_lyrics() +I'm a lumberjack, and I'm okay. +I sleep all night and I work all day. +I'm a lumberjack, and I'm okay. +I sleep all night and I work all day. +
But that’s not really how the song goes.
+Pulling together the code fragments from the previous section, the whole program looks +like this:
+def print_lyrics(): + print "I'm a lumberjack, and I'm okay." + print "I sleep all night and I work all day." +def repeat_lyrics(): + print_lyrics() + print_lyrics() + +repeat_lyrics() +
This program contains two function definitions: print_lyrics and repeat_lyrics.
+Function definitions get executed just like other statements, but the result creates func
+tion objects. The statements inside the function do not get executed until the function
+is called, and the function definition generates no output.
+As you might expect, you have to create a function before you can execute it. In other
+words, the function definition has to be executed before the function is called the first
+time.
In order to ensure that a function is defined before its first use, you have to know the
+order in which statements are executed, which is called the flow of execution.
+Execution always begins at the first statement of the program. Statements are executed
+one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember
+that statements inside the function are not executed until the function is called.
+A function call is like a detour in the flow of execution. Instead of going to the next
+statement, the flow jumps to the body of the function, executes all the statements there,
+and then comes back to pick up where it left off.
+That sounds simple enough, until you remember that one function can call another.
+While in the middle of one function, the program might have to execute the statements
+in another function. But while executing that new function, the program might have to
+execute yet another function!
+Fortunately, Python is good at keeping track of where it is, so each time a function
+completes, the program picks up where it left off in the function that called it. When it
+gets to the end of the program, it terminates.
+What’s the moral of this sordid tale? When you read a program, you don’t always want
+to read from top to bottom. Sometimes it makes more sense if you follow the flow of
+execution.
Some of the built-in functions we have seen require arguments. For example, when you
+call math.sin you pass a number as an argument. Some functions take more than one
+argument: math.pow takes two, the base and the exponent.
+Inside the function, the arguments are assigned to variables called parameters. Here is
+an example of a user-defined function that takes an argument:
def print_twice(bruce): + print bruce + print bruce +
This function assigns the argument to a parameter named bruce. When the function is
+called, it prints the value of the parameter (whatever it is) twice.
+This function works with any value that can be printed.
>>> print_twice('Spam') +Spam +Spam +>>> print_twice(17) +17 +17 +>>> print_twice(math.pi) +3.14159265359 +3.14159265359 +
The same rules of composition that apply to built-in functions also apply to user-defined
+functions, so we can use any kind of expression as an argument for print_twice:
>>> print_twice('Spam '*4) +Spam Spam Spam Spam +Spam Spam Spam Spam +>>> print_twice(math.cos(math.pi)) +-1.0 +-1.0 +
The argument is evaluated before the function is called, so in the examples the expres
+sions 'Spam '*4 and math.cos(math.pi) are only evaluated once.
+You can also use a variable as an argument:
>>> michael = 'Eric, the half a bee.' +>>> print_twice(michael) +Eric, the half a bee. +Eric, the half a bee. +
The name of the variable we pass as an argument (michael) has nothing to do with the +name of the parameter (bruce). It doesn’t matter what the value was called back home +(in the caller); here in print_twice, we call everybody bruce.
+When you create a variable inside a function, it is local, which means that it only exists +inside the function. For example:
+def cat_twice(part1, part2): + cat = part1 + part2 + print_twice(cat) +
This function takes two arguments, concatenates them, and prints the result twice. Here +is an example that uses it:
+>>> line1 = 'Bing tiddle ' +>>> line2 = 'tiddle bang.' +>>> cat_twice(line1, line2) +Bing tiddle tiddle bang. +Bing tiddle tiddle bang. +
When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get +an exception:
+>>> print cat +NameError: name 'cat' is not defined +
Parameters are also local. For example, outside print_twice, there is no such thing as +bruce.
+To keep track of which variables can be used where, it is sometimes useful to draw a
+stack diagram. Like state diagrams, stack diagrams show the value of each variable, but
+they also show the function each variable belongs to.
+Each function is represented by a frame. A frame is a box with the name of a function
+beside it and the parameters and variables of the function inside it. The stack diagram
+for the previous example is shown in Figure 3-1.
The frames are arranged in a stack that indicates which function called which, and so
+on. In this example, print_twice was called by cat_twice, and cat_twice was called
+by \__main\__, which is a special name for the topmost frame. When you create a variable
+outside of any function, it belongs to \__main\__.
Each parameter refers to the same value as its corresponding argument. So, part1 has
+the same value as line1, part2 has the same value as line2, and bruce has the same
+value as cat.
+If an error occurs during a function call, Python prints the name of the function, and
+the name of the function that called it, and the name of the function that called that, all
+the way back to \__main__\.
For example, if you try to access cat from within print_twice, you get a NameError:
+Traceback (innermost last): + File "test.py", line 13, in __main__ + cat_twice(line1, line2) + File "test.py", line 5, in cat_twice + print_twice(cat) + File "test.py", line 9, in print_twice + print cat + NameError: name 'cat' is not defined +
This list of functions is called a traceback. It tells you what program file the error oc +curred in, and what line, and what functions were executing at the time. It also shows +the line of code that caused the error. +The order of the functions in the traceback is the same as the order of the frames in the +stack diagram. The function that is currently running is listed at the bottom.
+Some of the functions we are using, such as the math functions, yield results; for lack of +a better name, I call them fruitful functions. Other functions, like print_twice, per +form an action but don’t return a value. They are called void functions. +When you call a fruitful function, you almost always want to do something with the +result; for example, you might assign it to a variable or use it as part of an expression:
+x = math.cos(radians) +golden = (math.sqrt(5) + 1) / 2 +
When you call a function in interactive mode, Python displays the result:
+>>> math.sqrt(5) +2.2360679774997898 +
But in a script, if you call a fruitful function all by itself, the return value is lost forever!
+math.sqrt(5) +
This script computes the square root of 5, but since it doesn’t store or display the result, +it is not very useful. +Void functions might display something on the screen or have some other effect, but +they don’t have a return value. If you try to assign the result to a variable, you get a special +value called None.
+>>> result = print_twice('Bing') +Bing +Bing +>>> print result +None +
The value None is not the same as the string 'None'. It is a special value that has its own +type:
+>>> print type(None) +<type 'NoneType'> +
The functions we have written so far are all void. We will start writing fruitful functions +in a few chapters.
+It may not be clear why it is worth the trouble to divide a program into functions. There
+are several reasons:
+- Creating a new function gives you an opportunity to name a group of statements,
+which makes your program easier to read and debug.
+- Functions can make a program smaller by eliminating repetitive code. Later, if you
+make a change, you only have to make it in one place.
+- Dividing a long program into functions allows you to debug the parts one at a time
+and then assemble them into a working whole.
+- Well-designed functions are often useful for many programs. Once you write and
+debug one, you can reuse it.
++Source:
+
+ Think Python by Allen B. Downey - 2012
In Part III, we looked at basic procedural statements in Python. Here, we’ll move on to
+explore a set of additional statements that we can use to create functions of our own.
+In simple terms, a function is a device that groups a set of statements so they can be run
+more than once in a program. Functions also can compute a result value and let us
+specify parameters that serve as function inputs, which may differ each time the code
+is run. Coding an operation as a function makes it a generally useful tool, which we
+can use in a variety of contexts.
+More fundamentally, functions are the alternative to programming by cutting and
+pasting—rather than having multiple redundant copies of an operation’s code, we can
+factor it into a single function. In so doing, we reduce our future work radically: if the
+operation must be changed later, we only have one copy to update, not many.
+Functions are the most basic program structure Python provides for maximizing code
+reuse and minimizing code redundancy. As we’ll see, functions are also a design tool
+that lets us split complex systems into manageable parts. Table 16-1 summarizes the
+primary function-related tools we’ll study in this part of the book.
| Statement | +Examples | +
|---|---|
| Calls | +myfunc('spam', 'eggs', meat=ham) | +
| def, return | +def adder(a, b=1, *c): return a + b + c[0] | +
| global | +def changer():global x; x = 'new' | +
| nonlocal | +def changer():nonlocal x; x = 'new' | +
| yield | +def squares(x):for i in range(x): yield i ** 2 | +
| lambda | +funcs = [lambda x: x*2, lambda x: x3] | +
Before we get into the details, let’s establish a clear picture of what functions are all +about. Functions are a nearly universal program-structuring device. You may have +come across them before in other languages, where they may have been called subroutines +or procedures. As a brief introduction, functions serve two primary development +roles:
+Maximizing code reuse and minimizing redundancy +As in most programming languages, Python functions are the simplest way to +package logic you may wish to use in more than one place and more than one time. +Up until now, all the code we’ve been writing has run immediately. Functions allow +us to group and generalize code to be used arbitrarily many times later. Because +they allow us to code an operation in a single place and use it in many places, +Python functions are the most basic factoring tool in the language: they allow us +to reduce code redundancy in our programs, and thereby reduce maintenance +effort.
+Procedural decomposition +Functions also provide a tool for splitting systems into pieces that have well-defined +roles. For instance, to make a pizza from scratch, you would start by mixing the +dough, rolling it out, adding toppings, baking it, and so on. If you were programming +a pizza-making robot, functions would help you divide the overall “make +pizza” task into chunks—one function for each subtask in the process. It’s easier +to implement the smaller tasks in isolation than it is to implement the entire process +at once. In general, functions are about procedure—how to do something, rather +than what you’re doing it to. We’ll see why this distinction matters in Part VI, when +we start making new object with classes.
+In this part of the book, we’ll explore the tools used to code functions in Python: function +basics, scope rules, and argument passing, along with a few related concepts such +as generators and functional tools. Because its importance begins to become more apparent +at this level of coding, we’ll also revisit the notion of polymorphism introduced +earlier in the book. As you’ll see, functions don’t imply much new syntax, but they do +lead us to some bigger programming ideas.
+Although it wasn’t made very formal, we’ve already used some functions in earlier
+chapters. For instance, to make a file object, we called the built-in open function; similarly,
+we used the len built-in function to ask for the number of items in a collection
+object.
+In this chapter, we will explore how to write new functions in Python. Functions we
+write behave the same way as the built-ins we’ve already seen: they are called in expressions, are passed values, and return results. But writing new functions requires
+the application of a few additional ideas that haven’t yet been introduced. Moreover,
+functions behave very differently in Python than they do in compiled languages like C.
+Here is a brief introduction to the main concepts behind Python functions, all of which
+we will study in this part of the book:
def is executable code. Python functions are written with a new statement, the
+def. Unlike functions in compiled languages such as C, def is an executable statement—
+your function does not exist until Python reaches and runs the def. In fact,
+it’s legal (and even occasionally useful) to nest def statements inside if statements,
+while loops, and even other defs. In typical operation, def statements are coded in
+module files and are naturally run to generate functions when a module file is first
+imported.def creates an object and assigns it to a name. When Python reaches and runs
+a def statement, it generates a new function object and assigns it to the function’s
+name. As with all assignments, the function name becomes a reference to the function
+object. There’s nothing magic about the name of a function—as you’ll see,
+the function object can be assigned to other names, stored in a list, and so on.
+Function objects may also have arbitrary user-defined attributes attached to them
+to record data.
lambda creates an object but returns it as a result. Functions may also be created
+with the lambda expression, a feature that allows us to in-line function definitions
+in places where a def statement won’t work syntactically
return sends a result object back to the caller. When a function is called, the
+caller stops until the function finishes its work and returns control to the caller.
+Functions that compute a value send it back to the caller with a return statement;
+the returned value becomes the result of the function call.
yield sends a result object back to the caller, but remembers where it left
+off. Functions known as generators may also use the yield statement to send back
+a value and suspend their state such that they may be resumed later, to produce a
+series of results over time. This is another advanced topic covered later in this part
+of the book.
global declares module-level variables that are to be assigned. By default, all
+names assigned in a function are local to that function and exist only while the
+function runs. To assign a name in the enclosing module, functions need to list it
+in a global statement. More generally, names are always looked up in scopes—
+places where variables are stored—and assignments bind names to scopes.
nonlocal declares enclosing function variables that are to be assigned. Similarly,
+the nonlocal statement added in Python 3.0 allows a function to assign a
+name that exists in the scope of a syntactically enclosing def statement. This allows
+enclosing functions to serve as a place to retain state—information remembered
+when a function is called—without using shared global names.
Arguments are passed by assignment (object reference). In Python, arguments
+are passed to functions by assignment (which, as we’ve learned, means by object
+reference). As you’ll see, in Python’s model the caller and function share objects
+by references, but there is no name aliasing. Changing an argument name within
+a function does not also change the corresponding name in the caller, but changing
+passed-in mutable objects can change objects shared by the caller.
Arguments, return values, and variables are not declared. As with everything
+in Python, there are no type constraints on functions. In fact, nothing about a
+function needs to be declared ahead of time: you can pass in arguments of any type,
+return any kind of object, and so on. As one consequence, a single function can
+often be applied to a variety of object types—any objects that sport a compatible
+interface (methods and expressions) will do, regardless of their specific types.
If some of the preceding words didn’t sink in, don’t worry—we’ll explore all of these +concepts with real code in this part of the book. Let’s get started by expanding on some +of these ideas and looking at a few examples.
+The def statement creates a function object and assigns it to a name. Its general format +is as follows:
+def <name>(arg1, arg2,... argN): + <statements> +
As with all compound Python statements, def consists of a header line followed by a
+block of statements, usually indented (or a simple statement after the colon). The
+statement block becomes the function’s body—that is, the code Python executes each
+time the function is called.
+The def header line specifies a function name that is assigned the function object, along
+with a list of zero or more arguments (sometimes called parameters) in parentheses.
+The argument names in the header are assigned to the objects passed in parentheses at
+the point of call.
Function bodies often contain a return statement:
+def <name>(arg1, arg2,... argN): + ... + return <value> +
The Python return statement can show up anywhere in a function body; it ends the +function call and sends a result back to the caller. The return statement consists of an +object expression that gives the function’s result. The return statement is optional; if +it’s not present, the function exits when the control flow falls off the end of the function +body. Technically, a function without a return statement returns the None object automatically, +but this return value is usually ignored.
+The Python def is a true executable statement: when it runs, it creates a new function +object and assigns it to a name. (Remember, all we have in Python is runtime; there is +no such thing as a separate compile time.) Because it’s a statement, a def can appear +anywhere a statement can—even nested in other statements. For instance, although +defs normally are run when the module enclosing them is imported, it’s also completely +legal to nest a function def inside an if statement to select between alternative +definitions:
+if test: + def func(): # Define func this way +... +else: + def func(): # Or else this way + ... + ... +func() # Call the version selected and built +
One way to understand this code is to realize that the def is much like an = statement: +it simply assigns a name at runtime. Unlike in compiled languages such as C, Python +functions do not need to be fully defined before the program runs. More generally, +defs are not evaluated until they are reached and run, and the code inside defs is not +evaluated until the functions are later called. +Because function definition happens at runtime, there’s nothing special about the +function name. What’s important is the object to which it refers:
+othername = func # Assign function object +othername() # Call func again +
Here, the function was assigned to a different name and called through the new name. +Like everything else in Python, functions are just objects; they are recorded explicitly +in memory at program execution time. In fact, besides calls, functions allow arbitrary +attributes to be attached to record information for later use:
+def func(): ... # Create function object +func() # Call object +func.attr = value # Attach attributes +
Apart from such runtime concepts (which tend to seem most unique to programmers +with backgrounds in traditional compiled languages), Python functions are straightforward +to use. Let’s code a first real example to demonstrate the basics. As you’ll see, +there are two sides to the function picture: a definition (the def that creates a function) +and a call (an expression that tells Python to run the function’s body).
+Here’s a definition typed interactively that defines a function called times, which returns +the product of its two arguments:
+>>> def times(x, y): # Create and assign function +... return x * y # Body executed when called +... +
When Python reaches and runs this def, it creates a new function object that packages +the function’s code and assigns the object to the name times. Typically, such a statement +is coded in a module file and runs when the enclosing file is imported; for something +this small, though, the interactive prompt suffices.
+After the def has run, you can call (run) the function in your program by adding +parentheses after the function’s name. The parentheses may optionally contain one or +more object arguments, to be passed (assigned) to the names in the function’s header:
+>>> times(2, 4) # Arguments in parentheses +8 +
This expression passes two arguments to times. As mentioned previously, arguments +are passed by assignment, so in this case the name x in the function header is assigned +the value 2, y is assigned the value 4, and the function’s body is run. For this function, +the body is just a return statement that sends back the result as the value of the call +expression. The returned object was printed here interactively (as in most languages, +2 * 4 is 8 in Python), but if we needed to use it later we could instead assign it to a +variable. For example:
+>>> x = times(3.14, 4) # Save the result object +>>> x +12.56 +
Now, watch what happens when the function is called a third time, with very different +kinds of objects passed in:
+>>> times('Ni', 4) # Functions are "typeless" +'NiNiNiNi' +
This time, our function means something completely different (Monty Python reference
+again intended). In this third call, a string and an integer are passed to x and y, instead
+of two numbers. Recall that * works on both numbers and sequences; because we never
+declare the types of variables, arguments, or return values in Python, we can use
+times to either multiply numbers or repeat sequences.
+In other words, what our times function means and does depends on what we pass into
+it. This is a core idea in Python (and perhaps the key to using the language well), which
+we’ll explore in the next section.
++Source:
+
+ Learning Python, Fourth Edition by Mark Lutz - 2009
A function is a block of instructions that performs an action and, once defined, can be reused. Functions make code more modular, allowing you to use the same code over and over again.
+Python has a number of built-in functions that you may be familiar with, including:
+Function names include parentheses and may include parameters.
+In this tutorial, we’ll go over how to define your own functions to use in your coding projects.
+Let’s start with turning the classic “Hello, World!” program into a function.
+We’ll create a new text file in our text editor of choice, and call the program hello.py. Then, we’ll define the function.
+A function is defined by using the def keyword, followed by a name of your choosing, followed by a set of parentheses which hold any parameters the function will take (they can be empty), and ending with a colon.
+In this case, we’ll define a function named hello():
+def hello(): +
This sets up the initial statement for creating a function.
+From here, we’ll add a second line with a 4-space indent to provide the instructions for what the function does. In this case, we’ll be printing Hello, World! to the console:
+def hello(): + print("Hello, World!") +
Our function is now fully defined, but if we run the program at this point, nothing will happen since we didn’t call the function.
+So, outside of our defined function block, let’s call the function with hello():
+def hello(): + print("Hello, World!") + +hello() +
Now, let’s run the program:
+python hello.py +
You should receive the following output:
+Hello, World! +
Functions can be more complicated than the hello() function we defined above. For example, we can use for loops, conditional statements, and more within our function block.
For example, the function defined below utilizes a conditional statement to check if the input for the name variable contains a vowel, then uses a for loop to iterate over the letters in the name string.
# Define function names() +def names(): + # Set up name variable with input + name = str(input('Enter your name: ')) + # Check whether name has a vowel + if set('aeiou').intersection(name.lower()): + print('Your name contains a vowel.') + else: + print('Your name does not contain a vowel.') + + # Iterate over name + for letter in name: + print(letter) + +# Call the function +names() +
The names() function we defined above sets up a conditional statement and a for loop, showing how code can be organized within a function definition. However, depending on what we intend with our program and how we want to set up our code, we may want to define the conditional statement and the for loop as two separate functions.
Defining functions within a program makes our code modular and reusable so that we can call the same functions without rewriting them.
+So far we have looked at functions with empty parentheses that do not take arguments, but we can define parameters in function definitions within their parentheses.
+A parameter is a named entity in a function definition, specifying an argument that the function can accept.
+Let’s create a small program that takes in parameters x, y, and z. We’ll create a function that adds the parameters together in different configurations. The sums of these will be printed by the function. Then we’ll call the function and pass numbers into the function.
+def add_numbers(x, y, z): + a = x + y + b = x + z + c = y + z + print(a, b, c) + +add_numbers(1, 2, 3) +
We passed the number 1 in for the x parameter, 2 in for the y parameter, and 3 in for the z parameter. These values correspond with each parameter in the order they are given.
+The program is essentially doing the following math based on the values we passed to the parameters:
+a = 1 + 2 +b = 1 + 3 +c = 2 + 3 +
The function also prints a, b, and c, and based on the math above we would expect a to be equal to 3, b to be 4, and c to be 5. Let’s run the program:
+python add_numbers.py +Output : 3 4 5 +
When we pass 1, 2, and 3 as parameters to the add_numbers() function, we receive the expected output.
+Parameters are arguments that are typically defined as variables within function definitions. They can be assigned values when you run the method, passing the arguments into the function.
+In addition to calling parameters in order, you can use keyword arguments in a function call, in which the caller identifies the arguments by the parameter name.
When you use keyword arguments, you can use parameters out of order because the Python interpreter will use the keywords provided to match the values to the parameters.
+Let’s create a function that will show us profile information for a user. We’ll pass parameters to it in the form of username (intended as a string), and followers (intended as an integer).
# Define function with parameters +def profile_info(username, followers): + print("Username: " + username) + print("Followers: " + str(followers)) +
Within the function definition statement, username and followers are contained in the parentheses of the profile_info() function. The block of the function prints out information about the user as strings, making use of the two parameters.
Now, we can call the function and assign parameters to it:
+def profile_info(username, followers): + print("Username: " + username) + print("Followers: " + str(followers)) + +# Call function with parameters assigned as above +profile_info("sammyshark", 945) + +# Call function with keyword arguments +profile_info(username="AlexAnglerfish", followers=342) +
In the first function call, we have filled in the information with a username of sammyshark and followers being 945, in the second function call we used keyword arguments, assigning values to the argument variables.
+Let’s run the program:
+python profile.py +Output : +Username: sammyshark +Followers: 945 +Username: AlexAnglerfish +Followers: 342 +
The output shows us the usernames and numbers of followers for both users.
+This also permits us to modify the order of the parameters, as in this example of the same program with a different call:
+def profile_info(username, followers): + print("Username: " + username) + print("Followers: " + str(followers)) + +# Change order of parameters +profile_info(followers=820, username="cameron-catfish") +
When we run the program again with the python profile.py command, we’ll receive the following output:
+Output: +Username: cameron-catfish +Followers: 820 +
Because the function definition maintains the same order of print() statements, if we use keyword arguments, it does not matter which order we pass them into the function call.
+We can also provide default values for one or both of the parameters. Let’s create a default value for the followers parameter with a value of 1:
def profile_info(username, followers=1): + print("Username: " + username) + print("Followers: " + str(followers)) +
Now, we can run the function with only the username function assigned, and the number of followers will automatically default to 1. We can also still change the number of followers if we would like.
+def profile_info(username, followers=1): + print("Username: " + username) + print("Followers: " + str(followers)) + +profile_info(username="JOctopus") +profile_info(username="sammyshark", followers=945) +
When we run the program with the python profile.py command, we’ll receive the following output:
+Output: +Username: JOctopus +Followers: 1 +Username: sammyshark +Followers: 945 +
Providing default parameters with values can let us skip defining values for each argument that already has a default.
+You can pass a parameter value into a function, and a function can also produce a value.
+A function can produce a value with the return statement, which will exit a function and optionally pass an expression back to the caller. If you use a return statement with no arguments, the function will return None.
+So far, we have used the print() statement instead of the return statement in our functions. Let’s create a program that instead of printing will return a variable.
+In a new text file called square.py, we’ll create a program that squares the parameter x and returns the variable y. We issue a call to print the result variable, which is formed by running the square() function with 3 passed into it.
+def square(x): + y = x ** 2 + return y + +result = square(3) +print(result) +
We can run the program and see the output:
+python square.py +Output: +9 +
The integer 9 is returned as output, which is what we would expect by asking Python to find the square of 3.
+To further understand how the return statement works, we can comment out the return statement in the program:
def square(x): + y = x ** 2 + # return y + +result = square(3) +print(result) +
Now, let’s run the program again:
+python square.py +Output: +None +
Without using the return statement here, the program cannot return a value so the value defaults to None.
As another example, in the add_numbers.py program above, we could swap out the print() statement for a return statement.
def add_numbers(x, y, z): + a = x + y + b = x + z + c = y + z + return a, b, c + +sums = add_numbers(1, 2, 3) +print(sums) +
Outside of the function, we set the variable sums equal to the result of the function taking in 1, 2, and 3 as we did above. Then we called a print of the sums variable.
+Let’s run the program again now that it has the return statement:
+Output: +(3, 4, 5) +
We receive the same numbers 3, 4, and 5 as output that we received previously by using the print() statement in the function. This time it is delivered as a tuple because the return statement’s expression list has at least one comma.
+Functions exit immediately when they hit a return statement, whether or not they’re returning a value.
+def loop_five(): + for x in range(0, 25): + print(x) + if x == 5: + # Stop function at x == 5 + return + print("This line will not execute.") + +loop_five() +
Using the return statement within the for loop ends the function, so the line that is outside of the loop will not run. If, instead, we had used a break statement, only the loop would have exited at that time, and the last print() line would run.
The return statement exits a function, and may return a value when issued with a parameter.
main() as a FunctionAlthough in Python you can call the function at the bottom of your program and it will run (as we have done in the examples above), many programming languages (like C++ and Java) require a main function in order to execute. Including a main() function, though not required, can structure our Python programs in a logical way that puts the most important components of the program into one function. It can also make our programs easier for non-Python programmers to read.
+We’ll start with adding a main() function to the hello.py program above. We’ll keep our hello() function, and then define a main() function:
+def hello(): + print("Hello, World!") + +def main(): +
Within the main() function, let’s include a print() statement to let us know that we’re in the main() function. Additionally, let’s call the hello() function within the main() function:
+def hello(): + print("Hello, World!") + + +def main(): + print("This is the main function") + hello() +
Finally, at the bottom of the program we’ll call the main() function:
+def hello(): + print("Hello, World!") + +def main(): + print("This is the main function.") + hello() + +main() +
At this point, we can run our program:
+python hello.py +Output: +This is the main function. +Hello, World! +
Because we called the hello() function within main() and then only called main() to run, the Hello, World! text printed only once, after the string that told us we were in the main function.
Next we’re going to be working with multiple functions, so it is worth reviewing the variable scope of global and local variables. If you define a variable within a function block, you’ll only be able to use that variable within that function. If you would like to use variables across functions it may be better to declare a global variable.
+In Python, '_main_' is the name of the scope where top-level code will execute. When a program is run from standard input, a script, or from an interactive prompt, its _name_ is set equal to '_main_'.
+Because of this, there is a convention to use the following construction:
+if __name__ == '__main__': + # Code to run when this is the main program here +
This lets program files be used either: +- as the main program and run what follows the if statement +- as a module and not run what follows the if statement.
+Any code that is not contained within this statement will be executed upon running. If you’re using your program file as a module, the code that is not in this statement will also execute upon its import while running the secondary file.
+Let’s expand on our names.py program above, and create a new file called more_names.py. In this program we’ll declare a global variable and modify our original names() function so that the instructions are in two discrete functions.
+The first function, has_vowel() will check to see if the name string contains a vowel.
The second function print_letters() will print each letter of the name string.
# Declare global variable name for use in all functions +name = str(input('Enter your name: ')) + + +# Define function to check if name contains a vowel +def has_vowel(): + if set('aeiou').intersection(name.lower()): + print('Your name contains a vowel.') + else: + print('Your name does not contain a vowel.') + + +# Iterate over letters in name string +def print_letters(): + for letter in name: + print(letter) +
With this set up, let’s define the main() function which will contain a call to both the has_vowel() and the print_letters() functions.
+# Declare global variable name for use in all functions +name = str(input('Enter your name: ')) + + +# Define function to check if name contains a vowel +def has_vowel(): + if set('aeiou').intersection(name.lower()): + print('Your name contains a vowel.') + else: + print('Your name does not contain a vowel.') + + +# Iterate over letters in name string +def print_letters(): + for letter in name: + print(letter) + + +# Define main method that calls other functions +def main(): + has_vowel() + print_letters() +
Finally, we’ll add the if \__name\__ == '\__main\__': construction at the bottom of the file. For our purposes, since we have put all the functions we would like to do in the main() function, we’ll call the main() function following this if statement.
# Declare global variable name for use in all functions +name = str(input('Enter your name: ')) + + +# Define function to check if name contains a vowel +def has_vowel(): + if set('aeiou').intersection(name.lower()): + print('Your name contains a vowel.') + else: + print('Your name does not contain a vowel.') + + +# Iterate over letters in name string +def print_letters(): + for letter in name: + print(letter) + + +# Define main method that calls other functions +def main(): + has_vowel() + print_letters() + + +# Execute main() function +if __name__ == '__main__': + main() +
We can now run the program:
+python more_names.py +
The program will show the same output as the names.py program, but here the code is more organized and can be used in a modular way without modification.
+If you did not want to declare a main() function, you alternatively could have ended the program like this:
+if __name__ == '__main__': + has_vowel() + print_letters() +
Using main() as a function and the if _name_ == '_main_': statement can organize your code in a logical way, making it more readable and modular.
Functions are code blocks of instructions that perform actions within a program, helping to make our code reusable and modular.
+To learn more about how to make your code more modular, you can read our guide on How To Write Modules in Python 3.
+++Source:
+
+ https://stackoverflow.com/questions/1909512/what-is-python-used-for
When writing utility functions, there’s a draw for Python programmers to give special +meaning to the return value of None. It seems to makes sense in some cases. For example, +say you want a helper function that divides one number by another. In the case of dividing +by zero, returning None seems natural because the result is undefined.
+def divide(a, b): + try: + return a / b + except ZeroDivisionError: + return None +
Code using this function can interpret the return value accordingly.
+result = divide(x, y) +if result is None: + print(‘Invalid inputs’) +
What happens when the numerator is zero? That will cause the return value to also be zero +(if the denominator is non-zero). This can cause problems when you evaluate the result in +a condition like an if statement. You may accidentally look for any False equivalent +value to indicate errors instead of only looking for None.
+x, y = 0, 5 +result = divide(x, y) +if not result: + print(‘Invalid inputs’) # This is wrong! +
This is a common mistake in Python code when None has special meaning. This is why +returning None from a function is error prone. There are two ways to reduce the chance of +such errors.
+The first way is to split the return value into a two-tuple. The first part of the tuple +indicates that the operation was a success or failure. The second part is the actual result +that was computed.
+def divide(a, b): + try: + return True, a / b + except ZeroDivisionError: + return False, None +
Callers of this function have to unpack the tuple. That forces them to consider the status +part of the tuple instead of just looking at the result of division.
+success, result = divide(x, y) +if not success: + print(‘Invalid inputs’) +
The problem is that callers can easily ignore the first part of the tuple (using the +underscore variable name, a Python convention for unused variables). The resulting code +doesn’t look wrong at first glance. This is as bad as just returning None.
+_, result = divide(x, y) +if not result: + print(‘Invalid inputs’) +
The second, better way to reduce these errors is to never return None at all. Instead, raise +an exception up to the caller and make them deal with it. Here, I turn a +ZeroDivisionError into a ValueError to indicate to the caller that the input +values are bad:
+def divide(a, b): + try: + return a / b + except ZeroDivisionError as e: + raise ValueError(‘Invalid inputs’) from e +
Now the caller should handle the exception for the invalid input case. +The caller no longer requires a condition on the return value of the function. If the +function didn’t raise an exception, then the return value must be good. The outcome of +exception handling is clear.
+x, y = 5, 2 +try: + result = divide(x, y) +except ValueError: + print(‘Invalid inputs’) +else: + print(‘Result is %.1f’ % result) +>>> +Result is 2.5 +
++ + + + + + + +Source:
+
+ Effective Python by Brett Slatkin
The programming language you will learn is Python. Python is an example of a highlevel -language; other high-level languages you might have heard of are C, C++, Perl, -and Java. -There are also low-level languages, sometimes referred to as “machine languages” or -“assembly languages.” Loosely speaking, computers can only run programs written in -low-level languages. So programs written in a high-level language have to be processed -before they can run. This extra processing takes some time, which is a small disadvantage -of high-level languages.
-The advantages are enormous. First, it is much easier to program in a high-level lan -guage. Programs written in a high-level language take less time to write, they are shorter -and easier to read, and they are more likely to be correct. Second, high-level languages -are portable, meaning that they can run on different kinds of computers with few or no -modifications. Low-level programs can run on only one kind of computer and have to -be rewritten to run on another.
-Due to these advantages, almost all programs are written in high-level languages. Lowlevel -languages are used only for a few specialized applications.
-Two kinds of programs process high-level languages into low-level languages: -interpreters and compilers. An interpreter reads a high-level program and executes it, -meaning that it does what the program says. It processes the program a little at a time, -alternately reading lines and performing computations. Figure 1-1 shows the structure -of an interpreter.
-
A compiler reads the program and translates it completely before the program starts -running. In this context, the high-level program is called the source code, and the -translated program is called the object code or the executable. Once a program is com -piled, you can execute it repeatedly without further translation. Figure 1-2 shows the -structure of a compiler.
-
Python is considered an interpreted language because Python programs are executed -by an interpreter. There are two ways to use the interpreter: interactive mode and script mode. In interactive mode, you type Python programs and the interpreter displays the -result: ->>> 1 + 1 -2 -The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you -type 1 + 1, the interpreter replies 2.
-Alternatively, you can store code in a file and use the interpreter to execute the contents -of the file, which is called a script. By convention, Python scripts have names that end -with .py. -To execute the script, you have to tell the interpreter the name of the file. If you have a -script named dinsdale.py and you are working in a UNIX command window, you type -python dinsdale.py. In other development environments, the details of executing -scripts are different. You can find instructions for your environment at the Python web -site http://python.org. -Working in interactive mode is convenient for testing small pieces of code because you -can type and execute them immediately. But for anything more than a few lines, you -should save your code as a script so you can modify and execute it in the future.
---Source:
-
- Think Python by Allen B. Downey - 2012
The brief description in the prior section is fairly standard for scripting languages, and -it’s usually all that most Python programmers need to know. You type code into text -files, and you run those files through the interpreter. Under the hood, though, a bit -more happens when you tell Python to “go.” Although knowledge of Python internals -is not strictly required for Python programming, a basic understanding of the runtime -structure of Python can help you grasp the bigger picture of program execution. -When you instruct Python to run your script, there are a few steps that Python carries -out before your code actually starts crunching away. Specifically, it’s first compiled to -something called “byte code” and then routed to something called a “virtual machine.”
-Internally, and almost completely hidden from you, when you execute a program -Python first compiles your source code (the statements in your file) into a format known -as byte code. Compilation is simply a translation step, and byte code is a lower-level, -platform-independent representation of your source code. Roughly, Python translates -each of your source statements into a group of byte code instructions by decomposing -them into individual steps. This byte code translation is performed to speed -execution—byte code can be run much more quickly than the original source code -statements in your text file. -You’ll notice that the prior paragraph said that this is almost completely hidden from -you. If the Python process has write access on your machine, it will store the byte code -of your programs in files that end with a .pyc extension (“.pyc” means compiled “.py” -source). You will see these files show up on your computer after you’ve run a few -programs alongside the corresponding source code files (that is, in the same -directories). -Python saves byte code like this as a startup speed optimization. The next time you run -your program, Python will load the .pyc files and skip the compilation step, as long as -you haven’t changed your source code since the byte code was last saved. Python automatically -checks the timestamps of source and byte code files to know when it must -recompile—if you resave your source code, byte code is automatically re-created the -next time your program is run. -If Python cannot write the byte code files to your machine, your program still works— -the byte code is generated in memory and simply discarded on program exit.* However, -because .pyc files speed startup time, you’ll want to make sure they are written for larger -programs. Byte code files are also one way to ship Python programs—Python is happy -to run a program if all it can find are .pyc files, even if the original .py source files are -absent.
-Once your program has been compiled to byte code (or the byte code has been loaded -from existing .pyc files), it is shipped off for execution to something generally known -as the Python Virtual Machine (PVM, for the more acronym-inclined among you). The -PVM sounds more impressive than it is; really, it’s not a separate program, and it need -not be installed by itself. In fact, the PVM is just a big loop that iterates through your -byte code instructions, one by one, to carry out their operations. The PVM is the runtime -engine of Python; it’s always present as part of the Python system, and it’s the -component that truly runs your scripts. Technically, it’s just the last step of what is -called the “Python interpreter.”
-
Figure illustrates the runtime structure described here. Keep in mind that all of this -complexity is deliberately hidden from Python programmers. Byte code compilation is -automatic, and the PVM is just part of the Python system that you have installed on -your machine. Again, programmers simply code and run files of statements.
-Readers with a background in fully compiled languages such as C and C++ might notice -a few differences in the Python model. For one thing, there is usually no build or “make” -step in Python work: code runs immediately after it is written. For another, Python byte -code is not binary machine code (e.g., instructions for an Intel chip). Byte code is a -Python-specific representation.
-This is why some Python code may not run as fast as C or C++ code, as described in -Chapter 1—the PVM loop, not the CPU chip, still must interpret the byte code, and -byte code instructions require more work than CPU instructions. On the other hand, -unlike in classic interpreters, there is still an internal compile step—Python does not -need to reanalyze and reparse each source statement repeatedly. The net effect is that -pure Python code runs at speeds somewhere between those of a traditional compiled -language and a traditional interpreted language. See Chapter 1 for more on Python -performance tradeoffs.
---Source:
-
- Learning Python, Fourth Edition by Mark Lutz - 2009
Really, as this book is being written, there are three primary implementations of the -Python language—CPython, Jython, and IronPython—along with a handful of secondary -implementations such as Stackless Python. In brief, CPython is the standard implementation; -all the others have very specific purposes and roles. All implement the -same Python language but execute programs in different ways.
-The original, and standard, implementation of Python is usually called CPython, when -you want to contrast it with the other two. Its name comes from the fact that it is coded -in portable ANSI C language code. This is the Python that you fetch from http://www -.python.org, get with the ActivePython distribution, and have automatically on most -Linux and Mac OS X machines. If you’ve found a preinstalled version of Python on -your machine, it’s probably CPython, unless your company is using Python in very -specialized ways. -Unless you want to script Java or .NET applications with Python, you probably want -to use the standard CPython system. Because it is the reference implementation of the -language, it tends to run the fastest, be the most complete, and be more robust than -the alternative systems. Figure 1-3 reflects CPython’s runtime architecture.
-The Jython system (originally known as JPython) is an alternative implementation of -the Python language, targeted for integration with the Java programming language. -Jython consists of Java classes that compile Python source code to Java byte code and -then route the resulting byte code to the Java Virtual Machine (JVM). Programmers -still code Python statements in .py text files as usual; the Jython system essentially just -replaces the rightmost two bubbles in Figure 1-3 with Java-based equivalents. -Jython’s goal is to allow Python code to script Java applications, much as CPython -allows Python to script C and C++ components. Its integration with Java is remarkably -seamless. Because Python code is translated to Java byte code, it looks and feels like a -true Java program at runtime. Jython scripts can serve as web applets and servlets, build -Java-based GUIs, and so on. Moreover, Jython includes integration support that allows -Python code to import and use Java classes as though they were coded in Python. -Because Jython is slower and less robust than CPython, though, it is usually seen as a -tool of interest primarily to Java developers looking for a scripting language to be a -frontend to Java code.
-A third implementation of Python, and newer than both CPython and Jython, -IronPython is designed to allow Python programs to integrate with applications coded -to work with Microsoft’s .NET Framework for Windows, as well as the Mono open -source equivalent for Linux. .NET and its C# programming language runtime system -are designed to be a language-neutral object communication layer, in the spirit of Microsoft’s -earlier COM model. IronPython allows Python programs to act as both client -and server components, accessible from other .NET languages. -By implementation, IronPython is very much like Jython (and, in fact, was developed -by the same creator)—it replaces the last two bubbles in Figure 1-3 with equivalents -for execution in the .NET environment. Also, like Jython, IronPython has a special -focus—it is primarily of interest to developers integrating Python with .NET components. -Because it is being developed by Microsoft, though, IronPython might also be -able to leverage some important optimization tools for better performance. -IronPython’s scope is still evolving as I write this; for more details, consult the Python -online resources or search the Web.
---Source:
-
- Learning Python, Fourth Edition by Mark Lutz - 2009
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
-Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
---Source:
-
- https://stackoverflow.com/questions/1909512/what-is-python-used-for
--Source:
-
- https://en.wikiversity.org/wiki/Python_Concepts/Why_learn_Python
Here are links to just a few of the organizations that use python:
-- https://wiki.python.org/moin/OrganizationsUsingPython
Python Success Stories :
-- https://www.python.org/about/success
The programming language you will learn is Python. Python is an example of a highlevel +language; other high-level languages you might have heard of are C, C++, Perl, +and Java. +There are also low-level languages, sometimes referred to as “machine languages” or +“assembly languages.” Loosely speaking, computers can only run programs written in +low-level languages. So programs written in a high-level language have to be processed +before they can run. This extra processing takes some time, which is a small disadvantage +of high-level languages.
+The advantages are enormous. First, it is much easier to program in a high-level lan +guage. Programs written in a high-level language take less time to write, they are shorter +and easier to read, and they are more likely to be correct. Second, high-level languages +are portable, meaning that they can run on different kinds of computers with few or no +modifications. Low-level programs can run on only one kind of computer and have to +be rewritten to run on another.
+Due to these advantages, almost all programs are written in high-level languages. Lowlevel +languages are used only for a few specialized applications.
+Two kinds of programs process high-level languages into low-level languages: +interpreters and compilers. An interpreter reads a high-level program and executes it, +meaning that it does what the program says. It processes the program a little at a time, +alternately reading lines and performing computations. Figure 1-1 shows the structure +of an interpreter.
+
A compiler reads the program and translates it completely before the program starts +running. In this context, the high-level program is called the source code, and the +translated program is called the object code or the executable. Once a program is com +piled, you can execute it repeatedly without further translation. Figure 1-2 shows the +structure of a compiler.
+Python is considered an interpreted language because Python programs are executed +by an interpreter. There are two ways to use the interpreter: interactive mode and script mode. In interactive mode, you type Python programs and the interpreter displays the +result: +>>> 1 + 1 +2 +The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you +type 1 + 1, the interpreter replies 2.
+Alternatively, you can store code in a file and use the interpreter to execute the contents +of the file, which is called a script. By convention, Python scripts have names that end +with .py. +To execute the script, you have to tell the interpreter the name of the file. If you have a +script named dinsdale.py and you are working in a UNIX command window, you type +python dinsdale.py. In other development environments, the details of executing +scripts are different. You can find instructions for your environment at the Python web +site http://python.org. +Working in interactive mode is convenient for testing small pieces of code because you +can type and execute them immediately. But for anything more than a few lines, you +should save your code as a script so you can modify and execute it in the future.
+++Source:
+
+ Think Python by Allen B. Downey - 2012
The brief description in the prior section is fairly standard for scripting languages, and +it’s usually all that most Python programmers need to know. You type code into text +files, and you run those files through the interpreter. Under the hood, though, a bit +more happens when you tell Python to “go.” Although knowledge of Python internals +is not strictly required for Python programming, a basic understanding of the runtime +structure of Python can help you grasp the bigger picture of program execution. +When you instruct Python to run your script, there are a few steps that Python carries +out before your code actually starts crunching away. Specifically, it’s first compiled to +something called “byte code” and then routed to something called a “virtual machine.”
+Internally, and almost completely hidden from you, when you execute a program +Python first compiles your source code (the statements in your file) into a format known +as byte code. Compilation is simply a translation step, and byte code is a lower-level, +platform-independent representation of your source code. Roughly, Python translates +each of your source statements into a group of byte code instructions by decomposing +them into individual steps. This byte code translation is performed to speed +execution—byte code can be run much more quickly than the original source code +statements in your text file. +You’ll notice that the prior paragraph said that this is almost completely hidden from +you. If the Python process has write access on your machine, it will store the byte code +of your programs in files that end with a .pyc extension (“.pyc” means compiled “.py” +source). You will see these files show up on your computer after you’ve run a few +programs alongside the corresponding source code files (that is, in the same +directories). +Python saves byte code like this as a startup speed optimization. The next time you run +your program, Python will load the .pyc files and skip the compilation step, as long as +you haven’t changed your source code since the byte code was last saved. Python automatically +checks the timestamps of source and byte code files to know when it must +recompile—if you resave your source code, byte code is automatically re-created the +next time your program is run. +If Python cannot write the byte code files to your machine, your program still works— +the byte code is generated in memory and simply discarded on program exit.* However, +because .pyc files speed startup time, you’ll want to make sure they are written for larger +programs. Byte code files are also one way to ship Python programs—Python is happy +to run a program if all it can find are .pyc files, even if the original .py source files are +absent.
+Once your program has been compiled to byte code (or the byte code has been loaded +from existing .pyc files), it is shipped off for execution to something generally known +as the Python Virtual Machine (PVM, for the more acronym-inclined among you). The +PVM sounds more impressive than it is; really, it’s not a separate program, and it need +not be installed by itself. In fact, the PVM is just a big loop that iterates through your +byte code instructions, one by one, to carry out their operations. The PVM is the runtime +engine of Python; it’s always present as part of the Python system, and it’s the +component that truly runs your scripts. Technically, it’s just the last step of what is +called the “Python interpreter.”
+Figure illustrates the runtime structure described here. Keep in mind that all of this +complexity is deliberately hidden from Python programmers. Byte code compilation is +automatic, and the PVM is just part of the Python system that you have installed on +your machine. Again, programmers simply code and run files of statements.
+Readers with a background in fully compiled languages such as C and C++ might notice +a few differences in the Python model. For one thing, there is usually no build or “make” +step in Python work: code runs immediately after it is written. For another, Python byte +code is not binary machine code (e.g., instructions for an Intel chip). Byte code is a +Python-specific representation.
+This is why some Python code may not run as fast as C or C++ code, as described in +Chapter 1—the PVM loop, not the CPU chip, still must interpret the byte code, and +byte code instructions require more work than CPU instructions. On the other hand, +unlike in classic interpreters, there is still an internal compile step—Python does not +need to reanalyze and reparse each source statement repeatedly. The net effect is that +pure Python code runs at speeds somewhere between those of a traditional compiled +language and a traditional interpreted language. See Chapter 1 for more on Python +performance tradeoffs.
+++Source:
+
+ Learning Python, Fourth Edition by Mark Lutz - 2009
Really, as this book is being written, there are three primary implementations of the +Python language—CPython, Jython, and IronPython—along with a handful of secondary +implementations such as Stackless Python. In brief, CPython is the standard implementation; +all the others have very specific purposes and roles. All implement the +same Python language but execute programs in different ways.
+The original, and standard, implementation of Python is usually called CPython, when +you want to contrast it with the other two. Its name comes from the fact that it is coded +in portable ANSI C language code. This is the Python that you fetch from http://www +.python.org, get with the ActivePython distribution, and have automatically on most +Linux and Mac OS X machines. If you’ve found a preinstalled version of Python on +your machine, it’s probably CPython, unless your company is using Python in very +specialized ways. +Unless you want to script Java or .NET applications with Python, you probably want +to use the standard CPython system. Because it is the reference implementation of the +language, it tends to run the fastest, be the most complete, and be more robust than +the alternative systems. Figure 1-3 reflects CPython’s runtime architecture.
+The Jython system (originally known as JPython) is an alternative implementation of +the Python language, targeted for integration with the Java programming language. +Jython consists of Java classes that compile Python source code to Java byte code and +then route the resulting byte code to the Java Virtual Machine (JVM). Programmers +still code Python statements in .py text files as usual; the Jython system essentially just +replaces the rightmost two bubbles in Figure 1-3 with Java-based equivalents. +Jython’s goal is to allow Python code to script Java applications, much as CPython +allows Python to script C and C++ components. Its integration with Java is remarkably +seamless. Because Python code is translated to Java byte code, it looks and feels like a +true Java program at runtime. Jython scripts can serve as web applets and servlets, build +Java-based GUIs, and so on. Moreover, Jython includes integration support that allows +Python code to import and use Java classes as though they were coded in Python. +Because Jython is slower and less robust than CPython, though, it is usually seen as a +tool of interest primarily to Java developers looking for a scripting language to be a +frontend to Java code.
+A third implementation of Python, and newer than both CPython and Jython, +IronPython is designed to allow Python programs to integrate with applications coded +to work with Microsoft’s .NET Framework for Windows, as well as the Mono open +source equivalent for Linux. .NET and its C# programming language runtime system +are designed to be a language-neutral object communication layer, in the spirit of Microsoft’s +earlier COM model. IronPython allows Python programs to act as both client +and server components, accessible from other .NET languages. +By implementation, IronPython is very much like Jython (and, in fact, was developed +by the same creator)—it replaces the last two bubbles in Figure 1-3 with equivalents +for execution in the .NET environment. Also, like Jython, IronPython has a special +focus—it is primarily of interest to developers integrating Python with .NET components. +Because it is being developed by Microsoft, though, IronPython might also be +able to leverage some important optimization tools for better performance. +IronPython’s scope is still evolving as I write this; for more details, consult the Python +online resources or search the Web.
+++Source:
+
+ Learning Python, Fourth Edition by Mark Lutz - 2009
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
+Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
+++Source:
+
+ https://stackoverflow.com/questions/1909512/what-is-python-used-for
++Source:
+
+ https://en.wikiversity.org/wiki/Python_Concepts/Why_learn_Python
Here are links to just a few of the organizations that use python:
+- https://wiki.python.org/moin/OrganizationsUsingPython
Python Success Stories :
+- https://www.python.org/about/success
Now that you’re ready to start writing your own functions, we need to get more formal
+about what names mean in Python. When you use a name in a program, Python creates,
+changes, or looks up the name in what is known as a namespace—a place where names
+live. When we talk about the search for a name’s value in relation to code, the term
+scope refers to a namespace: that is, the location of a name’s assignment in your code
+determines the scope of the name’s visibility to your code.
+Just about everything related to names, including scope classification, happens at assignment
+time in Python. As we’ve seen, names in Python spring into existence when
+they are first assigned values, and they must be assigned before they are used. Because
+names are not declared ahead of time, Python uses the location of the assignment of a
+name to associate it with (i.e., bind it to) a particular namespace. In other words, the
+place where you assign a name in your source code determines the namespace it will
+live in, and hence its scope of visibility.
+Besides packaging code, functions add an extra namespace layer to your programs—
+by default, all names assigned inside a function are associated with that function’s
+namespace, and no other. This means that:
In all cases, the scope of a variable (where it can be used) is always determined by where
+it is assigned in your source code and has nothing to do with which functions call which.
+In fact, as we’ll learn in this chapter, variables may be assigned in three different places,
+corresponding to three different scopes:
+- If a variable is assigned inside a def, it is local to that function.
+- If a variable is assigned in an enclosing def, it is nonlocal to nested functions.
+- If a variable is assigned outside all defs, it is global to the entire file.
+We call this lexical scoping because variable scopes are determined entirely by the locations
+of the variables in the source code of your program files, not by function calls.
+For example, in the following module file, the X = 99 assignment creates a global variable
+named X (visible everywhere in this file), but the X = 88 assignment creates a
+local variable X (visible only within the def statement):
X = 99 +def func(): + X = 88 +
Even though both variables are named X, their scopes make them different. The net +effect is that function scopes help to avoid name clashes in your programs and help to +make functions more self-contained program units.
+Before we started writing functions, all the code we wrote was at the top level of a
+module (i.e., not nested in a def), so the names we used either lived in the module itself
+or were built-ins predefined by Python (e.g., open). Functions provide nested namespaces
+(scopes) that localize the names they use, such that names inside a function
+won’t clash with those outside it (in a module or another function). Again, functions
+define a local scope, and modules define a global scope. The two scopes are related as
+follows:
+- The enclosing module is a global scope. Each module is a global scope—that
+is, a namespace in which variables created (assigned) at the top level of the module
+file live. Global variables become attributes of a module object to the outside world
+but can be used as simple variables within a module file.
+- The global scope spans a single file only. Don’t be fooled by the word “global”
+here—names at the top level of a file are only global to code within that single file.
+There is really no notion of a single, all-encompassing global file-based scope in Python. Instead, names are partitioned into modules, and you must always import
+a module explicitly if you want to be able to use the names its file defines. When
+you hear “global” in Python, think “module.”
+- Each call to a function creates a new local scope. Every time you call a function,
+you create a new local scope—that is, a namespace in which the names created
+inside that function will usually live. You can think of each def statement (and
+lambda expression) as defining a new local scope, but because Python allows functions
+to call themselves to loop (an advanced technique known as recursion), the
+local scope in fact technically corresponds to a function call—in other words, each
+call creates a new local namespace. Recursion is useful when processing structures
+whose shapes can’t be predicted ahead of time.
+- Assigned names are local unless declared global or nonlocal. By default, all
+the names assigned inside a function definition are put in the local scope (the
+namespace associated with the function call). If you need to assign a name that
+lives at the top level of the module enclosing the function, you can do so by declaring
+it in a global statement inside the function. If you need to assign a name
+that lives in an enclosing def, as of Python 3.0 you can do so by declaring it in a
+nonlocal statement.
+- All other names are enclosing function locals, globals, or built-ins. Names
+not assigned a value in the function definition are assumed to be enclosing scope
+locals (in an enclosing def), globals (in the enclosing module’s namespace), or builtins
+(in the predefined builtin module Python provides).
There are a few subtleties to note here. First, keep in mind that code typed at the +interactive command prompt follows these same rules. You may not know it yet, but +code run interactively is really entered into a built-in module called main; this +module works just like a module file, but results are echoed as you go. Because of this, +interactively created names live in a module, too, and thus follow the normal scope +rules: they are global to the interactive session. You’ll learn more about modules in the +next part of this book.
+Also note that any type of assignment within a function classifies a name as local. This +includes = statements, module names in import, function names in def, function argument +names, and so on. If you assign a name in any way within a def, it will become a +local to that function.
+Conversely, in-place changes to objects do not classify names as locals; only actual name +assignments do. For instance, if the name L is assigned to a list at the top level of a +module, a statement L = X within a function will classify L as a local, but L.append(X) +will not. In the latter case, we are changing the list object that L references, not L itself— +L is found in the global scope as usual, and Python happily modifies it without requiring +a global (or nonlocal) declaration. As usual, it helps to keep the distinction between +names and objects clear: changing an object is not an assignment to a name.
+++Source:
+
+ Learning Python, Fourth Edition by Mark Lutz - 2009
good resource : http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html
+ + + + + + + +Roughly speaking, namespaces are just containers for mapping names to objects. As you might have already heard, everything in Python - literals, lists, dictionaries, functions, classes, etc. - is an object. +Such a “name-to-object” mapping allows us to access an object by a name that we’ve assigned to it. E.g., if we make a simple string assignment via a_string = "Hello string", we created a reference to the "Hello string" object, and henceforth we can access via its variable name a_string.
+We can picture a namespace as a Python dictionary structure, where the dictionary keys represent the names and the dictionary values the object itself (and this is also how namespaces are currently implemented in Python), e.g.,
+a_namespace = {'name_a':object_1, 'name_b':object_2, ... } +
Now, the tricky part is that we have multiple independent namespaces in Python, and names can be reused for different namespaces (only the objects are unique, for example:
+a_namespace = {'name_a':object_1, 'name_b':object_2, ...} +b_namespace = {'name_a':object_3, 'name_b':object_4, ...} +
For example, everytime we call a for-loop or define a function, it will create its own namespace. Namespaces also have different levels of hierarchy (the so-called “scope”), which we will discuss in more detail in the next section.
+In the section above, we have learned that namespaces can exist independently from each other and that they are structured in a certain hierarchy, which brings us to the concept of “scope”. The “scope” in Python defines the “hierarchy level” in which we search namespaces for certain “name-to-object” mappings. +For example, let us consider the following code:
+i = 1 + +def foo(): + i = 5 + print(i, 'in foo()') + +print(i, 'global') + +foo() + +''' +output: +1 global +5 in foo() +''' +
Here, we just defined the variable name i twice, once on the foo function. +- foo_namespace = {'i':object_3, ...} +- global_namespace = {'i':object_1, 'name_b':object_2, ...}
+So, how does Python know which namespace it has to search if we want to print the value of the variable i? This is where Python’s LEGB-rule comes into play, which we will discuss in the next section.
+If we want to print out the dictionary mapping of the global and local variables, we can use the the functions global() and local()
+#print(globals()) # prints global namespace +#print(locals()) # prints local namespace + +glob = 1 + +def foo(): + loc = 5 + print('loc in foo():', 'loc' in locals()) + +foo() +print('loc in global:', 'loc' in globals()) +print('glob in global:', 'foo' in globals()) + +''' +loc in foo(): True +loc in global: False +glob in global: True +''' +
We have seen that multiple namespaces can exist independently from each other and that they can contain the same variable names on different hierachy levels. The “scope” defines on which hierarchy level Python searches for a particular “variable name” for its associated object. Now, the next question is: “In which order does Python search the different levels of namespaces before it finds the name-to-object’ mapping?” +To answer is: It uses the LEGB-rule, which stands for
+Local -> Enclosed -> Global -> Built-in,
where the arrows should denote the direction of the namespace-hierarchy search order.
+So, if a particular name:object mapping cannot be found in the local namespaces, the namespaces of the enclosed scope are being searched next. If the search in the enclosed scope is unsuccessful, too, Python moves on to the global namespace, and eventually, it will search the built-in namespace (side note: if a name cannot found in any of the namespaces, a NameError will is raised).
+Namespaces can also be further nested, for example if we import modules, or if we are defining new classes. In those cases we have to use prefixes to access those nested namespaces. Let me illustrate this concept in the following code block:
+import numpy +import math +import scipy + +print(math.pi, 'from the math module') +print(numpy.pi, 'from the numpy package') +print(scipy.pi, 'from the scipy package') + + +''' +3.141592653589793 from the math module +3.141592653589793 from the numpy package +3.141592653589793 from the scipy package +''' +
(This is also why we have to be careful if we import modules via “from a_module import *”, since it loads the variable names into the global namespace and could potentially overwrite already existing variable names)
+
As a warm-up exercise, let us first forget about the enclosed (E) and built-in (B) scopes in the LEGB rule and only take a look at LG - the local and global scopes. +What does the following code print?
+a_var = 'global variable' + +def a_func(): + print(a_var, '[ a_var inside a_func() ]') + +a_func() +print(a_var, '[ a_var outside a_func() ]') + +''' +answer: +global value [ a_var inside a_func() ] +global value [ a_var outside a_func() ] +''' +
Here is why:
+We call a_func() first, which is supposed to print the value of a_var. According to the LEGB rule, the function will first look in its own local scope (L) if a_var is defined there. Since a_func() does not define its own a_var, it will look one-level above in the global scope (G) in which a_var has been defined previously.
+Example 1.2 +Now, let us define the variable a_var in the global and the local scope. +Can you guess what the following code will produce?
+a_var = 'global value' + +def a_func(): + a_var = 'local value' + print(a_var, '[ a_var inside a_func() ]') + +a_func() +print(a_var, '[ a_var outside a_func() ]') +''' +answer: +local value [ a_var inside a_func() ] +global value [ a_var outside a_func() ] +''' +
Here is why:
+When we call a_func(), it will first look in its local scope (L) for a_var, since a_var is defined in the local scope of a_func, its assigned value local variable is printed. Note that this doesn’t affect the global variable, which is in a different scope.
+However, it is also possible to modify the global by, e.g., re-assigning a new value to it if we use the global keyword as the following example will illustrate:
+a_var = 'global value' + +def a_func(): + global a_var + a_var = 'local value' + print(a_var, '[ a_var inside a_func() ]') + +print(a_var, '[ a_var outside a_func() ]') +a_func() +print(a_var, '[ a_var outside a_func() ]') +''' +output: +global value [ a_var outside a_func() ] +local value [ a_var inside a_func() ] +local value [ a_var outside a_func() ] +''' +
But we have to be careful about the order: it is easy to raise an UnboundLocalError if we don’t explicitly tell Python that we want to use the global scope and try to modify a variable’s value (remember, the right side of an assignment operation is executed first):
+a_var = 1 + +def a_func(): + a_var = a_var + 1 + print(a_var, '[ a_var inside a_func() ]') + +print(a_var, '[ a_var outside a_func() ]') +a_func() + +''' +output: +--------------------------------------------------------------------------- +UnboundLocalError Traceback (most recent call last) +''' +
Now, let us introduce the concept of the enclosed (E) scope. Following the order “Local -> Enclosed -> Global”, can you guess what the following code will print?
+Example 2.1
+a_var = 'global value' + +def outer(): + a_var = 'enclosed value' + + def inner(): + a_var = 'local value' + print(a_var) + + inner() + +outer() +''' +output: +local value +''' +
Here is why:
+Let us quickly recapitulate what we just did: We called outer(), which defined the variable a_var locally (next to an existing a_var in the global scope). Next, the outer() function called inner(), which in turn defined a variable with of name a_var as well. The print() function inside inner() searched in the local scope first (L->E) before it went up in the scope hierarchy, and therefore it printed the value that was assigned in the local scope.
+Similar to the concept of the global keyword, which we have seen in the section above, we can use the keyword nonlocal inside the inner function to explicitly access a variable from the outer (enclosed) scope in order to modify its value. +Note that the nonlocal keyword was added in Python 3.x and is not implemented in Python 2.x (yet).
+a_var = 'global value' + +def outer(): + a_var = 'local value' + print('outer before:', a_var) + def inner(): + nonlocal a_var + a_var = 'inner value' + print('in inner():', a_var) + inner() + print("outer after:", a_var) +outer() +''' +output: +outer before: local value +in inner(): inner value +outer after: inner value +''' +
To wrap up the LEGB rule, let us come to the built-in scope. Here, we will define our “own” length-function, which happens to bear the same name as the in-built len() function. What outcome do you excpect if we’d execute the following code?
+a_var = 'global variable' + +def len(in_var): + print('called my len() function') + l = 0 + for i in in_var: + l += 1 + return l + +def a_func(in_var): + len_in_var = len(in_var) + print('Input variable is of length', len_in_var) + +a_func('Hello, World!') +''' +output: +called my len() function +Input variable is of length 13 +''' +
Here is why:
+Since the exact same names can be used to map names to different objects - as long as the names are in different name spaces - there is no problem of reusing the name len to define our own length function (this is just for demonstration pruposes, it is NOT recommended). As we go up in Python’s L -> E -> G -> B hierarchy, the function a_func() finds len() already in the global scope (G) first before it attempts to search the built-in (B) namespace.
+Now, after we went through a couple of exercises, let us quickly check where we are. So, one more time: What would the following code print out?
+a = 'global' + +def outer(): + + def len(in_var): + print('called my len() function: ', end="") + l = 0 + for i in in_var: + l += 1 + return l + + a = 'local' + + def inner(): + global len + nonlocal a + a += ' variable' + inner() + print('a is', a) + print(len(a)) + + +outer() + +print(len(a)) +print('a is', a) + + +''' +output: +a is local variable +called my len() function: 14 +6 +a is global +''' +
I hope this short tutorial was helpful to understand the basic concept of Python’s scope resolution order using the LEGB rule. I want to encourage you (as a little self-assessment exercise) to look at the code snippets again tomorrow and check if you can correctly predict all their outcomes.
+A rule of thumb
+In practice, it is usually a bad idea to modify global variables inside the function scope, since it often be the cause of confusion and weird errors that are hard to debug. +If you want to modify a global variable via a function, it is recommended to pass it as an argument and reassign the return-value. +For example:
+a_var = 2 + +def a_func(some_var): + return 2**3 + +a_var = a_func(a_var) +print(a_var) + +''' +output: +8 +''' +
++ + + + + + + +Source:
+
+ http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html
A program is a sequence of instructions that specifies how to perform a computation. +The computation might be something mathematical, such as solving a system of equat +ions or finding the roots of a polynomial, but it can also be a symbolic computation, +such as searching and replacing text in a document or (strangely enough) compiling a +program. +The details look different in different languages, but a few basic instructions appear in +just about every language:
+input:
+output:
+math:
+conditional execution:
+repetition:
+Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no +matter how complicated, is made up of instructions that look pretty much like these. So +you can think of programming as the process of breaking a large, complex task into +smaller and smaller subtasks until the subtasks are simple enough to be performed with +one of these basic instructions. +That may be a little vague, but we will come back to this topic when we talk about +algorithms.
+++Source:
+
+ Think Python by Allen B. Downey - 2012
If you can't execute or run a Python script, then programming is pointless. When you run a Python script, the interpreter converts a Python program into something that that the computer can understand. Executing a Python program can be done in two ways: calling the Python interpreter with a shebang line, and using the interactive Python shell.
+Generally programmers write stand alone scripts, that are independent to live environments. Then they save it with a ".py" extension, which indicates to the operating system and programmer that the file is actually a Python program. After the interpreter is invoked, it reads and interprets the file. The way Python scripts are run on Windows versus Unix based operating systems is very different. We'll show you the difference, and how to run a Python script on Windows and Unix platforms.
+Windows users must pass the path of the program as an argument to the Python interpreter. Such as follows:
+C:\Python27\python.exe C:\Users\Username\Desktop\my_python_script.py +
Note that you must use the full path of the Python interpreter. If you want to simply type python.exe C:\Users\Username\Desktop\my_python_script.py you must add python.exe to your PATH environmental variable. +Note that Windows comes with two Python executables - python.exe and pythonw.exe. If you want a terminal to pop-up when you run your script, use python.exe However if you don't want any terminal pop-up, use pythonw.exe. pythonw.exe is typically used for GUI programs, where you only want to display your program, not the terminal.
+On platforms like Mac, BSD or Linux (Unix) you can put a "shebang" line as first line of the program which indicates the location of the Python interpreter on the hard drive. It's in the following format:
+#!/path/to/interpreter
+A common shebang line used for the Python interpreter is as follows:
+#!/usr/bin/env python
+You must then make the script executable, using the following command:
+chmod +x my_python_script.py +
Unlike Windows, the Python interpreter is typically already in the $PATH environmental variable, so adding it is un-necessary.
+You can then run a program by invoking the Python interpreter manually as follows:
+python firstprogram.py +
Assuming that you already have Python installed and running well (if you're getting an error, see this post), open the terminal or console and type 'python' and hit the 'Enter' key. You will then be directed immediately to the Python live interpreter. Your screen will display a message something like:
+user@hostname:~ python +Python 3.3.0 (default, Nov 23 2012, 10:26:01) +[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> +
The Python programmer should keep in mind one thing: that while working with the live interpreter, everything is read and interpreted in real-time. For example loops iterate immediately, unless they are part of function. So it requires some mental planning. Using the Python shell is typically used to execute code interactively. If you want to run a Python script from the interpreter, you must either import it or call the Python executable.
+++Source:
+
+ http://pythoncentral.io/execute-python-script-file-shell/
Type the following text into a single file named ex1.py. Python works best with files ending in .py.
+print "Hello World!" +print "Hello Again" +print "I like typing this." +print "This is fun." +print 'Yay! Printing.' +print "I'd much rather you 'not'." +print 'I "said" do not touch this.' +
Your Atom text editor should look something like this on all platforms:
+Don't worry if your editor doesn't look exactly the same, it should be close though. You may have a slightly different window header, maybe slightly different colors, and the left side of your Atom window won't say "zedshaw" but will instead show the directory you used for saving your files. All of those differences are fine.
+When you create this file, keep in mind these points:
+In Terminal run the file by typing:
+python ex1.py +
If you did it right then you should see the same output as I in the What You Should See section of this exercise. If not, you have done something wrong. No, the computer is not wrong.
+On Mac OS X in the Terminal you should see this:
+
+On Windows in PowerShell you should see this:
+
You may see different names, before the python ex1.py command, but the important part is that you type the command and see the output is the same as mine.
+ + +If you have an error it will look like this:
+$ python ex/ex1.py + File "ex/ex1.py", line 3 + print "I like typing this. + ^ +SyntaxError: EOL while scanning string literal +
It's important that you can read these error messages because you will be making many of these mistakes. Even I make many of these mistakes. Let's look at this line by line.
+++Source:
+
+ LEARN PYTHON THE HARD WAY by Zed A. Shaw - 2013
Programming is error-prone. For whimsical reasons, programming errors are called +bugs and the process of tracking them down is called debugging. +Three kinds of errors can occur in a program: syntax errors, runtime errors, and se +mantic errors. It is useful to distinguish between them in order to track them down more +quickly.
+Python can only execute a program if the syntax is correct; otherwise, the interpreter +displays an error message. Syntax refers to the structure of a program and the rules +about that structure.For example, parentheses have to come in matching pairs, so +(1 + 2) is legal, but 8) is a syntax error. +In English readers can tolerate most syntax errors, which is why we can read the poetry +of e. e. cummings without spewing error messages. Python is not so forgiving. If there +is a single syntax error anywhere in your program, Python will display an error message +and quit, and you will not be able to run your program. During the first few weeks of +your programming career, you will probably spend a lot of time tracking down syntax +errors. As you gain experience, you will make fewer errors and find them faster.
+The second type of error is a runtime error, so called because the error does not appear +until after the program has started running. These errors are also called exceptions +because they usually indicate that something exceptional (and bad) has happened. +Runtime errors are rare in the simple programs you will see in the first few chapters, so +it might be a while before you encounter one.
+The third type of error is the semantic error. If there is a semantic error in your program, +it will run successfully in the sense that the computer will not generate any error mess +ages, but it will not do the right thing. It will do something else. Specifically, it will do +what you told it to do. +The problem is that the program you wrote is not the program you wanted to write. The +meaning of the program (its semantics) is wrong. Identifying semantic errors can be +tricky because it requires you to work backward by looking at the output of the program +and trying to figure out what it is doing.
+++Source:
+
+ Think Python by Allen B. Downey - 2012
The following list shows the Python keywords. These are reserved words and you cannot use them as constants or variables or any other identifier names. All the Python keywords contain lowercase letters only.
+++ + + + + + + +Source:
+
+ https://www.tutorialspoint.com
Variables are named locations which are used to store references to the object stored in memory. The names we choose for variables and functions are commonly known as Identifiers. In python Identifiers must obey the following rules.
+Identifier can’t be a keyword (keywords are reserved words that + Python uses for special purpose).Following are Keywords in python 3.
+Values are basic things that programs works with. For e.g 1 , 11 , 3.14 , "hello" are all values. In programming terminology they are also commonly known as literals. Literals can be of different type for e.g 1 , 11 are of type int , 3.14 is float and "hello" is string . Remember in python everything is object even basic data types like int, float, string, we will elaborate more on this in later chapters.
+In python you don’t need to declare types of variable ahead of time. Interpreter automatically detects the type of the variable by the data it contains. To assign value to a variable equal sign ( = ) is used. = is also known as assignment operator.
+Following are some examples of variable declaration:
+x = 100 # x is integer +pi = 3.14 # pi is float +empname = "python is great" # empname is string + +a = b = c = 100 # this statement assign 100 to c, b and a. +
++Note: +In the above code x stores reference to the 100 ( which is an int object ) , x don’t store 100 itself.
+
In Python comments are preceded by a pound sign ( # ). Comments are not programming statements that python interpreter executes while running the program. Comments are used by programmers to remind themselves how the program works. They are also used to write program documentation.
+#display hello world +print("hello world") +
Python allow simultaneous assignment syntax like this:
+var1, var2, ..., varn = exp1, exp2, ..., expn +
this statements tells the python to evaluate all the expression on the right and assign them to the corresponding variables on the left. Simultaneous Assignments is helpful to swap values of two variables. For e.g
+>>> x = 1 +>>> y = 2 + +>>> y, x = x, y # assign y value to x and x value to y +
Python has 5 standard data types namely.
+a) Numbers
+b) String
+c) List
+d) Tuple
+e) Dictionary
+f) Boolean – In Python True and False are boolean literals. But the following values are also considered as false.
[] – empty list , () – empty tuple , {} – empty dictionary
+input() function is used to receive input from the console.
+Syntax: input([prompt]) -> string
+input() function accepts an optional string argument called prompt and returns a string.
+>>> name = input("Enter your name: ") +>>> Enter your name: tim +>>> name +'tim' +
Note that input() returns string even if you enter a number, to convert it to an integer you can use int() or eval() .
+>> age = int(input("Enter your age: ")) +Enter your age: 22 +>>> age +22 +>>> type(age) +<class 'int'> +
++Source:
+
+ http://thepythonguru.com
Have you ever noticed any difference between variables in Python and C? For example, when you do an assignment like the following in C, it actually creates a block of memory space so that it can hold the value for that variable
+int a = 1; +
You can think of it as putting the value assigned in a box with the variable name as shown below.
+
And for all the variables you create a new box is created with the variable name to hold the value. If you change the value of the variable the box will be updated with the new value. That means doing
+a = 2; +
will result in
+
Assigning one variable to another makes a copy of the value and put that value in the new box.
+int b = a; +

But in Python variables work more like tags unlike the boxes you have seen before. When you do an assignment in Python, it tags the value with the variable name.
+a = 1 +

and if you change the value of the varaible, it just changes the tag to the new value in memory. You dont need to do the housekeeping job of freeing the memory here. Python's Automatic Garbage Collection does it for you. When a value is without names/tags it is automatically removed from memory.
+a = 2 +

Assigning one variable to another makes a new tag bound to the same value as show below.
+b = a +

+Other languages have 'variables'. Python has 'names'.
As you have seen before, a value will have only one copy in memory and all the variables having this value will refer to this memory location. For example when you have variables a, b, c having a value 10, it doesn't mean that there will be 3 copy of 10s in memory. There will be only one 10 and all the variables a, b, c will point to this value. Once a variable is updated, say you are doing a += 1 a new value 11 will be allocated in memory and a will be pointing to this.
+Let's check this behaviour with Python Interpreter. Start the Python Shell and try the following for yourselves.
+>>> a = 10 +>>> b = 10 +>>> c = 10 +>>> id(a), id(b), id(c) +(140621897573616, 140621897573616, 140621897573616) +>>> a += 1 +>>> id(a) +140621897573592 +
id() will return an objects memory address (object's identity). As you have noticed, when you assign the same integer value to the variables, we see the same ids. But this assumption does not hold true all the time. See the following for example
+>>> x = 500 +>>> y = 500 +>>> id(x) +4338740848 +>>> id(y) +4338741040 +
What happened here? Even after assigning the same integer values to different variable names, we are getting two different ids here. These are actually the effects of CPython optimization we are observing here. CPython implementation keeps an array of integer objects for all integers between -5 and 256. So when we create an integer in that range, they simply back reference to the existing object. You may refer the following links for more information.
+Let's take a look at strings now.
+>>> s1 = 'hello' +>>> s2 = 'hello' +>>> id(s1), id(s2) +(4454725888, 4454725888) +>>> s1 == s2 +True +>>> s1 is s2 +True +>>> s3 = 'hello, world!' +>>> s4 = 'hello, world!' +>>> id(s3), id(s4) +(4454721608, 4454721664) +>>> s3 == s4 +True +>>> s3 is s4 +False +
Looks interesting, isn't it? When the string was a simple and shorter one the variable names where referring to the same object in memory. But when they became bigger, this was not the case. This is called interning, and Python does interning (to some extent) of shorter string literals (as in s1 and s2) which are created at compile time. But in general, Python string literals creates a new string object each time (as in s3 and s4). Interning is runtime dependant and is always a trade-off between memory use and the cost of checking if you are creating the same string. There's a built-in intern() function to forcefully apply interning. Read more about interning from the following links.
+Stack Overflow: Does Python intern Strings? +Stack Overflow: Python String Interning +Internals of Python String Interning
+++Source:
+
+ http://foobarnbaz.com/2012/07/08/understanding-python-variables/
In this article, we will take a deep look at three kinds of assignment statements in Python and discuss what’s going on under the hood.
+>>> my_string = "Hello World" # right hand side is a simple expression +>>> another_string = my_string # right hand side is another variable +>>> another_string = another_string + "!" # right hand side is an operation +
What we find may surprise you.
+What happens when the right hand side is a simple expression?
+>>> my_string = "Hello World" +
In simple terms, this creates a string “Hello World” in memory and assigns the name my_string to it. If you are using CPython[1], then we can even check the memory address explicitly by using the built in function id .
+>>> my_string = “Hello World” +>>> id(my_string) +140400709562064 +
That big number 140400709562064 denotes where the data lives in the memory. It will be very useful for us in this entire discussion. +What happens if we create another string with the same value?
+>>> another_string = “Hello World” +
Does it reuse the previous “Hello World” stored in memory or does it create an independent copy? Let’s check this by querying the id function again.
+>>> id(another_string) +140400709562208 +
This outputs a different id, so this must be an independent copy. We conclude that:
+++Note: +Assignment statements where the right hand side is a simple expression creates independent copies every time.
+
While for everyday programming, this is the rule we should remember, there are actually some weird exceptions to this rule. Here’s an example.
+>>> my_string = “hello” +>>> id(my_string) +140400709562016 +>>> another_string = “hello” +>>> id(another_string) +140400709562016 +
In this case, two consecutive assignment statements did not create independent copies. Why? +It gets interesting now. +For optimizing memory, Python treats a special set of objects differently. The string “hello” belongs to this privileged set and has a different behavior. The exact set depends on the implementation like CPython, PyPy, Jython or IronPython. For CPython, the special rule applies to:
+These objects are always reused or interned. The rationale behind doing this is as follows:
+However, Python does not do this for all immutable objects because there is a runtime cost involved for this feature. For interning an object, it must first search for the object in memory, and searching takes time. This is why the special treatment only applies for small integers and strings, because finding them is not that costly.
+What happens when the right hand side is an existing Python variable? +Let’s move on to the second type of assignment statement where the right hand side is an existing Python variable.
+>>> another_string = my_string +
In this case, nothing is created in memory. After the assignment, both variables refer to the already existing object. It’s basically like giving the object an additional nickname or alias. Let’s confirm this by using the id function.
+>>> my_string = “Hello World” +>>> id(my_string) +140400709562160 +>>> another_string = my_string +>>> id(another_string) +140400709562160 +
The natural question at this stage is : what if, instead of just giving the existing object an alias, we wanted to create an independent copy? +For mutable objects, this is possible. You can either use the copy module of Python (which works on all objects) or you may use copy methods specific to the class. For a list, you have several possibilities for creating copies, all of which have different runtime.
+>>> my_list = [1, 2, 3] +>>> copy_of_my_list = my_list.copy() # fastest, works only on latest Python versions +>>> copy_of_my_list = my_list[:] # same runtime as List.copy() +>>> copy_of_my_list = list(my_list) # slightly slower +>>> import copy +>>> copy_of_my_list = copy.copy(my_list) # slowest +
How can you copy an immutable object? Well…you can’t! At least not in a straightforward way. If you try to use the copy module or the slicing notation, you will get back the same object and not an independent copy. Here’s proof.
+# Standard ways of copying lists do not apply for tuples + +>>> my_tuple = (1, 2, 3) +>>> id(my_tuple) +140371873244816 +>>> another_tuple = my_tuple[:] +>>> id(another_tuple) +140371873244816 + +# The copy module also doesn’t help + +>>> import copy +>>> another_tuple = copy.copy(my_tuple) +>>> id(another_tuple) +140371873244816 +
More importantly, there is no reason for explicitly copying an immutable object anyway. We will see why in a moment when we discuss the third kind of assignment statement. +What happpens when the right hand side is an operation?
+In this case, what happens depends on the result of the operation. We will discuss two simple cases:
+Let’s start with the case of the tuple.
+>>> another_tuple += (4,) +
When you add a new element to a tuple using another_tuple += (4,), this creates a new object in memory. The immutability of tuples is key to understanding this. Since tuples are immutable, any operation that leads to a changed tuple would result in an independent copy. +This is the reason why you don’t need to explicitly copy immutable objects : it happens automatically under the hood. Here’s an example.
+>>> my_tuple = (1, 2, 3) +>>> another_tuple = my_tuple # both variables point to the same object +>>> another_tuple += (4,) # this statement creates a new independent object +>>> print(another_tuple) +(1, 2, 3, 4) +>>> print(my_tuple) # the old one remains unharmed +(1, 2, 3) +
The situation is much different for mutable objects and much more confusing. Let’s try the same example, but now for lists.
+>>> my_list = [1, 2, 3] +>>> another_list = my_list # both variables point to the same object +>>> another_list += [4,] # this statement modifies the object in place +>>> print(another_list) +[1, 2, 3, 4] +>>> print(my_list) # the original list is modified +[1, 2, 3, 4] +
Mutable objects can be modified in place. Some operations modify the list in place and some operations don’t. In this case, the statement another_list += [4,] calls another_list.iadd([4,]) and iadd modifies the existing object in place. +To make things doubly confusing, we would have completely different results if we used a slightly different notation.
+>>> my_list = [1, 2, 3] +>>> another_list = my_list # both variables point to the same object +>>> another_list = another_list + [4,] # this creates an independent copy +>>> print(another_list) +[1, 2, 3, 4] +>>> print(my_list) # the original list is unharmed +[1, 2, 3] +
Woah! What’s going on? What changed? +It turns out that when we change the third line, Python now internally calls a different function another_list.add([4,]) instead of iadd. This function returns a new copy instead of modifying the list in place. +To prevent this confusion, it is always better to create a true copy of the list if you wish to prevent modification to the original. +Let’s remember the list copy methods from before. They were List.copy(), [:], list() and copy.copy(). This is what we should use.
+>>> my_list = [1, 2, 3] +>>> another_list = my_list.copy() # this creates an independent copy +>>> another_list += [4,] # this statement modifies the independent copy +>>> print(another_list) +[1, 2, 3, 4] +>>> print(my_list) # the original list is unharmed +[1, 2, 3] +
There’s one last gotcha that can happen when copying lists. +Suppose we have a list that has a nested list inside it. We copy this list using List.copy() and then modify the nested list. Unfortunately, this will modify the original list again!
+>>> my_list = [[1, 2, 3], 4, 5] +>>> another_list = my_list.copy() +>>> another_list[0] += [6,] +>>> print(another_list) +[[1, 2, 3, 6], 4, 5] +>>> print(my_list) +[[1, 2, 3, 6], 4, 5] +
Why did that happen? Didn’t we just copy the original list? +The truth is : we actually don’t have a completely independent copy in this case. The copy() function generates a shallow copy. To see what it does, let’s look at the ids of all the elements in my_list and the ids of all the elements in the copied list.
+# for my_list + +>>> my_list = [[1, 2, 3], 4, 5] +>>> id(my_list) +140371873277424 +>>> print([id(x) for x in my_list]) +[140371873599288, 13820176, 13820152] + +# for another_list obtained by my_list.copy() + +>>> id(another_list) +140371873317016 +>>> print([id(x) for x in another_list]) +[140371873599288, 13820176, 13820152] +
We see the ids of my_list and another_list are indeed different, indicating another_list is a copy. But the ids of the elements contained in another_list have the same ids as the elements in my_list . So the elements have not been copied! +This is the property of shallow copy. It creates a new copy of the object but reuses the attributes and elements of the old copy. Thus, when you modify the elements of the new copy, you are modifying the elements of the old copy too. +To solve this problem, we need to copy an object along with all its attributes and elements. This can be achieved by copy.deepcopy.
+>>> my_list = [[1, 2, 3], 4, 5] +>>> another_list = copy.deepcopy(my_list) +>>> another_list[0] += [6,] +>>> another_list +[[1, 2, 3, 6], 4, 5] +>>> my_list +[[1, 2, 3], 4, 5] +
Deep copy is a quite time intensive operation and can take 1o times longer to complete compared to a shallow copy. But in some situations, it is unavoidable.
+This brings me to the end of this discussion. To summarize, we have talked about the different scenarios which can arise in an assignment statement in Python. We found that:
+++ + + + + + + +Source:
+
+ https://medium.com/broken-window/many-names-one-memory-address-122f78734cb6
For full documentation visit mkdocs.org.
-mkdocs new [dir-name] - Create a new project.mkdocs serve - Start the live-reloading docs server.mkdocs build - Build the documentation site.mkdocs help - Print this help message.mkdocs new [dir-name] - Create a new project.mkdocs serve - Start the live-reloading docs server.mkdocs build - Build the documentation site.mkdocs help - Print this help message.mkdocs new [dir-name] - Create a new project.mkdocs serve - Start the live-reloading docs server.mkdocs build - Build the documentation site.mkdocs help - Print this help message.mkdocs.yml # The configuration file.
-docs/
- index.md # The documentation homepage.
- ... # Other markdown pages, images and other files.
-In this repository I want to share resources, that helped me understand python programing language deeply. +It was not easy to find appropriate books, articles, answers from Stackoverflow, online courses, videos from py conferences and etc.
+So, after all I decided to share top resources for everyone about each topic, that you need to know about python, if you want to be senior python Software Engineer.
+Of course, it needs plenty of time to organize best resources based on the topics and it's hard for me to do it every day, but I want to do min 1 chapter each week and now I think, that there will be more than 30-40 chapters.
+| t |