About
Getting started with Python LanguageLanguage
Getting Started
On Unix-based (including Mac) systems, you can open it from the shell by typing $ idle python_file.py. For example, if you have the file in your home directory and your user is "user" on Linux, you can type python /home/user/hello.py.
Creating variables and assigning values
Python tutor allows you to step through the Python code so you can visualize how the program will flow and helps you understand where your program went wrong. Finally, variables in Python don't have to remain the same type they were first defined - you can simply use .
Block Indentation
When configuring the editor, one must distinguish between the tab character ('\t') and the Tab key. The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases where (accidental) mixed indentation is possible.
Datatypes
In python, we can check the data type of an object using the built-in function type. For example, '123' is of type str and can be converted to an integer using the int function.
Collection Types
The elements of a list can be accessed via an index or numerical representation of their position. So the values in the tuple cannot be changed, nor can values be added to or removed from the tuple.
IDLE - Python GUI
When using multiple versions of Python on the same computer, a possible solution is to rename one of the python.exe files. The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for Python 3.x and python2 for Python 2.x.
User Input
Built in Modules and Functions
To know all the functions in a module, we can assign the function list to a variable and then print the variable. For each user-defined type, the attributes, the class's attributes, and recursively the class's base class attributes can be retrieved using dir().
Creating a module
If a module is inside a directory and python needs to detect it, the directory must contain a file named __init__.py.
Installation of Python 2.7.x and 3.x
As we speak, macOS comes installed with Python 2.7.10, but this version is outdated and slightly modified from the regular Python. The version of Python that ships with OS X is great for learning, but it's not good for development.
String function - str() and repr()
The version included with OS Otherwise, the representation is a string in angle brackets that contains the name of the object type along with additional information.
Installing external modules using pip
Using pip only installs packages for Python 2 and pip3 only installs packages for Python 3. When new versions of installed packages appear, they are not automatically installed on your system.
Help Utility
Python Data Types
String Data Type
Set Data Types
Numbers data type
List Data Type
Dictionary Data Type
Tuple Data Type
Indentation
Simple example
How Indentation is Parsed
Indentation Errors
Comments and Documentation
Single line, inline and multiline comments
Programmatically accessing docstrings
Write documentation using docstrings
The value of the docstring can be accessed within the program and is used, for example, by the help command. Note PEP 257 defines what information must be given in a document string, it does not define in what format it must be given.
Date and Time
Parsing a string into a timezone aware datetime objectobject
Constructing timezone-aware datetimes
For daylight saving time zones, Python's standard libraries do not provide a default class, so it is necessary to use a third-party library. In addition to static time zones, dateutil provides time zone classes that use daylight saving time (see the documentation for the tz module).
Computing time dierences
Basic datetime objects usage
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.date' However, it is easy to convert between types.
Switching between time zones
Simple date arithmetic
Converting timestamp to datetime
Subtracting months from a date accurately
Parsing an arbitrary ISO 8601 timestamp with minimal librariesminimal libraries
Get an ISO 8601 timestamp
Parsing a string with a short time zone name into
Fuzzy datetime parsing (extracting datetime out of a text)of a text)
Iterate over dates
Date Formatting
Time between two date-times
Outputting datetime object to string
Parsing string to datetime object
Enum
Creating an enum (Python 2.4 through 3.3)
Iteration
Operations on sets
Get the unique elements of a list
Set of Sets
Set Operations using Methods and Builtins
Sets versus multisets
Counter is a dictionary where elements are stored as dictionary keys and their counts are stored as dictionary values.
Simple Mathematical Operators
Division
Addition
Exponentiation
Trigonometric Functions
Inplace Operations
Subtraction
Multiplication
Logarithms
Modulus
Bitwise Operators
Bitwise NOT
Bitwise XOR (Exclusive OR)
Bitwise AND
Bitwise OR
Bitwise Left Shift
Bitwise Right Shift
Inplace Operations
Boolean Operators
A simple example
Short-circuit evaluation
Evaluates to the second argument if and only if both arguments are true. The 1's in the above example can be changed to any true value, and the 0's can be changed to any false value.
Operator Precedence
Simple Operator Precedence Examples in python
Variable Scope and Binding
Nonlocal Variables
Global Variables
The global keyword means that tasks will occur at the top level of the module, not at the top level of the program. If you found x nonlocal, then x belongs to a closure function and is neither local nor global 2.
Local Variables
The del command
Functions skip class scope when looking up namesnames
The target is similar to the one described above, but with slices - arrays of items instead of a single item. The scope of names defined in a class block is limited to the class block; it does not extend to method code blocks - this includes understanding and generating generator expressions as they are.
Local vs Global Scope
In this function, foo is a global variable from the start foo = 7 # global foo has been changed. On the other hand, non-local (see Non-local variables), available in Python 3, takes a local variable from a bounding scope to the local scope of the current function.
Binding Occurrence
A non-local statement causes the specified identifiers to refer to previously bound variables in the nearest enclosing scope, except global ones.
Conditionals
Truth Values
User-defined types where the __bool__ or __len__ methods return 0 or False. All other values in Python evaluate to True. Note: A common mistake is to simply check for the False of an operation that returns different False values where the difference matters.
Boolean Logic Expressions
In the example above, print_me is never executed because Python can determine that the entire expression is False when it encounters the 0 (False). Keep this in mind if print_me needs to execute to serve your program logic.
Using the cmp function to get the comparison result of two objectsresult of two objects
Else statement
Testing if an object is None and assigning it
If statement
Build an army of powerful Machine Learning models and know how to combine them to solve any problem.
Comparisons
Chain Comparisons
Greater than or less than
Not equal to
Equal To
Comparing Objects
Loops
Break and Continue in Loops
If a loop has an else clause, it is not executed when the loop is terminated through a break statement. A continue statement will jump to the next iteration of the loop, skipping the rest of the current block but continuing the loop.
For loops
Iterating over lists
The result will be a special string sequence type in python >=3 and a list in python <=2. NB: in Python 3.x map returns an iterator instead of a list, so in case you need a list, you have to throw the result print(list(x)).
Loops with an "else" clause
The original concept for such a clause dates back to Donald Knuth and the meaning of the else keyword becomes clear if we rewrite a loop in terms of if statements and goto statements from earlier days before structured programming or from a lower level -assembly language. Some discussion of this can be found in [Python ideas] Summary of for..else threads, Why python uses 'else' after for and while loops.
The Pass Statement
The for loop completes without error, but no commands or code are executed. Similarly, pass can be used in while loops, as well as in selections and function definitions, etc.
Iterating over dictionaries
If you just need to iterate the result, you can use the equivalents .iterkeys(), .itervalues() and .iteritems(). The difference between .keys() and .iterkeys(), .values() and .itervalues(), .items() and .iteritems() is that the iter* methods are generators.
Looping and Unpacking
The elements in the dictionary thus appear one by one as they are evaluated. When a list object is returned, all the elements are packed into a list and then returned for further evaluation.
Iterating dierent portion of a list with dierent step sizestep size
While Loop
Arrays
Access individual elements through indexes
Basic Introduction to Arrays
In the above statement, arrayIdentifierName is the name of the array, the typecode lets python know the type of the array, and Initializers are the values with which the array is initialized. Type codes are codes used to determine the type of array values or array type.
Append any value to the array using append() methodmethod
The table in the parameters section shows the possible values you can use when declaring an array and its type.
Insert value in an array using insert() method
Extend python array using extend() method
Add items from list into array using fromlist() methodmethod
Remove any array element using remove() methodmethod
Remove last array element using pop() method
Fetch any element through its index using index() methodmethod
Reverse a python array using reverse() method
Get array buer information through buer_info() methodbuer_info() method
Check for number of occurrences of an element using count() methodusing count() method
Convert array to string using tostring() method
Convert array to a python list with same elements using tolist() methodelements using tolist() method
Append a string to char array using fromstring() methodmethod
Multidimensional arrays
Lists in lists
Dictionary
Introduction to Dictionary
Avoiding KeyError Exceptions
Iterating Over a Dictionary
Dictionary with default values
Merging dictionaries
Accessing keys and values
Remember that if you have many values to add, dict.setdefault() will create a new instance of the initial value (in this example a []) each time it is called - which can create unnecessary workloads. Use sort(), sorted(), or an OrderedDict if you care about the order these methods return.
Accessing values of a dictionary
Python 2/3 difference: In Python 3, these methods return special iterable objects, not lists, and are the equivalent of the Python 2 iterkeys(), itervalues(), and iteritems() methods. These objects can be used as lists for the most part, although there are some differences.
Creating a dictionary
Each key must be hashable (can use the hash function to hash it; otherwise TypeError will be thrown) There is no particular order for the keys.
Creating an ordered dictionary
Unpacking dictionaries using the ** operator
As of Python 3.5, you can also use this syntax to concatenate any number of dict objects.
The trailing comma
The dict() constructor
Dictionaries Example
All combinations of dictionary values
List
List methods and supported operators
Lists can also be reversed when sorted using the reverse=True method in the sort() method. Element deletion – it is possible to delete multiple elements in the list using the del keyword and bit 12.
Accessing list values
Checking if list is empty
Iterating over a list
In this last example, we deleted the first element on the first iteration, but that caused the bar to be skipped.
Checking whether an item is in a list
Any and All
Reversing list elements
Concatenate and Merge lists
To pad lists of unequal length to the longest with Nones, use itertools.zip_longest (itertools.izip_longest in Python 2).
Length of a list
Remove duplicate values in list
Comparison of lists
Accessing values in nested list
Initializing a List to a Fixed Number of Elements
List comprehensions
List Comprehensions
While the if after the for…in is part of list comprehension and is used to iteratively filter elements from the source. Before using list comprehension, you need to understand the difference between functions that are called because of their side effects (mutating or in-place functions) that usually return None, and functions that return an interesting value.
Conditional List Comprehensions
Also, a conditional list comprehension of the form [e for x in y if c] (where e and c are expressions in the form of x) corresponds to list(filter(lambda x: c, map(lambda x: e, y ))). If you are using Python 2.7, xrange may be better than range for several reasons as described in the xrange documentation.
Avoid repetitive and expensive operations using conditional clauseconditional clause
So (for simplicity and without actual loss of generality) say you have L sublists of I elements each: the first I elements are copied back and forth L-1 times, the other I elements L-2 times, and so on; the total number of copies is I times the sum of x for x from 1 to L excluded, i.e. I * (L**2)/2. The list comprehension only generates one list once and copies each point (from its original residence to the result list) exactly once as well.
Dictionary Comprehensions
Note: Dictionary comprehension was added in Python 3.0 and ported to 2.7+, unlike list comprehension which was added in 2.0. Versions < 2.7 can use generator expressions and the built-in dict() to simulate the behavior of dictionary comprehensions.
List Comprehensions with Nested Loops
In both expanded form and list comprehension, the outer loop (the first for the statement) comes first. This is especially true if the nesting is more than 2 levels deep and/or the comprehension logic is too complex.
Generator Expressions
There may be thousands of objects, they need to be retrieved one by one, and we just need to know if there exists an object that matches a pattern.
Set Comprehensions
Where for reasons of readability, the results of one map or filter function must therefore be carried over to the next; with simple cases this can be replaced with a single list comprehension. Furthermore, we can easily tell from the list comprehension what the outcome of our process is, where there is more cognitive load when reasoning about the chained Map & Filter process.
Comprehensions involving tuples
Counting Occurrences Using Comprehension
Changing Types in a List
Nested List Comprehensions
As with nested for loops, there is no limit to how deeply understanding can be nested.
Iterate two or more list simultaneously within list comprehensionlist comprehension
List slicing (selecting parts of lists)lists)
Using the third "step" argument
Selecting a sublist from a list
Reversing a list with slicing
Shifting a list using slicing
Example 4
Example 2
Example 3
Linked lists
Single linked list example
Linked List Node
Write a simple Linked List Node in python
Filter
Basic use of filter
Filter without function
Filter as short-circuit check
Complementary function: filterfalse, ifilterfalse
Heapq
Largest and smallest items in a collection
Smallest item in a collection
Tuple
Tuple
Tuples are immutable
Packing and Unpacking Tuples
In Python 3, a target variable with a * prefix can be used as a catch variable (see Unpacking Iterables).
Built-in Tuple Functions
The min function returns the item from the tuple with the min value min(tuple1).
Tuple Are Element-wise Hashable and Equatable
Indexing Tuples
Reversing Elements
Basic Input and Output
Using the print function
Input from a File
If the file size is small, it is safe to read the entire contents of the file into memory. When read() is called with no argument, it will read to the end of the file.
Read from stdin
Using input() and raw_input()
Function to prompt user for a number
Printing a string without a newline at the end
Files & Folders I/O
File modes
Reading a file line-by-line
Iterate files (recursively)
Getting the full contents of a file
Writing to a file
Check whether a file or path exists