Basics

Contenido

Basics#

Pyt#

IDLE:

Integrated Development Environment.

Rules for valid variable names:

  • Avoid decorated characters (eg. é, ü, …).

  • Descriptive names are beeter tha short names, but make them less than 3 or 4 words long.

  • Write variables in _snake_case_(as PEP 8 sugests): every word is lower case and separated by an underscore. Another commonly used sintax is camelCase.

Comments:

  • Begin lines with the # character. comments that start on a new line are called block comments while in-line comments, are comments that appear on the same line as some code.

  • According to PEP 8, comments shouls always be written in complete sentences with a sigle space between de # and the first word of the comment.

  • For in-lines comments, PEP 8 recomends at least two spaces between the code and the # symbol.

  • Use comments only when they add value to your code by make it easier to understand why something is done a certain way. Comments that describe what something does can often be avoided by using more descriptive variable names.

  • Strings:
    • Properties:
      1. Strings contains characters: individual letters or symbols.

      2. Strings have a length: the number of characters conatined in a string.

      3. Characters in a string appear in a sequence: each character has a numbered position in the string.

    • PEP 8 recommends each line of Ptyhon code contain no more tha 79 characters-including spaces. For larger lines use `` to break into multiple lines.

  • Integers:
    • Underscores can be used to make the numbers more readable eg. 1_000_000 = 1000000.

  • Floating-point numbers:
    • Can be created in three different ways:
      1. 1000.0

      2. 1_000.0

      3. 1e3 (E-notation)

    • The maximum float number depends on each system. When the maximum is reached Python returns a special float value: inf.

    • floating-point representation error: happend due to the way a floating-point number is store in a computers memory (binary representation).

    • To print a number with certain format use the formatting language.
      • {n:.2f} prints n number rounding two decimal places. To insert commas to group the integer part of large numbers by the thousands use «,» eg.

        > > > n = 1234567890 > > > f» The value of n is {n:,. 2f}»

        “The value of n is 1,234.56”

      This is useful for displaying currency values.

    • fixed-point: a number display with the precise number of decimals places specified.

  • Complex numbers:
    • A complex number is a number with two distinct components: a real component and an imaginary component.
      • n = 1 + 2j

      • Properties:

      • n.real = 1

      • n.imag = 2

      • Method:

      • n.conjugate() => returns the complex conjugate of the number. = (1-2j).

  • Functions:
    • One of the most important properties of a function in Python is that functions are values and can be assigned to a variable.

    • An argument is a value that gets passed to the function as input.

    • Process of executing a funtcion:
      1. the function is called, and any arguments are passed to the function as input.

      2. the functions excecutes, and some action is performed with the arguments.

      3. the function returns, and the original function call is replaced with the return value.

    • When a function changes or affects something external to the function itself, it is said to have a side effect eg. print().

    • If a function doesn’t have a retunr statement, the returned value is None.

    • The anatomy of a function:
      1. The function signature defines the name of the function and any inputs it expects.

      2. The function body contains the code that runs every time the function is used. ```

      {—-} <- Parameter list

      def multiply(x, y): # Function signature
      “””

      Return the product of two numbers x and y.

      “”” # Function body product = x * y return product # Return statement

      ``` + PEP 8 recommends indenting with four spaces. + Documenting your functions:

    • Operations:
      • Hierarchy:
        1. () -> parentheses.

        2. x^y -> exponents.

          • / -> multiplication and division (left to right).

        4. + | - -> addition and subtraction (left to right). {PEMDAS}

    • Addition: +

    • Substraction: -

    • Multiplication: *

    • Division: /

    • Integer division: //

    • Exponents: **

    • Modulus operator: % > To calculate the remainder r of dividing a number x by a number y, Python uses the equation r = x - (y * (x // y)).

    • PEP 8 says: If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority( ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.

  • Build-in functions:
    • type(): returns the data type of a variable or value.

    • len(): returns the length of a string or list.

    • int(): converts a string into integer.

    • float(): converts a string intp numbers with decimal point.

    • str(): converts a number into a string.

    • round(): round a number to its nearest integer. Has unexpected behavior when the number ends in .5 due Python uses the «rounding ties to even» rounding strategy.

    • abs(): absolute value.

    • pow(): different from ** because it can use a third argument computing the modulus of the result from raising a number to a certain power. i.e. ((x ** y) % z).

  • Build-in number data types:
    • integers

    • floating-point numbers

    • complex numbers

  • Methods:
    • <str>.lower(): converts all letters from string to lower case.

    • <str>.upper(): converts all letters from string to upper case.

    • <str>.rstrip(): removes white spaces from the right side of a string.

    • <str>.lstrip(): removes white spaces from the left side of a string.

    • <str>.strip(): removes white spaces from both sides of a string.

    • <str>.startswith(string): string starts with given string (this method is case sensitive).

    • <str>.endswith(string): string ends with given string (this method is case sensitive).

    • To see more String methods create a string variable, add a dot at the end of it and wait for a few seconds. A list of available methods will appear in the IDLE.

    • number.is_integer(): verify if the number is integral -meaning it has no fractional part-.

    • <str>.split(<separator>):

    • random.choice(list): randomly select an item from the list given.

  • Open Debugger:
    • From python Shell select Debug > Debugger.

  • Loops:
    • while: repeat a section of code ahile some condition is met.

      ``` while n < 100:

      print(n) n = n + 1

      ```

    • for: executes a section of code once for each item in a collection of items.

      ``` for letter in «Python»: #statement = for + membership expression + :

      print(letter)

      ``` - Python’s built-in function range() produces a range of numbers.

      • range(n) = a range from 0 to n - 1.

      • range(n, n + i) = a range from n to n + i - 1.

    • Using nested loops is sometimes the only way to get something done, but too many nested loops can have a negative effect on a program’s performance.

    • else statement in loops:
      • Any code in the else block after a loop is executed only it the for loop completes without a break statement.

  • Scope:
    • ¿How Python resolves scope? LEGB rule: Local, Enclosing, Global, Built-in

  • Logical Operators:
    • and

    • or

    • not

    • Order of precedence for logical operators:
      • <, <=, ==, >=, >

      • not

      • and

      • or

      • Grouping expressions with parentheses is a great way to clarify which operators belogn to which part of a compound expression.

  • Boolean comparators:
    • if

    • else

    • elif

    • The complexity that results from using deeply nested if statements may make difficult to predict how your program will behave under given conditions. For this reason, nested if statements are generally discouraged.

  • Break out of the pattern:
    • break:
      • Tells python to break out of a loop.

    • continue:
      • Is used to skip any remaining code in the loop body and continue on to the next iteration.

  • Handling errors:
    • built-in exception types:
      • ValueError: operation encounters an invalid value (e.g. int(«not a number»)).

      • TypeError: operation is performed on a value of the wrong type (e.g. «1» + 2).

      • NameError: using a variable name that hasn’t been defined yet (e.g. print(does_not_exist)).

      • ZeroDivisionError: 1 / 0.

      • OverflowError: the result of an arithmetic operation is too large (e.g. pow(2.0, 1_000_000)). note: integers in Python have unlimited precision. This means that OverflowErrors can oly occur with floating-point numbers.

    • try and except: sometimes you can predict that a certain exception might occur. Instead of letting the program crash, you can catch the error if it occurs and do something else instead.

      ``` try:

      …do something…

      except type_of_error:

      …do something else instead…

      ``` -E.g:

      ```Python # one kind of exception try:

      number = int( input(» Enter an integer: «))

      except ValueError:

      print(» That was not an integer»)

      # two or more kinds of exception try:

      number1 = int( input(» Enter an integer: «)) number2 = int( input(» Enter another integer: «)) print(number1 / number2)

      except (ValueError, ZeroDivisionError):

      print(«Encountered an error»)

      # two or more kinds of exception with different explanation. try:

      number1 = int( input(» Enter an integer: «)) number2 = int( input(» Enter another integer: «)) print(number1 / number2)

      except ValueError:

      print(» That was not an integer»)

      except ZeroDivisionError:

      print(«number2 must not be 0»)

      ```

  • Tuples, Lists, and Dictionaries:

    Python has three built-in data structures: tuples, lists, and dictionaries: + Tuples (immutable sequences)

    • comes from mathematics, where it is used to describe a finite ordered sequence of values.

    -Empty tuple: a tuple that doesn’t contain any values (eg. empty_tuple = ()). -One value tuple: x = (1,) -Tuple built in function can only create a tuple from another sequences type, like strings. Other similarities: both are sequence types with finite lengths, support indexing and slicing, are immutable, and can be iterated over in a loop. -Main difference: tuples can be any kinf of value you like, whereas strings can only contain characters.

    • Lists (mutable sequences):
      • Change several values in a list at once with a slice assignment:

        colors[1:3] = [«orange», «magenta»] «»» colors[1:3] selects the slots with indices 1 and 2.

      The list aassigned to a slice does not need to have the same lenght as the slice. When the lenght of the list being assigned to the slice is less than the lentgh of the slice, the overall length of the original list is reduced. - Methods to mutate a list:

      • list.insert(i, x)
        • .insert() is said to alter colors in place. This is true for all list methods that do not return a value.

      • list.pop(i) -> removes the value from the list at index i. The value removed is returned by the method.
        • if you do not pass a value to .pop(), it removes the last item in the list.

      • list.append(x) -> inserts x to the end of the list. append(x) alters the list in place (just like .insert(i, x)).

      • list.extend(iterable) -> adds several new elements to the end of a list (also alters the list in place).

      • Lists of numbers:
        • sum([1, 2, 3, 4, 5])

          = 15

        • min([1, 2, 3, 4, 5])

          = 1

        • max([1, 2, 3, 4, 5])

          = 5

      • List Comprehensions:
        • short-hand for a for loop. Commonly used to convert values in one list to a different type.

    • Nesting:
      • A table is an informal way of thinking about a list o lists (or tuples). While you can use the built in list and tuple type for matrices, better alternative exists.

    • Copying:
      • Quirk OOP, when assigning one list to another, both variables refer to the same object, so if one changes the other also changes.

      • A variable name is really just a reference to a specific localtion in computer memory.

      • To get an independent copy of a list, it can be used the slicing notation. This will return a new list with the same values.
        Eg.

        animals = [«lion», «tiger», «frumious Bandersnatch»] large_cats = animals[:]

      • More reading @ [Shallow VS Deep Copying of Python Objects](https://realpython.com/copying-python-objects/).

    • Sorting lists
      • .sort(key): sorts all of the itmes in ascending order (alphabetical o numerical order). It sorts the list in place, so you don’t need to assign it’s result to anything.

      • The key parameter can be used to adjust how the list gets sorted, is also accepts a function that based on the return value will sort the list.
        Eg.

        colors = [«red», «yellow», «green», «blue»] colors.sort(key=len) colors

        [«red», «blue», «green», «yellow»]

        «»» Important: the function that gets passed to key must only accept a single argument. «»»

    • Dictionaries:
      • Key-value pairs: each object in a dictionary has two parts: a key and a value.

      Eg.
      capitals = {

      «California»: «Sacramento», «New York»: «Albany», «Texas»: «Austin»,

      }

      • To add an item to a dictionary:

        capitals[«Colorado»] = «Denver»

      • To remove an item from a dictionary:

        del capitals[«Texas»]

      • To check that a key exists in a dictionary use the «in» keyword.

        >>>»Colorado» in capitals TRUE

      • dictionary.items() method will return a list-like object containing tuples of key-value pair (type called dict_items).

      • Only immutable types can be dictionary keys.

  • [Decorators](https://realpython.com/courses/python-decorators-101/):
    • are functions that take another function, and extends the behavior of that function without explicitly modifying that function.

    • Function as First-Class Objects: functions can be used as arguments also as any other object.

    • eg.

    ```Python import datetime from datetime # decorator def not_during_the_night(func):

    def wrapper():
    if 7 <= datetime.now().hour < 22:

    func()

    else:

    pass # Hush, the neighbors are asleep

    return wrapper

    # x function def say_whee():

    print(“Whee!”)

    # using the decorator say_whee = not_during_the_night(say_whee) ``` + Syntactic Sugar:

    • @ + decorator function’s name

    • Reusing decorators: import from modules.

    • Using arguments in decorators:
      • wrapper(*args, **kwargs):
        • *args: arguments

        • **kwargs: key arguments

    • return values from decorated functions:
      • use inside the wrappeer the “return” statemmenet.

    • Introspection:
      • import functools and decorate the wrapper function with wraps(func).

      • Eg.

      ```Python immport functools

      def do_twice(func):

      # use functools to find the original function properties. @functools.wraps(func) def wrapper_do_twice(*args, **kwargs):

      func(*args, **kwargs) return fun(*args, **kwargs)

      return wrapper

      ```

      • Template Eg.

      ```Python import functools

      def decorator(func):

      @functools.wraps(func) def wrapper_decorator(*args, **kwargs):

      # do something before value = func(*args, **kwargs) # do something after return value

      return wrapper_decorator

      ```

    • Real world examples:
      • Timing functions.

      Eg. ```Python def timer(func):

      «»»Print the runtime of the decorated function»»» @functools.wraps(func) def wrapper_timer(*args, **kwargs):

      start_time = time.perf_count() #1 value = func(*args, **kwards) end_time = time.perf_counter() #2 run_time = end_time - start_time #3 print(f’Finished {func.__name__!r} in {run_time:.4f} secs”) return value

      return wrapper_timer

      ``` - Debugger: Eg. ```Python def debug(func):

      «»»Print the function signature and return value»»» @functools.wraps(func) def wrapper_debug(*args, **kwargs):

      # do something before args_repr = [repr(a) for a in args] #1 kwargs_repr = [f”{k} = {v!r}” for k, v in kwargs.items()] #2 signature = “, “.join(args_repr + kwargs_repr) #3 print(f’Calling {func.__name__}({signature})”) value = func(*args, **kwargs) # do something after print(f”{func.__name__!r} returned {value!r}”) #4 return value

      return wrapper_debug

      ``` - Slowing down code - Registering Plugins

  • OOP:
    • Objetc-oriented programming is a method of structuring a program by bundling related properties and behaviors into individual objects.

    • Classes define functions called methods, which identify the behaviors and actions that an object created from the class can perform with its data.

    • A class is a blueprint for how something should be defined.

    • An instance is an object that is built from a class and contains real data. Creating a new object from a class is called instantiating an object.

    • Python class names are written in CapitalizedWords notation by convention.

    • The first parameter in a method will always be a variable called self.

    • Attributes created in .__init__() are called instance attributes.

    • Instance methods are functions that are defined inside of a class and can only be called from an instance of that class.

    • When creating your own classes, it’s a good idea to have a method that returns a string containing useful informatión about an instance of the class. To do this, use __str__() dunder method.

    • Inheritance is the process by which one class takes on the attributes and methods of another.

    • Child classes can override or extend the attributs and methods of a parent class.

    • To create a child class, you create a new class with its own name and then put the name of the parent class in parentheses.

    • isinstance(object, class) is a function that tells if an object is also an instance of a certain class.

    • You can acces the parent class from inside a method of a child class by using super(). super() does much more than just search the parent class for a method or an attribute. It traverses the entire class hierarchy for a matching method or attribute. If you aren’t careful, super() can have surprising results.

    -E.g:

    ```Python # Parent class class Rectangle:

    # Class attributes species = «Canis Familiaris» # Instance attributes

    def __init__(self, length, width):

    self.length = length self.width = width

    # Instance method def __str__(self):

    pass

    # Another instance method def area(self):

    return self.length * self.width

    # Child class class Square(Rectangle):

    def __init__(self, side_length):

    super().__init__(side_length, side_length)

    ```

    • Managing attributes with python’s property()
      • The pythonic way to avoid getter and setter methods

      • Convert Class attributes into properties (managed attributes)

      • built-in function

      • implemented in C (to ensure optimal performance)

      • property() commonly referred to as a function but it is a class designed to work as a function

  • Keywords:
    • global keyword tells python to look in the global scope for a certain variable. Though, the global keyword is considered bad form in general.

    • del keyword is used to un-assign a variable from a value.

    • in keyword is used to check whether or not a value is contained in a tuple.

  • Dictionary:

    -By Packing/Unpacking you can make multiple variable assignments in a single line. Eg. name, age, occupation = «Daniel», 32, «programmer». -Immutable: the values previously created cannot be changed. -Sequence: an ordered list of values. -Data structure models a collection of data. -Lexicographic ordering: strings ordered as the would appear in a dictionary. - Refactoring: the process of re-writing existing code to be cleaner, easier to read and understand, or adhere to code standards set by a team. -Debugger is a tool that helps you hunt down bugs and understand why the are happening. - Debugging: removing bugs. - Logic errors cause unexpected behaviors called bugs. - Logic errors occur when an otherwise valid program doesn’t do what was intended. - Pythonic: it is generally used to describe code that is clear, concise and uses Python’s built-in features to its advantage. - rounding ties to even: a tie is any number whose last digit is a 5. When you round ties to even, you first look at the digit one decimal place to the left to the last digit in the tie. If that digit is even, you round down. if the digit is odd, you round up. This is a round strategy recommended for floating-point numbers by the IEEE because it helps limit the impact rounding has on operations involving lots of numbers. - sequence is any Python object that supports accessing elements by index. - immutable: an object that cannot be changed once created (e.g. strings). - substring: a portion of a string. - off-by-one error: Forgetting that counting starts with zero and trying to access the first character in a string with the index 1. - docstrings: tiple-quoted strings used to document code or custom functions. - triple-quoted srtring: a string definition which preserves whitespaces. - delimiters: the quotes surrounding a string. - string literal: a string literally written out in code. - Strings: a _fundamental_ data type that represents text. - fundamental data type: data types that can’t be broken down into smaller values of a different type. - data type: the kind of data a value represents.

  • Quotes:
    • «Computers execute code but humans read code.»

# Other topics: * [What is pip](https://realpython.com/what-is-pip/) * [f-string or formatted string literals](https://realpython.com/python-f-strings/) * [formatting language](https://docs.python.org/3/library/string.html#format-specification-mini-language) * [Pyhton’s built-in exceptions](https://docs.python.org/3/library/exceptions.html) * [Finding the Perfect Python Code Editor](https://realpython.com/courses/finding-perfect-python-code-editor/) * [Python args and kwargs: Demystified](https://realpython.com/courses/python-kwargs-and-args/) * [Regular Expressions: Regexes in Python (Part 1)](https://realpython.com/regex-python/) * [Python Inner Functions—What Are They Good For?](https://realpython.com/inner-functions-what-are-they-good-for/) * [Immutability in Python](https://realpython.com/courses/immutability-python/) — * [Python Virtual Environments: A Primer](https://realpython.com/python-virtual-environments-a-primer/) * [Setting up Python for Machine learning on Windows](https://realpython.com/python-windows-machine-learning-setup/) —

##What is Pip?

pip is the standard package manager for Python. It allows you to install and manage additional packages that are not part of the Python standard library. It is included with the Python installer since versions 3.4 for Python 3 and 2.7.9 for Python 2. pip is to python as npm is to JavaScript, gem to Ruby or NuGet to .NET.

###Installing Packages with pip

Python packages are published to the Python Package Index (PyPI aka Pie Pea Eye).

pip options: * install * download * uninstall * freeze * list * show * check * config * search * wheel * hash * completion * help

Other content: requirement files. Packages that are good candidates to become useful tools: requests and pytest.

###Finding packages to use

Use search command or search for packages directly in the PyPI website: https://pypi.org/.

###Uninstalling packages

Before uninstalling a package, make sure to run the show command for that pakage. Doing this will show the required packages for that package and required-by package info, then those can be uninstall to.

Adding a -y will suppress the file list and confirm the uninstall request. Eg. pip uninstall urllib3 -y -> Uninstalling urllib3-1.24.1: -> Successfully uninstalled urllib3-1.24.1

###Alternatives to pip

  1. Conda

  2. Pipenv

  3. Poetry

## Introduction to Python (Coursera) Program structure:

  1. Globals (state)

  2. Helper functions

  3. Classes (later)

  4. Define event handlers

  5. Create a frame

  6. Register event handlers

  7. Start frame and timers

```

# SimpleGUI program template

# Import the module import simplegui

# Define global variables (program state)

# Define «helper» functions

# Define event handler functions

# Create a frame

# Register event handlers

# Start frame and timers

```