L2 - Introduction To Python
L2 - Introduction To Python
Python
                            By
             Dr. Mubarak Sufyan
                              1
Table of content:
   Keyword, Operators, and Syntax
   Operators
   Arithmetic Operators
   Logical Operators
   Variables
   Built-in Functions/Standard Library
   Functions
   Python Script
   Plotting in Python
   If statement
   Arrays
   Control Statement
   Fibonacci Numbers
                                          2
                                   Whitespace
   Whitespace is meaningful in Python: especially indentation and
    placement of newlines.
   Use a newline to end a line of code.
        Use \ when must go to next line prematurely.
   No braces { } to mark blocks of code in Python… Use consistent
    indentation instead.
        The first line with less indentation is outside of the block.
        The first line with more indentation starts a nested block.
                                                                         hello3.py
   Often a colon appears at the start of a new block. (E.g. for
    function and class definitions.)                                     1   # Prints a helpful message.
                                                                         2   def hello():
   Python uses indentation to indicate blocks, instead of {}            3       print("Hello, world!")
                                                                         4       print("How are you?")
        Makes the code simpler and more readable                        5
        In Java, indenting is optional. In Python, you must indent.     6   # main (calls hello twice)
                                                                         7   hello()
                                                                                   3
                                                                         8   hello()
WHAT IS A RECIPE
1+2+3 = an algorithm!
                                                                         4
                                   Keywords
   Each high-level language has its own set of predefined words that the
    programmer must use to write a program.
   The words that make up a high-level programming language are known as key
    words or reserved words.
   Each key word
        has a specific meaning, and
        cannot be used for any other purpose.
   An example of a Python statement that uses the key word print to print a
    message on the screen.
                                                                                5
             The Python keywords
 Assert  in
                                              6
                              List methods
   Python has a set of built-in methods that you can use on lists.
        pop([i]), pop() : create stack (FIFO), or queue (LIFO) → pop(0)
        reverse()      : reverse list
        append()       : Adds an element at the end of the list
        clear()        : Removes all the elements from the list
        copy()         : Returns a copy of the list
        count()        : Returns the number of elements with the specified value
        extend()       : Add the elements of a list (or any iterable), to the end of the current list
        index()        : Returns the index of the first element with the specified value
        insert()       : Adds an element at the specified position
        pop()          : Removes the element at the specified position
        remove()       : Removes the item with the specified value
        reverse()      : Reverses the order of the list
                                                                                     7
Values and types
                   8
Values and types
   A value is one of the basic things a program works with, like a letter or a
    number.
   The values we have seen so far are 1, 2, and “Hello, World!” These values
    belong to
   different types:
        2 is an integer, and
        “Hello, World!” is a string, so called because it contains a “string” of letters
                                                                                            9
Core data types
   Numbers
   Strings
   Lists
   Dictionaries
   Tuples
   Files
   Sets
Basic Datatypes
          Integers (default for numbers)
           z = 5 / 2       # Answer 2, integer division
          Floats
           x = 3.456
          Strings
            Can     use “” or ‘’ to specify with “abc” == ‘abc’
            Unmatched      can occur within the string: “matt’s”
            Use  triple double-quotes for multi-line strings or
             strings than contain both ‘ and “ inside of them:
             “““a‘b“c”””
1- Python - Numbers
       Number data types store numeric values.
       They are immutable data types, which means that changing the value
        of a number data type results in a newly allocated object.
       Number objects are created when you assign a value to them. For
        example:
        var1 = 1
        var2 = 10
       You can also delete the reference to a number object by using the del
        statement.
       The syntax of the del statement is:
        del var1[,var2[,var3[....,varN]]]]
        You can delete a single object or multiple objects by using the del
        statement. For example:
        del var del var_a, var_b
Numbers
random() A random float r, such that 0 is less than or equal to r and r is less than 1
seed([x])                   Sets the integer starting value used in generating random numbers. Call this
                            function before calling any other random module function. Returns None.
uniform(x, y)               A random float r, such that x is less than or equal to r and r is less than y
 Trigonometric Functions:
 Function                        Description
acos(x)   Return the arc cosine of x, in radians.
asin(x)       Return the arc sine of x, in radians.
atan(x)       Return the arc tangent of x, in radians.
atan2(y, x)   Return atan(y / x), in radians.
cos(x)        Return the cosine of x radians.
hypot(x, y)   Return the Euclidean norm, sqrt(x*x + y*y).
sin(x)        Return the sine of x radians.
tan(x)        Return the tangent of x radians.
degrees(x)    Converts angle x from radians to degrees.
radians(x)    Converts angle x from degrees to radians.
2. Python - Strings
     Strings are amongst the most popular types in Python.
     can create them simply by enclosing characters in quotes.
     Python treats single quotes the same as double quotes.
     Creating strings is as simple as assigning a value to a variable. For
      example:
      var1 = 'Hello World!'
      var2 = "Python Programming"
Strings
   A string object is a ‘sequence’, i.e., it’s a list of items where each item has a
    defined position.
   Each character in the string can be referred, retrieved and modified by using its
    position.
   This order id called the ‘index’ and always starts with 0.
               Accessing Values in Strings:
   Python does not support a character type;
        these are treated as strings of length one, thus also considered a substring.
   To access substrings, use the square brackets for slicing along with the index
    or indices to obtain your substring:
   Example:
    var 1 = 'Hello World!'
    var2 = "Python Programming"
    print "var1[0]: ", var1[0]
    print "var2[1:5]: ", var2[1:5]
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given string H in a will give 1
not in            Membership - Returns true if a character does not exist in the given string   M not in a will give
                                                                                                1
r/R               Raw String - Suppress actual meaning of Escape characters.                    print r'\n' prints \n
                                                                                                and print R'\n'
                                                                                                prints \n
%                 Format - Performs String formatting                                           See at next section
String Formatting Operator:
     Format Symbol                         Conversion
%c                   character
%s                   string conversion via str() prior to formatting
%i                   signed decimal integer
%d                   signed decimal integer
%u                   unsigned decimal integer
%o                   octal integer
%x                   hexadecimal integer (lowercase letters)
%X                   hexadecimal integer (UPPERcase letters)
%e                   exponential notation (with lowercase 'e')
%E                   exponential notation (with UPPERcase 'E')
%f                   floating point real number
%g                   the shorter of %f and %e
%G                   the shorter of %f and %E
Other supported symbols and functionality are listed
in the following table:
                Symbol                         Functionality
        *                argument specifies width or precision
- left justification
9 isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
10 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
11 isdigit()
12 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
13 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise
14 isspace()
     Returns true if string contains only whitespace characters and false otherwise
15   istitle()
     Returns true if string is properly "titlecased" and false otherwise
16   isupper()
     Returns true if string has at least one cased character and all cased characters are in uppercase and false
     otherwise
17   join(seq)
     Merges (concatenates) the string representations of elements in sequence seq into a string, with separator
     string
18   len(string)
     Returns the length of the string
19   ljust(width[, fillchar])
     Returns a space-padded string with the original string left-justified to a total of width columns
20   lower()
     Converts all uppercase letters in string to lowercase
21   lstrip()
     Removes all leading whitespace in string
22   maketrans()
     Returns a translation table to be used in translate function.
23   max(str)
     Returns the max alphabetical character from the string str
24   min(str)
Replaces all occurrences of old in string with new, or at most max occurrences if max given
26 rfind(str, beg=0,end=len(string))
28 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
29 rstrip()
30 split(str="", num=string.count(str))
     Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most
     num substrings if given
31   splitlines( num=string.count('\n'))
     Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed
32 startswith(str, beg=0,end=len(string))
   Determines if string or a substring of string (if starting index beg and ending index
   end are given) starts with substring str; Returns true if so, and false otherwise
33 strip([chars])
34 swapcase()
35 title()
   Returns "titlecased" version of string, that is, all words begin with uppercase, and the
   rest are lowercase
36 translate(table, deletechars="")
   Translates string according to translation table str(256 chars), removing those in the
   del string
37 upper()
38 zfill (width)
   Returns original string leftpadded with zeros to a total of width characters; intended
   for numbers, zfill() retains any sign given (less one zero)
39 isdecimal()
     Returns true if a unicode string contains only decimal characters and false otherwise
Data Collection – Data Type
                              37
Arrays
   An array is a special variable, which can hold more than one value at a
    time.
   You define an array like this:
          1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
   You can also use text like this:
          1 carlist = [ ”Volvo” , ” Tesl a ” , ”Ford” ]
   You can use Arrays in Loops like this:
          1 for x in data :
          2 print( x )
   You can return the number of elements in the array like this:
          1 N = len (data)
   You can get a specific value inside the array like this:
          1 index = 2
          2 x = cars [ inde x ]
   You can use the append() method to add an element to an array:
          1 data.append ( 11.4 )
   many built in methods you can use in combination with arrays, like        38
   A Mapping type
   Dictionaries store a mapping between a set of keys and a set of values.
        Keys can be any immutable type.
        Values can be any type
        A single dictionary can store values of different types
   can define, modify, view, lookup, and delete the key-value pairs in the dictionary.
   Dictionaries are unordered mappings of ’Name : Value’ associations.
   Comparable to hashes and associative arrays in other languages.
   Intended to approximate how humans remember associations.
                     41
 Sequence types:
Tuples, Lists, and
           Strings
Mutable vs. Immutable
   Numbers, strings and tuples are immutable i.,e cannot be directly changed.
   Lists, dictionaries and sets can be changed in place.
 Sequence Types
1.   Tuple: (‘john’, 32)
     • A tuple is
         •   a sequence of comma-separated values inside a pair of parenthesis.
         •   a sequence of values much like a list.
         •   The values stored in a tuple can be any type, and they are indexed by
             integers
         •   (read Chapter 10 from “Python for Everybody” book)
     •   A simple immutable ordered sequence of items
     •   Items can be of mixed types, including collection types
      Tuples are immutable lists.
      Maintain integrity of data during program execution.
2.   Strings: “John Smith”
      Immutable
      Conceptually very much like a tuple
3.   List: [1, 2, ‘john’, (‘up’, ‘down’)]
     •   Mutable ordered sequence of items of mixed types
Similar Syntax
 Potentially   confusing:
        extend takes a list as an argument.
        append takes a singleton as an argument.
     >>> li.append([10, 11, 12])
     >>> li
     [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Operations on Lists Only
  Lists have many methods, including index, count,
  remove, reverse, sort
  >>> li = [‘a’, ‘b’, ‘c’, ‘b’]
  >>> li.index(‘b’)     # index of 1st occurrence
  1
  >>> li.count(‘b’)     # number of occurrences
  2
  >>> li.remove(‘b’) # remove 1st occurrence
  >>> li
      [‘a’, ‘c’, ‘b’]
Operations on Lists Only
>>> li = [5, 2, 6, 8]
>>> li.sort(some_function)
    # sort in place using user-defined comparison
Tuple details
          The comma is the tuple creation operator, not parens
             >>> 1,
             (1,)
          Python shows parens for clarity (best practice)
             >>> (1,)
             (1,)
          Don't forget the comma!
             >>> (1)
             1
          Trailing comma only required for singletons others
          Empty tuples have a special syntactic form
             >>> ()
             ()
             >>> tuple()
             ()
Summary: Tuples vs. Lists
                   61
Variables
  One of the most powerful features of a
   programming language is the ability to
   manipulate variables.
  A variable is a name that refers to a value.
  An assignment statement creates new variables
   and gives them values:
    Variable in python is always a reference to an object as
     in python everything, even a function, is an object.
    Variables can be reassigned at any time
    Python is dynamically typed, Meaning that variables
         can be assigned without declaring their type,
         and that their type can change.
    Values can come from
         Constants
         Computation involving values of other variables
         The output of a function.
                                                                62
Variables
    Some rules for Variable names can be
         arbitrarily long.
         contain both letters and numbers, but they cannot start with a number.
         legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase
          letter (you’ll see why later).
         The underscore character ( _ ) can appear in a name (often used in names with multiple
          words, such as my_name or airspeed_of_unladen_swallow).
         start with an underscore character, but generally avoid doing this unless we are writing
          library code for others to use.
    Custom types can be defined.
         No need to declare
    Need to assign (initialize)
         use of uninitialized variable raises exception
    Not typed
      if friendly: greeting = "hello world"
      else: greeting = 12**2
      print greeting
    Everything is a variable:
                                                                                                     63
                functions, modules, classes
                                                 Variables
   some basic rules for Python variables:
        A variable name must start with a letter or the underscore character
        A variable name cannot start with a number
        variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores
        Variable names are case-sensitive, e.g., amount, Amount and AMOUNT are three different
         variables.
        Can be any reasonable length
            66
                           Operators
                                        69
SIMPLE OPERATIONS
                    70
                                 logical operators
                                                                71
  LOGIC OPERATORS ON bools
pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)
derive = True
drink = False
both = drink and derive
print(both)
                                72
COMPARISON OPERATORS
                                                           73
                               Assignment
   Assignment:          =
   Binding a variable in Python means setting a name to hold a reference
    to some object.
        Assignment creates references, not copies
   Names in Python do not have an intrinsic type.
        Objects have types.
        Python determines the type of the reference automatically based on the
         data object assigned to it.
   You create a name the first time it appears on the left side of an
    assignment expression:
     x=3
   A reference is deleted via garbage collection after any names bound to
    it have passed out of scope.
                                                                                  74
                                                Assignment
   Accessing Non-Existent Names
        If you try to access a name before it’s been properly created (by placing it on the
         left side of an assignment), you’ll get an error.
     >>> y
     Traceback (most recent call last):
     File "", line 1, in -toplevel- y
     NameError: name ‘y' is not defined
     >>> y = 3
     >>> y
     3
   Multiple Assignment
        You can also assign to multiple names at the same time.
             >>> x, y = 2, 3
             >>> x
             2
     >>> y
     3                                                                                         75
Bitwise
 Identity: is is not
                                                                                                 78
The + Operator
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
Expressions
                                                                                      81
Order of operations
                                                                                                   82
Modulus operator
   The modulus operator works on integers and yields the
    remainder when the first operand is divided by the second.
   In Python, the modulus operator is a percent sign (%).
   The syntax is the same as for other operators:
                                                                 83
String operations
   The + operator works with strings, but it is not addition
    in the mathematical sense.
   Instead it performs concatenation, which means joining
    the strings by linking them end to end.
   For example:
                                                                84
Sets
                   86
INPUT/OUTPUT: print
                                                                        87
INPUT/OUTPUT: print
                      88
INPUT/OUTPUT: input("")
                                                                    89
Python Scripts
                 90
Python Scripts
   When you call a python program from the command line the interpreter
    evaluates each expression in the file
   From the Python Shell you select Run → Run Module or hit F5 in order to
    run or execute the Python Script
                                                  92
Plotting in Python
                     93
    Plotting in Python
   Typically you need to create some plots or charts.
                                                                    Plotting functions that
   In order to make plots or charts in Python you will
                                                                     you will use a lot:
    need an external library.
                                                                         plot()
   The most used library is Matplotlib.
                                                                         title()
         Matplotlib is a Python 2D plotting library
         Here you find an overview of the Matplotlib library:           xlabel()
          https://matplotlib.org                                         ylabel()
         import the whole library like this:                            axis()
                                                                         grid()
                                                                         subplot()
   4 basic plotting function in the Matplotlib library:                 legend()
     1.   plot()
                                                                         show()
     2.   xlabel()
     3.   ylabel()
     4.   show()
                                                                                         94
Subplots
   The subplot command enables you to display multiple plots in the same
    window.
   Example will be the Quiz
                                                                            95
References:
   For more information, you can read from “Python
    for Everybody” book
     Chapter   1 Why should you learn to write programs?
     Chapter   2 Variables, expressions, and statements
     Chapter   6 Strings
     Chapter   8 Lists
     Chapter   9 Dictionaries
     Chapter   10 Tuples
                                                            96
End
      97