Code Monkey home page Code Monkey logo

py-samples's Introduction

Python samples

Blocks

In python blocks do not define scopes, however Functions, Objects, Modules do.

Conditional statements

Python does not have switch/case, instead use elif statement.

Loops I

Two loops; for & while.

Class introspection

These functions work by using Class introspection:

  • type()
  • id()
  • isinstance()

Conditional Operators

  1. Comparison Operators

    operator py desc
    == a == b Equal
    != a != b NotEqual
    < a < b Less than
    > a > b Greater than
    <= a <= b Less than or equal
    >= a >= b Greater than or equal
  2. Logical Operators

    operator py desc
    and x and y True if both x and y
    or x or y True if x or y
    not not x Invert state
  3. Identity Operator

    py desc
    x is y True if the same object
    x is not y True if not the same object
  4. Membership Operators

    py desc
    x in y True if x member of collection y
    x not in y True if x not member of collection y

Arithmetic Operators

desc operator
Addition +
Subtraction -
Multiplication *
Division /
Integer Division //
Remainder(modulo) %
Exponent **
Unary negative -
Unary positive +
    # Unary operators
    z = -1
    z = +z
    print(z) # output: -1

Bitwise Operators

desc operator
And &
Or
Xor ^
Shift left <<
Shift right >>

Loops II

You can use else in while, or for loop!

    while pw != secret:
        if pw == '123': break
        pw = input('Enter secret word:')
    else: # in case while breaks, else won't run
        print('>Secret key is correct.')


    animals = ('bear', 'bunny', 'dog', 'cat')
    for pet in animals:
        print(pet)
    else:
        print('>Items finished.')

Functions

Arguments

To use argument lists, use *. For keyword arguments (a.k.a dictionary), use **

    ## Argument list
    def func(*args):
        if len(args):
            for arg in args:
                print(arg)

    args = ('one', 'two', 'three')
    func(*args)

    # Keyword arguments or dictionary arguments
    def kitten(**kwargs):
        if len(kwargs):
            for k in kwargs:
                print(f'Kitten {k} says {kwargs[k]}')

    x = dict(Buffy='meow', Zilla='grr', Angel='rawr')
    kitten(**x)

Generators

range() is an example of generators, it is useful for creating a series of values. It uses yield return.

    def inclusive_range(*args):
        ...
        i = start
        while i <= stop:
            yield i
            i += step

Decorators

    def f1(f):
        def f2():
            print('before function call')
            f()
            print('after function call')
        return f2

    @f1
    def f3():
        print('this is f3')

    f3()

Data structures

These collections may contain any object or type.

  1. The list type: ordered collection, sequential, iteratable, mutable

         x = [1, 2, 3, 4, 5]
  2. Tuple: exactly similar to list but the only difference: it is immutable

         x = (1, 2, 3, 4, 5)
  3. The dictionary type: key-value pairs or hashed array. strings and numbers can always be keys. keys must be immutable.

         # two syntax
         x = {"a": 1, "b": 2, "c": 3}
         y = dict(a=1, b=2, c=3)
  4. The set type: unordered list of unique values. It's exactly like a list without duplicate elements.

         # two syntax
         x = {1, 2, 3, 4, 5}
         y = set(12345)

    You can sort a set using sorted() function.

Classes

Special methods

Special methods start and ends with double underscores e.g. init

class Animal:
    # Class Variables, same for all objects of a class if they are mutable
    ## if you need a constant variable for your class, use immutable types
    x = 'I am a class variable'

    def __init__(self, **kwargs):
        # Object Variables starts with underscore _ this means do not touch this! use setters instead.
        # python doesn't have private variables
        self._type = kwargs['type'] if 'type' in kwargs else '-'
        self._name = kwargs['name'] if 'name' in kwargs else '-'
        self._sound = kwargs['sound'] if 'sound' in kwargs else '-'
    ...
    ## special method str, overriding string conversion
    def __str__(self):
        return f'Name: {self.name()}, Type: {self.type()}, Sound: {self.sound()}'
    ...

Generator vs Iterator

Check samples number 12 (using generator which uses yield return) and 18 (using Iterator).

  • Generator function is often easier to implement
  • Iterator is functionally identical to generator

Files

File endings:

  1. LF(Line Feed): Linux-based OS file ending e.g. Mac, etc (1 byte)
    1. decimal: ASCII 10
    2. Hex: 0a
  2. CR(Carriage Return): e.g. apple2, classic Macs (1 byte)
    1. decimal: ASCII 13
    2. Hex: 0d
  3. CRLF: e.g. Windows, OS2, etc (2 bytes)

Two ways to write into a file in python:

  1. using writeline()

        infile = open('02/23-lines.txt', 'rt')
        outfile = open('02/23-lines-copy.txt', 'wt')
        for line in infile:
            outfile.writelines(line)
            print('.', end='', flush=True)
        outfile.close()
  2. using print(): with rstrip() you can rewrite file endings with the default os file endings

        infile = open('02/23-lines.txt', 'rt')
        outfile = open('02/23-lines-copy.txt', 'wt')
        for line in infile:
            # rstrip(): rewrite file endings with the default os file endings
            print(line.rstrip(), file=outfile)
            print('.', end='', flush=True)
        outfile.close()

py-samples's People

Contributors

nkhalili avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.