Best Python Code Examples
31 DECEMBER 2019
Last updated
31 DECEMBER 2019
Last updated
Python is a general purpose programming language which is dynamically typed, interpreted, and known for its easy readability with great design principles.
freeCodeCamp has one of the most popular courses on Python. It's completely free (and doesn't even have any advertisements). You can watch it on YouTube here.
Some general information about floating point numbers and how they work in Python, can be found here.
Nearly all implementations of Python follow the IEEE 754 specification: Standard for Binary Floating-Point Arithmetic. More information found on the IEEE site.
Float objects can be created using floating point literals:
Numeric literals do not contain a sign, however creating negative float objects is possible by prefixing with a unary -
(minus) operator with no space before the literal:
Likewise, positive float objects can be prefixed with a unary +
(plus) operator with no space before the literal. Usually +
is omitted:
Note that leading and trailing zero(s) are valid for floating point literals.
Likewise, positive float objects can be prefixed with a unary +
(plus) operator with no space before the literal. Usually +
is omitted:
Note that leading and trailing zero(s) are valid for floating point literals.
The float
constructor is another way to create float
objects.
Creating float
objects with floating point literals is preferred when possible:
However, the float constructor allows for creating float objects from other number types:
The float
constructor will also make float
objects from strings that represent number literals:
The float
constructor can also be used to make numeric representations of NaN
(Not a Number), negative infinity
and infinity
(note that strings for these are case insensitive):
bool()
is a built-in function in Python 3. This function returns a Boolean value, i.e. True or False. It takes one argument, x
.
It takes one argument, x
. x
is converted using the standard Truth Testing Procedure.
If x
is false or omitted, this returns False
; otherwise it returns True
.
Python Docs - Boolean Operations
These are the Boolean operations, ordered by ascending priority:
OperationResultNotes x or y if x is false, then y, else x (1) x and y if x is false, then x, else y (2) not x if x is false, then True, else False (3).
Notes:
This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.
not
:and
:or
:Three commonly used built-in constants:
True
: The true value of the bool type. Assignments to True
raise a SyntaxError.
False
: The false value of the bool type. Assignments to False
raise a SyntaxError.
None
: The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None
raise a SyntaxError.
Other built-in constants:
NotImplemented
: Special value which should be returned by the binary special methods, such as __eg__()
, __add__()
, __rsub__()
, etc.) to indicate that the operation is not implemented with respect to the other type.
Ellipsis
: Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
__debug__
: True if Python was not started with an -o option.
Constants added by the site module. The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
Objects that, when printed, print a message like âUse quit() or Ctrl-D (i.e. EOF) to exitâ, and when called, raise SystemExit with the specified exit code:
quit(code=None)
exit(code=None)
Objects that, when printed, print a message like âType license() to see the full license textâ, and when called, display the corresponding text in a pager-like fashion (one screen at a time):
copyright
license
credits
A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table.
On the other hand, variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called. In this way, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.
The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:
Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.
Compared with other programming languages, Pythonâs class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++.
Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.
Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.
Class Definition Syntax :
The simplest form of class definition looks like this:
Class Objects:
Class objects support two kinds of operations: attribute references and instantiation.
Attribute references use the standard syntax used for all attribute references in Python: obj.name
. Valid attribute names are all the names that were in the classâs namespace when the class object was created. So, if the class definition looked like this:
Then MyClass.i
and MyClass.f
are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i
by assignment. __doc__
is also a valid attribute, returning the docstring belonging to the class: "A simple example class"
.
Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):
Creates a new instance of the class and assigns this object to the local variable x.
The instantiation operation (âcallingâ a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named init(), like this:
When a class defines an __init__()
method, class instantiation automatically invokes __init__()
for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:
Of course, the __init__()
method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__()
. For example,
It is generally good practice for you not to mix tabs and spaces when coding in Python. Doing this can possibly cause a TabError
, and your program will crash. Be consistent when you code - choose either to indent using tabs or spaces and follow your chosen convention throughout your program.
Code Blocks and Indentation
One of the most distinctive features of Python is its use of indentation to mark blocks of code. Consider the if-statement from our simple password-checking program:
The lines print(âLogging on âĶâ) and print(âIncorrect password.â) are two separate code blocks. These happen to be only a single line long, but Python lets you write code blocks consisting of any number of statements.
To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.
In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to. For instance, the final print(âAll done!â) is not indented, and so is not part of the else-block.
Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.
If/elif-statements
An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions. For example, suppose an airline has the following âchildâ ticket rates: Kids 2 years old or younger fly for free, kids older than 2 but younger than 13 pay a discounted child fare, and anyone 13 years or older pays a regular adult fare. The following program determines how much a passenger should pay:
After Python gets age from the user, it enters the if/elif-statement and checks each condition one after the other in the order they are given.
So first it checks if age is less than 2, and if so, it indicates that the flying is free and jumps out of the elif-condition. If age is not less than 2, then it checks the next elif-condition to see if age is between 2 and 13. If so, it prints the appropriate message and jumps out of the if/elif-statement. If neither the if-condition nor the elif-condition is True, then it executes the code in the else-block.
Conditional expressions
Python has one more logical operator that some programmers like (and some donât!). Itâs essentially a shorthand notation for if-statements that can be used directly within expressions. Consider this code:
The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either âyuckâ or âyumâ. Itâs equivalent to the following:
Conditional expressions are usually shorter than the corresponding if/else-statements, although not quite as flexible or easy to read. In general, you should use them when they make your code simpler.
There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z
is equivalent to x < y and y <= z
, except that y
is evaluated only once (but in both cases z
is not evaluated at all when x < y
is found to be false).
The following summarizes the comparison operations:
OperationMeaning<
strictly less than<=
less than or equal to>
strictly greater than>=
greater than or equal to==
equal to!=
not equal to is
object identity is not
negated object identity
Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The <
, <=
, >
and >=
operators will raise a TypeError
exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.
Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__()
method.
Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __lt__()
, __le__()
, __gt__()
, and __ge__()
(in general, __lt__()
and __eq__()
are sufficient, if you want the conventional meanings of the comparison operators).
The behavior of the is
and is not
operators cannot be customized; also they can be applied to any two objects and never raise an exception.
We can also chain <
and >
operators together. For instance, 3 < 4 < 5
will return True
, but 3 < 4 > 5
will not. We can also chain the equality operator. For instance, 3 == 3 < 5
will return True
but 3 == 5 < 5
will not.
In Python, there are two comparison operators which allow us to check to see if two objects are equal. The is
operator and the ==
operator. However, there is a key difference between them!
The key difference between âisâ and â==â can be summed up as:
is
is used to compare identity
==
is used to compare equality
First, create a list in Python.
Next, create a copy of that list.
If we use the â==â operator or the âisâ operator, both will result in a True output.
This is because both myListA and myListB are pointing to the same list variable, which I defined at beginning of my Python program. Both lists are exactly the same, both in identity and in content.
However, what if I now create a new list?
Performing the ==
operator still shows that both lists are the same, in terms of content.
However, performing the is
operator will now produce a False
output. This is because myListA and myListC are two different variables, despite containing the same data. Even though they look the same, they are different.
To sum up:
An is
expression outputs True
if both variables are pointing to the same reference
An ==
expression outputs True
if both variables contain the same data
A Dictionary (a.k.a âdictâ) in python is a built-in datatype that can be used to store key-value
pairs. This allows you to treat a dict
like itâs a database to store and organize data.
The special thing about dictionaries is the way they are implemented. Hash-table-like structure makes it easy to check for existence - which means that we can easily determine if a specific key is present in the dictionary without needing to examine every element. The Python interpreter can just go to the location key and check if the key is there.
Dictionaries can use almost any arbitrary datatypes, like strings, integers etc, for keys. However, values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1
and 1.0
) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)
One most important requirement of a dictionary is that the keys must be unique.
To create an empty dictionary just use a pair of braces:
To create a non-empty dictionary with some initial values, place a comma-seperated list of key-value pairs:
Itâs easy to add key-value pairs to an existing dictionary:
del
operator is used to delete a key-value pair from the dict. In scenarios where a key thatâs already in use is again used to store values, the old value associated with that key is completely lost. Also, keep in mind that itâs an error to extract the value using a non-existent key.
in
keyword can be used to check whether a key exist in the dict or not:
keys
is a built-in method that can be used to get the keys of a given dictionary. To extract the keys present in a dict as lists:
Yet another way of creating a dictionary is using the dict()
method:
Dict comprehensions can be used as well to create dictionaries from arbitrary key and value expressions:
Looping in Dictionary To simply loop over the keys in the dictionary, rather than the keys and values:
To loop over both key and value, you can use the following: For Python 2.x:
Use items()
for Python 3.x:
In Python, everything is an object.
Objects represent a logical grouping of attributes. Attributes are data and/or functions. When an object is created in Python it is created with an identity, type, and value.
In other languages, primitives are values that have no properties (attributes). For example, in javascript undefined
, null
, boolean
, string
, number
, and symbol
(new in ECMAScript 2015) are primitives.
In Python, there are no primitives. None
, booleans, strings, numbers, and even functions are all objects regardless how they are created.
We can demonstrate this using some built-in functions:
Built-in constants None
, True
, and False
are objects:
We test the None
object here.
Next, letâs inspect True
.
No reason to leave out False
!
Strings, even when created by a string literals, are also objects.
Same with numbers.
In Python, functions are first class objects.
Functions in Python are also objects, created with an identity, type, and value. They too can be passed into other functions:
It is also possible to bind functions to a name and called the bound function using that name:
A tuple is a sequence of Python objects. Tuples are immutable which means they cannot be modified after creation, unlike lists.
Creation:
An empty tuple
is created using a pair of round brackets, ()
:
A tuple
with elements is created by separating the elements with commas (surrounding round brackets, ()
, are optional with exceptions):
A tuple
with a single element must have the trailing comma (with or without round brackets):
Round brackets are required in cases of ambiguity (if the tuple is part of a larger expression):
Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.
For example, f(a, b, c)
is a function call with three arguments, while f((a, b, c))
is a function call with a 3-tuple as the sole argument.
A tuple
can also be created with the tuple
constructor:
Accessing elements of a tuple
:
Elements of tuples
are accessed and indexed the same way that lists
are.
Zero indexed
Wrap around indexing
Packing and Unpacking:
The statement t = 12345, 54321, 'hello!'
is an example of tuple packing: the values 12345
, 54321
and 'hello!'
are packed together in a tuple. The reverse operation is also possible:
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
Immutable:
tuples
are immutable containers, guaranteeing which objects they contain will not change. It does not guarantee that the objects they contain will not change:
Uses:
Functions can only return a single value, however, a heterogenuous tuple
can be used to return multiple values from a function. One example is the built-in enumerate
function that returns an iterable of heterogeneous tuples
:
Decorators essentially work as wrappers. They modify the behaviour of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it.
Before going in detail about decorators, there are some concepts that should be clear. In Python, functions are objects and we can do a lot of useful stuff with them.
Output: Hello John
Output: Hello John
Output: Hello John
In other words, functions generating other functions.
Output: Hello there!
More commonly known as a closure. A very powerful pattern that we will come across while building decorators. Another thing to note, Python only allows read access to the outer scope and not assignment. Notice how we modified the example above to read a ânameâ argument from the enclosing scope of the inner function and return the new function.
Output: Hello there John!
Function decorators are simply wrappers to existing functions. Putting the ideas mentioned above together, we can build a decorator. In this example letâs consider a function that wraps the string output of another function by p tags.
Output: <p>
lorem ipsum, John dolor sit amet</p>
That was our first decorator. A function that takes another function as an argument, generates a new function, augmenting the work of the original function, and returning the generated function so we can use it anywhere. To have get_text
itself be decorated by p_decorate
, we just have to assign get text to the result of p decorate.
Output: lorem ipsum, John dolor sit amet
Another thing to notice is that our decorated function takes a name argument. All that we have to do in the decorator is to let the wrapper of get_text pass that argument.
Python makes creating and using decorators a bit cleaner and nicer for the programmer through some syntactic sugar. To decorate gettext we donât have to gettext = pdecorator(gettext). There is a neat shortcut for that, which is to mention the name of the decorating function before the function to be decorated. The name of the decorator should be perpended with an @ symbol.
Output: <p>
lorem ipsum, John dolor sit amet</p>
Now letâs consider we wanted to decorate our get_text function by 2 other functions to wrap a div and strong tag around the string output.
With the basic approach, decorating get_text would be along the lines of
With Pythonâs decorator syntax, the same thing can be achieved with much more expressive power.
Output: <div><p><strong>
lorem ipsum, John dolor sit amet</strong></p></div>
One important thing to notice here is that the order of setting our decorators matters. If the order was different in the example above, the output would have been different.
In Python, methods are functions that expect their first parameter to be a reference to the current object. We can build decorators for methods the same way, while taking self into consideration in the wrapper function.
Output: <p>
John Doe</p>
A much better approach would be to make our decorator useful for functions and methods alike. This can be done by putting *args and **kwargs as parameters for the wrapper, then it can accept any arbitrary number of arguments and keyword arguments.
Output : <p>
John Doe</p>
Looking back at the example before the one above, you can notice how redundant the decorators in the example are. 3 decorators (divdecorate, pdecorate, strong_decorate) each with the same functionality, but wrapping the string with different tags.
We can definitely do much better than that. Why not have a more general implementation for one that takes the tag to wrap with as a string? Yes please!
Output: <p>
Hello John</p>
It took a bit more work in this case. Decorators expect to receive a function as an argument, that is why we will have to build a function that takes those extra arguments and generate our decorator on the fly. In the example above, tags is our decorator generator.
At the end of the day, decorators are just wrapping our functions. In case of debugging, that can be problematic since the wrapper function does not carry the name, module and docstring of the original function. Based on the example above if we do:
Output: funcwrapper. The output was expected to be gettext yet, the attributes name, doc, and module of gettext got overridden by those of the wrapper(funcwrapper.
Obviously we can re-set them within func_wrapper but Python provides a much nicer way.
Functools to the rescue
You can notice from the output that the attributes of get_text are the correct ones now.
Python utilizes a for loop to iterate over a list of elements. This is unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.
For loops iterate over collection-based data structures like lists, tuples, and dictionaries.
The basic syntax is:
In general, you can use anything as the iterator value, where entries of the iterable can be assigned to. E.g. you can unpack tuples from a list of tuples:
On the other hand, you can loop over anything that is iterable. You can call a function or use a list literal.
Some ways in which For loops are used:
Iterate over the range() function
Rather than being a function, range is actually an immutable sequence type. The output will contain results from lower bound i.e 0 to the upper bound i.e 10, but excluding 10. By default the lower bound or the starting index is set to zero. Output:
Additionally, one can specify the lower bound of the sequence and even the step of the sequence by adding a second and a third parameter.
Output:
xrange() function
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. It means that xrange doesnât actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.
One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x
Iterate over values in a list or tuple
Output:
Iterate over keys in a dictionary (aka hashmap)
Output:
Iterate over two lists of same size in a single loop with the zip() function
Output:
Iterate over a list and get the corresponding index with the enumerate() function
Output:
A common use case is iterating over a dictionary:
If you absolutely need to access the current index of your iteration, do NOT use range(len(iterable))
! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function enumerate()
instead:
for/else statements Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of break
statement so that we can break out of the loop on a satisfied condition. If we do not break out then the else part will be executed.
In the above case the output will be today is not a week day
since the break within the loop will never be executed.
Iterate over a list using inline loop function
We could also iterate inline using python. For example if we need to uppercase all the words in a list from a list, we could simply do the following:
Output:
A function allows you to define a reusable block of code that can be executed many times within your program.
Functions allow you to create more modular and DRY solutions to complex problems.
While Python already provides many built-in functions such as print()
and len()
, you can also define your own functions to use within your projects.
One of the great advantages of using functions in your code is that it reduces the overall number of lines of code in your project.
In Python, a function definition has the following features:
The keyword def
a function name
parenthesesâ()â, and within parentheses input parameters, although the input parameters are optional.
a colon â:â
some block of code to execute
a return statement (optional)
Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code more readable, easier to debug, and limits typing errors.
Functions in Python are created using the def
keyword, followed by a function name and function parameters inside parentheses.
A function always returns a value. The return
keyword is used by the function to return a value. If you donât want to return any value, the default value None
will be returned.
The function name is used to call the function, passing the needed parameters inside parentheses.
You can define default values for the parameters, and that way Python will interpret that the value of that parameter is the default one if none is given.
You can pass the parameters in the order you want, using the name of the parameter.
However, it is not possible to pass a keyword argument before a non-keyword one.
Functions are also Objects, so you can assign them to a variable, and use that variable like a function.
If a function definition includes parameters, you must provide the same number of parameters when you call the function.
The block of code that the function will run includes all statements indented within the function.
Variables defined within a function only exist within the scope of that function.
Python interprets the function block only when the function is called and not when the function is defined. So even if the function definition block contains some sort of error, the python interpreter will point that out only when the function is called.
Generators are a special type of function that allows you to return values without ending a function. It does this by using the yield
keyword. Similar to return
, the yield
expression will return a value to the caller. The key difference between the two is that yield
will suspend the function, allowing for more values to be returned in the future.
Generators are iterable so they can be used cleanly with for loops or anything else that iterates.
Like other iterators, generators can be passed to the next
function to retrieve the next item. When a generator has no more values to yield, a StopIteration
error is raised.
Generators are particularly useful when you need to create a large set of values but do not need to keep them all in memory at the same time. For example, if you need to print the first million fibonacci numbers, you would typically return a list of a million values and iterate over the list to print each value. However with a generator, you can return each value one at a time:
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.
Iteration is the process of programmatically repeating a step a given number of times. A programmer can make use of iteration to perform the same operation on every item in a collection of data, for example printing out every item in a list.
Objects can implement a __iter__()
method that returns an iterator object to support iteration.
Iterator objects must implement:
__iter__()
: returns the iterator object.
__next__()
: returns the next object of the container.iteratorobject = âabcâ.iter() print(iteratorobject) print(id(iteratorobject)) print(id(iteratorobject.iter())) # Returns the iterator itself. print(iteratorobject.next()) # Returns 1st object and advances iterator. print(iteratorobject.next()) # Returns 2nd object and advances iterator. print(iteratorobject.next()) # Returns 3rd object and advances iterator. print(iteratorobject.next()) # Raises StopIteration Exception.
Output :
Ternary operations in Python, often also referred to as conditional expressions, allow the programmer to perform an evaluation and return a value based on the truth of the given condition.
The ternary operator differs from a standard if
, else
, elif
structure in the sense that it is not a control flow structure, and behaves more like other operators such as ==
or !=
in the Python language.
In this example, the string Even
is returned if the val
variable is even, otherwise the string Odd
is returned. The returned string is then assigned to the is_even
variable and printed to the console.
Input
Output
Python utilizes the while
loop similarly to other popular languages. The while
loop evaluates a condition then executes a block of code if the condition is true. The block of code executes repeatedly until the condition becomes false.
The basic syntax is:
An example is shown below:
Output:
Line-by-Line explanation of the above CODE:
the variable âdaysâ is set to a value 0.
a variable week is assigned to a list containing all the days of the week.
while loop starts
the block of code will be executed until the condition returns âtrueâ.
the condition is âdays<7â which roughly says run the while loop until the point the variable days is less than 7
So when the days=7 the while loop stops executing.
the days variable gets updated on every iteration.
When the while loop runs for the first time, the line âToday is Mondayâ is printed onto the console and the variable days becomes equal to 1.
Since the variable days is equal to 1 which is less than 7, the while loop is executed again.
It goes on again and again and when the console prints âToday is Sundayâ the variable days is now equal to 7 and the while loop stops executing.
You can download Python from this official link. Based on your OS (Windows or Linux or OSX), you might want to install Python 3 following these instructions.
It is always a great idea to sandbox your Python installation and keep it separate from your System Python. The System Python is the path to Python interpreter, which is used by other modules installed along with your OS.
Itâs not safe to install Python Web-frameworks or libraries directly using System Python. Instead, you can use Virtualenv to create and spawn a separate Python process when you are developing Python applications.
The Virtualenvwrapper module makes it easy for you to manage and sandbox multiple Python sandboxed environments in one machine, without corrupting any modules or services written in Python and used by your machine.
Of course, most cloud hosted development environments such as Nitrous or Cloud9 also come with these pre-installed and ready for you to get coding! You can quickly pick a box from your dashboard and start coding after activating a Python 3 environment.
In Cloud9, you need to select the Django box while creating a new development environment.
A few shell command examples follow. If you wish to copy-paste, do note that the $
sign is a shorthand for the terminal prompt, itâs not part of the command. My terminal prompt looks something like this:
And, an ls
would look like
But, while writing the same in this documentation, I would be writing it as
Getting back to our discussion, you can create a Python 3 interpreter-included sandbox on Cloud9 by running on your cloud terminal:
You have to run it only once after creating a new box for your project. Once executed, this command would create a new sandboxed virtualenv ready for you to use, named py3
.
To view available virtual environments, you can use
To activate py3
, you can use the workon
command with the name of the environment:
All three terminal commands above would also work on local Linux machines or OSX machines. These are virtualenvwrapper commands; so if you are planning on using them, make sure you have this module installed and added to PATH
variable.
If you are inside a virtual environment; you can easily find that out by checking your terminal prompt. The environment name will be clearly shown in your terminal prompt.
For instance, when I am inside the py3
environment, I will be seeing this as my terminal prompt:
Notice the (py3)
in braces! If for some reason you are not seeing this, even if you are inside a virtual env; you can try doing one of the things mentioned here.
To get out of a virtual environment or to deactivate one - use this command:
Again, this works only with virtualenvwrapper module.
An alternative to using virtualenvwrapper is Pipenv. It automatically creates virtual environments for your projects, and maintains a Pipfile
which contains the dependencies. Using Pipenv means you no longer need to use pip and virtualenv separately, or manage your own requirements.txt
file. For those familiar with JavaScript, Pipenv is similar to using a packaging tool like npm
.
To get started with Pipenv, you can follow this very detailed guide. Pipenv makes it easy to specify which version of Python you wish to use for each project, import from an existing requirements.txt
file and graph your dependencies.
Reference : https://www.freecodecamp.org/news/python-example/