garogarabed12 / Learning-Python

Learning Python using Head-First Python, 2nd Edition by Paul Barry and other sources

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Python

Important Bulletpoints:

  • When trying to determine the code that they need to solve a particular problem, Python programmers often favor experimenting with code snippets at the shell. The shell provides two interactive functions that work at the >>> prompt. The dir function lists an object’s attributes, whereas help provides access to the Python docs.

  • Growing a list at runtime is possible due to the inclusion of a handful of list methods, which include append, extend, and insert.

  • Shrinking a list at runtime is possible due to the inclusion of the remove and pop methods.

  • If you want to have another variable reference an existing list, use the assignment operator (=). If you want to make a copy of the objects in an existing list and use them to initialize a new list, be sure to use the copy method instead.

  • Unlike a lot of other programming languages, Python lets you index into a list from either end. Using –1 selects the last item in the list, –2 the second last, and so on.

  • Lists also provide slices (or fragments) of a list by supporting the specification of start, stop, and step as part of the square bracket notation.

    💡
    Lists are used a lot, but…​
    They are not a data structure panacea. Lists can be used in lots of places; if you have a collection of similar objects that you need to store in a data structure, lists are the perfect choice. However — and perhaps somewhat counterintuitively — if the data you’re working with exhibits some structure, lists can be a bad choice.
  • Think of a dictionary as a collection of rows, with each row containing exactly two columns. The first column stores a key, while the second contains a value. Each row is known as a key/value pair, and a dictionary can grow to contain any number of key/value pairs. Like lists, dictionaries grow and shrink on demand.

  • Python’s triple-quoted strings can be used to add multiline comments to a function. When they are used in this way, they are known as docstrings.

  • Function annotations can be used to document the type of your function’s arguments, as well as its return type.

  • Any function argument can be assigned a default value in the function’s def line. When this happens, the specification of a value for that argument during a function’s invocation is optional.

  • As well as assigning arguments by position, you can use keywords, too. When you do, any ordering is acceptable (as any possibility of ambiguity is removed by the use of keywords and position doesn’t matter anymore).

Meet the four Built-in Data Structures.

Python comes with four built-in data structures that you can use to hold any collection of objects, and they are list, tuple, dictionary, and set. Note that by “built-in” we mean that lists, tuples, dictionaries, and sets are always available to your code and they do not need to be imported prior to use: each of these data structures is part of the language.

  • List: An ordered mutable collection of objects. A list in Python is very similar to the notion of an array in other programming languages

  • Tuple: An ordered immutable collection of objects. A tuple is an immutable list. This means that once you assign objects to a tuple, the tuple cannot be changed under any circumstance.

  • Dictionary: An unordered set of key/value pairs Depending on your programming background, you may already know what a dictionary is, but you may know it by another name, such as associative array, map, symbol table, or hash.

    ⚠️
    Something to watch out for when using a dictionary is that you cannot rely upon the internal ordering used by the interpreter. Specifically, the order in which you add key/value pairs to a dictionary is not maintained by the interpreter, and has no meaning (to Python).
  • Set: An unordered set of unique objects. In Python, a set is a handy data structure for remembering a collection of related objects while ensuring none of the objects are duplicated. The fact that sets let you perform unions, intersections, and differences is an added bonus (especially if you are a math type who loves set theory). Sets, like lists and dictionaries, can grow (and shrink) as needed. Like dictionaries, sets are unordered, so you cannot make assumptions about the order of the objects in your set.

List Slices in Action

You can put start, stop, and step inside square brackets. When used with lists, start, stop, and step are specified within the square brackets and are separated from one another by the colon (:) character: letters[start:stop:step]

  • When start is missing, it has a default value of 0.

  • When stop is missing, it takes on the maximum value allowable for the list.

  • When step is missing, it has a default value of 1.

letters = ['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c', '!']

>>> letters[0:10:3]
['D', "'", 'p', 'i']

>>> letters[3:]
["'", 't', ' ', 'p', 'a', 'n', 'i', 'c', '!']

>>> letters[:10]
['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i']

>>> letters[::2]
['D', 'n', 't', 'p', 'n', 'c']

Dictionaries

  • By default, every dictionary is unordered, as insertion order is not maintained. If you need to sort a dictionary on output, use the sorted built-in function.

  • The items method allows you to iterate over a dictionary by row—that is, by key/value pair. On each iteration, the items method returns the next key and its associated value to your for loop.

  • Trying to access a nonexistent key in an existing dictionary results in a KeyError. When a KeyError occurs, your program crashes with a runtime error.

  • You can avoid a KeyError by ensuring every key in your dictionary has a value associated with it before you try to access it. Although the in and not in operators can help here, the established technique is to use the setdefault method instead.

Follow Best Practice As Per the PEPs

When it comes to formatting your code, the Python programming community has spent a long time establishing and documenting best practice. This best practice is known as PEP 8. PEP is shorthand for “Python Enhancement Protocol.”

PEP 8 is the style guide for Python code. It is recommended reading for all Python programmers, and it is the document that suggests the “be consistent” advice for string quotes described on the last page. Take the time to read PEP 8 at least once. Another document, PEP 257, offers conventions on how to format docstrings, and it’s worth reading, too.

Find the list of PEPs here:

True or false?

Every object in Python has a truth value associated with it, in that the object evaluates to either True or False. Something is False if it evaluates to 0, the value None, an empty string, or an empty built-in data structure. Every other object in Python evaluates to True.

ℹ️
We can pass any object to the bool function and determine whether it is True or False. Critically, any nonempty data structure evaluates to True.

Functions

  1. Function annotations are optional It’s OK not to use them. In fact, a lot of existing Python code doesn’t (as they were only made available to programmers in the most recent versions of Python 3).

  2. Function annotations are informational They provide details about your function, but they do not imply any other behavior (such as type checking).

💡
For more details on annotations, see PEP 3107.
⚠️
The goal of annotations is not to make life easier for the interpreter; it’s to make life easier for the user of your function. Annotations are a documentation standard, not a type enforcement mechanism.

In fact, the interpreter does not care what type your arguments are, nor does it care what type of data your function returns. The interpreter calls your function with whatever arguments are provided to it (no matter their type), executes your function’s code, and then returns to the caller whatever value it is given by the return statement. The type of the data being passed back and forth is not considered by the interpreter

Source: Head-First Python Book.

Clean Code Practices:

Stop writing Python functions that take more than three minutes to understand!

Have you ever looked at a function you wrote one month earlier and found it difficult to understand in 3 minutes? If that is the case, it is time to refactor your code. If it takes you more than 3 minutes to understand your code, imagine how long it would take for your teammates to understand your code. If you want your code to be reusable, you want it to be readable.
These practices will make your functions more readable and easier to detect errors.

  • Small:

    • A function should be small because it is easier to know what the function does. How small is small? There should rarely be more than 20 lines of code in one function. It can be as small as below. The indent level of a function should not be greater than one or two.

  • Do One Task:

    • A function should complete only one task, not multiple tasks.

  • One Level Of Abstraction:

    The level of abstraction is the amount of complexity by which a system is viewed or programmed. The higher the level, the less detail. The lower the level, the more detail.
    — PCMag
    • To make the code within the function to be at the same level of abstraction, we can put the low-level code into another function.

  • Duplication:

    • We should avoid duplication because:

      • It is redundant

      • If we make a change to one piece of code, we need to remember to make the same change to another piece of code. If we forget to do so, we will introduce bugs into our code.

    • We can eliminate duplication by putting the duplicated code into a function.

  • Descriptive Names:

    A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment.
    — Clean Code by Robert C. Martin
    • Don’t be afraid to write long names. It is better to write long names rather than write vague names.

  • Have Fewer than 4 Arguments:

    • A function should not have more than 3 arguments since it is a sign that the function is performing multiple tasks. It is also difficult to test a function with more than 3 different combinations of variables.

      💡
      If a function has more than 3 arguments, consider turning it into a class.

About

Learning Python using Head-First Python, 2nd Edition by Paul Barry and other sources


Languages

Language:Jupyter Notebook 93.3%Language:Python 6.7%