python programming language reference - introduction_to_python... · python programming language...

Download Python Programming Language Reference - Introduction_to_Python... · Python Programming Language Reference

Post on 29-Jun-2018

235 views

Category:

Documents

7 download

Embed Size (px)

TRANSCRIPT

  • Python Programming Language Reference

    Daniel ToppoPictet Asset Management

    20192 Financial Econometrics 2

    Spring 2017

  • Python

    2Intro Lecture

    The language basics

    http://www.google.ch/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwj539LI2MTSAhWBsiwKHUBUC6AQjRwIBw&url=http://www.icone-png.com/theme-python.php&bvm=bv.148747831,d.bGg&psig=AFQjCNEv_q7QaUUZU0MOapfDIMMp8bfIDw&ust=1488986317239372http://www.google.ch/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwj539LI2MTSAhWBsiwKHUBUC6AQjRwIBw&url=http://www.icone-png.com/theme-python.php&bvm=bv.148747831,d.bGg&psig=AFQjCNEv_q7QaUUZU0MOapfDIMMp8bfIDw&ust=1488986317239372

  • Python language Basics

    3Intro Lecture

    Sample code #1# This is a comment>>> s1 = "Hello" # 's1' holds 'Hello'>>> s2 = " World" # 's2' holds ' World'>>> print (s1 + s2) # string concatenation'Hello World'

    >>> x = (1+2)*3.4 # simple arithmetic operation>>> print (x) # let's print x in the terminal10.2

    >>> for i in [1,2,3]: # loop! statement ends with a semi-colon print (i) # we are in the loop block -> take care of indentation!123>>> if i==3: # condition! statement ends with a semi-colon print ("bingo!") # we are in the condition block -> indentation again!'bingo'

  • Python language Basics

    4Intro Lecture

    Sample code #1 Explained! Comments: start with a dash (#)

    print will print values on the terminal

    Variables are assigned with the = identifier

    Compare variables with the == identifier

    Boolean (aka logical) operators: and | or | not

    Arithmetic operators: + | - | * | / | %

    Strings operators:o + concatenationo * repetitiono % when formatting strings

  • Python language Basics

    5Intro Lecture

    Comments Starts with a dash (#) Everything that is right to the # is ignored by the interpreter To span a comment on multiple lines, every line must start

    with a dash (#)

    # This is a comment completely ignored by the interpreterprint("Hello World!") # this is another comment

    # This is a comment which# is spanned over multiple# lines

  • Python language Basics

    6Intro Lecture

    Identifiers and Keywords A python identifier is a name used to define

    o a variableo a functiono a module (file containing Python statements & definitions)o a Class (i.e. a template, specification representing an object)

    An identifier starts with o a letter [a-z], or an underscore (_) ([A-Z] for Classes)o followed by letters | underscores | digitso punctuation characters are NOT allowed within an identifier

    x = 1 # valid1abd = "Rainbow" # invalid an identifier cannot start with a digit_a_string_ = "Hello" # validlistA1 = ['a', x, "aaa"] # validx@3 = 0 # invalid @ is not allowed in an identifier

  • Python language Basics

    7Intro Lecture

    Identifiers and Keywords

    False assert del for in or while

    None break elif from is pass with

    True class else global lambda raise yield

    and continue except if nonlocal return

    as def finally import not try

    The table below lists the Python Keywords These cannot be used as ordinary identifiers (i.e., variable |

    constant | function | class, etc.) in your programs

  • Python language Datatypes & Operators

    8Intro Lecture

    Python Datatypes Overview

    Data Type ExamplesNumbers int (signed integers) float (real values) complex

    103.453.5 + 7.2j

    String "Hello"List [1, 2, 3]Tuple (1, "London", 2.2, 6j)Dictionary {"Name" : "Tony", "Age" : 15}

  • Python language Datatypes & Operators

    9Intro Lecture

    Numbers Types

    Type DescriptionInteger Limited precision

    Positive | Negative whole number (no fractional part)

    Float Real numbers Integer and fractional parts

    Complex Real and imaginary parts (a + bj) Parts are floating point numbers j represents the squared root of -1

    See Python Reference in the Appendix to this presentation for detailed information about numbers

  • Python language Datatypes & Operators

    10Intro Lecture

    Numbers FunctionsFunction DescriptionComparison functions int (x) float (x) complex (x, y)

    convert x to a integer number convert x to a floating point number convert x and y to a complex number

    (real part = x; imaginary part = y)Mathematical functions abs (x) | fabs(x) ceil (x) | floor (x) cmp (x, y) exp (x) | log (x) | log10 (x) min(x1,x2,) |

    max(x1,x2,) pow (x, y) round (x[,n]) sqrt (x)

    absolute value of x: ceiling of x: | floor of x: comparison | ln()| 10() min | max of arguments round x to n digits from the decimal

    point

  • Python language Datatypes & Operators

    11Intro Lecture

    Numbers FunctionsFunction DescriptionTrigonometric functions cos (x) | sin (x) | tan (x) acos (x) | asin (x) | atan (x) hypot (x, y) degrees (x) radians (x)

    cosine, sine, tangent arccos, arcsin, arctan Euclidian norm: 2 + 2 convert x from radians to degrees convert x from degrees to radians

    Random functions choice (seq) random() seed ([x])

    shuffle (list)

    pick a random item from sequence generates a random float: 0 1 Sets the integer starting value for

    generating a random floating number Shuffles the items of a list

  • Python language Datatypes & Operators

    12Intro Lecture

    Strings Strings are immutable ordered sequences of characters Represented in a variety of ways:

    o Single quoteso Double quoteso Triple quotes (they can span multi lines)

    See Python Reference in the Appendix to this presentation for detailed information about strings

    aString = "I'm double-quoted!" # Note the embedded 'single' quotesanotherString = 'I am "single-quoted"! # Note the embedded "double" quotesspannedString = '''I am spanned over

    multiple lines!'''

  • Python language Datatypes & Operators

    13Intro Lecture

    String OperatorsOperators DescriptionSpecific string operators + * [i] [ : ]

    in | not in

    concatenation repetition slicing : returns the ith character range slicing: returns the characters

    within the given range True if the character is | is not in the

    given string

  • Python language Datatypes & Operators

    14Intro Lecture

    String Formatting A string can be formatted using the % operator

    >>> print ("Hello! My name is %s and I have %d legs" %("John", 5))Hello! My name is John and I have 5 legs

    Operators Description %c %d | %i %e | %E %s %f %u %x | %X

    character signed decimal integer exponential notation string floating point number unsigned decimal integer hexadecimal integer

  • Python language Datatypes & Operators

    15Intro Lecture

    String Functions

    Function Description capitalize() count(str) startswith(str) | endswith(str) lower() | upper()

    len() find(str)

    isalnum() | isalpha() | isdigit()| isnumeric() | isdecimal() | isspace()

    lstrip() | rstrip() | strip()

    capitalizes the first letter of the string counts the occurrences of str in the

    string checks if the string starts | ends with str converts the string to lowercase |

    uppercase returns the length of the string finds str in the string. If found, return

    the starting index within the string, otherwise, return -1

    checks if string is alphanumeric |alphabetic | digit | numeric | decimals | only spaces

    removes all leading | trailing whitespaces | leading and trailing whitespaces

  • Python language Datatypes & Operators

    16Intro Lecture

    Sequences & Dictionaries

    aString = "Bob" aList = [1, aString, "toto"] # [1, 'Bob', 'toto']aTuple = (1, 2, aString) # (1, 2, 'Bob')aDictionary = {"Name" : aString, "Age" : 52} # {'Age': 52, 'Name': 'Bob'}

    Type Description

    String Ordered sequence of characters Defined using quotes " " or ' ' Immutable

    List Ordered sequence of mixed types Defined using square brackets [ ] Mutable

    Tuple Ordered sequence of mixed types Defined using parenthesis ( ) Immutable

    Dictionary Unordered sequence of key-value items Defined using curly braces { } Mutable

  • Python language Datatypes & Operators

    17Intro Lecture

    List & Tuple OperatorsOperators DescriptionSpecific string operators

    + * [i] [ : ]

    in | not in

    concatenation repetition slicing : returns the ith character range slicing: returns the characters

    within the given range True if the character is | is not in

    the given string

  • Python language Datatypes & Operators

    18Intro Lecture

    List & Tuple FunctionsFunction DescriptionList & Tuple methods

    cmp (list1, list2) len (list) max (list) | min (list) list (seq) | tuple (seq)

    compares element of list1 and list2 returns the total length of list return the item of list with the max | min

    value converts a tuple into a list & vice-versa

    List only methods

    append (obj) | extend (seq) insert (obj, index) count (obj) index (obj) remove (obj) | pop ()

    reverse () | sort ([func])

    appends obj | seq to the list insert obj at the given index counts how many time obj is in the list returns the lowest index of obj in list removes obj from the list | removes and

    returns the last object from the list reverses elements of the list | sorts the list

    using a comparing function func if given

  • Python language Datatypes & Operators

Recommended

View more >