Python Basic Note

Made by Mike_Zhang


所有文章:
Introductory Probability Course Note
Python Basic Note
Limits and Continuity Note
Calculus for Engineers Course Note
Introduction to Data Analytics Course Note
Introduction to Computer Systems Course Note


个人笔记,仅供参考
FOR REFERENCE ONLY

Course note of COMP1002 Computational Thinking and Problem Solving, The Hong Kong Polytechnic University, 2021.


1. Identifiers

Begin with a letter or underscore (“_”), CAN NOT start with digits;
Followed by any sequence of letters, digits, or underscores(“_”) ;
“-”, “.” and many other symbols are not allowed;
Case sensitive;
CANNOT be Python’s keywords

Python’s keywords


2. Basic Data Types

2.1 Rounding functions

1
2
3
4
5
6
7
8
9
import math
#1
round(x,n) # built-in (“四舍五入” 不完全是)round to n decimal places
#2
math.ceil(x) # round up
math.ceil(4.5) = 5
#3
math.floor(x) # round down
math.floor(5.45) = 5

When using the floating point number representation, most decimal fractions can’t be represented exactly as a float, there may be infinite 0 and 1s.

2.2 String

  1. Expressed inside double quotes or single quotes, usually single quote for char, double quote for string, but both ok.

  2. A string can be empty.

  3. 1
    2
    3
    4
    5
    ord() # returns the numeric (ordinal) code of a single character
    ord("A") = 65

    chr() # converts a numeric code to the corresponding character
    chr(65) = 'A'
  4. ASCII table

  5. Escape character

Code Result
\‘ Single Quote
\“ Double Quote
\n New Line
\t Tab
\r Carriage Return
\b Backspace
\f Form Feed
\\ Backslash
\ooo ASCII character represented by $ooo_{oct}$, e.g. “\063” = “3”.
\xhh ASCII character represented by $hh_{hex}$, e.g. “\x41” = “A”.
\uhhhh Unicode character represented by $hhhh_{hex}$, e.g. “\u2190” = “<-“,“\u5927” = “⼤”, “\u3042” = “あ”, “\u3184” = “ㆄ”.

2.3 Expression

  1. Simultaneous Assignment

    1
    2
    3
    4
    5
    6
    7
    8
    # 1 RHS and assign them to the variables on the LHS. 
    <var>, <var>, … = <expr>, <expr>, …
    # 2
    x, y = y, x # swap
    # 3
    sum, diff = x+y, x-y
    # 4
    x, y = eval(input("Input the first and second numbers separated by a comma: "))
  2. Expressions Print

    1
    2
    3
    4
    5
    >>> print("A"+"B"+"C")
    ABC
    >>> print("A","B","C")
    A B C
    >>>
  3. Python built-in numeric operations

Python built-in numeric operations

  1. Operator precedence and associativity

Operator precedence and associativity

2.4 Data types

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    type(x) # returns the data type of x which could be a literal or variable.

    int(x), float(x) # explicit type conversion

    # [Example]
    >>> int(2.2) # OK
    2
    >>> int("22") # OK
    22
    >>> int("2.2") # Error!
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '2.2'

    >>> float(2) # OK
    2.0
    >>> float(1.2) # OK
    1.2
    >>> float("2.2") # OK!
    2.2
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    eval() # The arguments are a string
    # The expression argument is parsed and evaluated as a Python expression

    #[Example]
    >>> eval("1.2")
    1.2
    >>> eval("1")
    1
    >>> eval("1+2")
    3
    >>> eval(1)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: eval() arg 1 must be a string, bytes or code object
    # must be a String

    x, y = eval(input("Input the first and second numbers separated by a comma: "))
    # can not use int()
  3. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    >>> type(6+3)
    <class 'int'>

    >>> type(6.0+3.0)
    <class 'float'> # !!!

    >>> type(6.0+3)
    <class 'float'>

    >>> type(6.00+3.00)
    <class 'float'>

    >>> type(6*3)
    <class 'int'>

    >>> type(6.0*3.0)
    <class 'float'>

    >>> type(6.0*3)
    <class 'float'>

    >>> type(6/3)
    <class 'float'> # !!!

    >>> type(6.0/3.0)
    <class 'float'>

    >>> type(6.0/3)
    <class 'float'> # !!!

3. Condition

boolean value: True, False, both in upper case.

1
2
3
4
>>> print(int(True))
1
>>> print(int(False))
0
  1. Relational Operators

Can be used for Number comparison and Lexicographical ordering for string comparison

Relational Operators

  1. in operator

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    >>> 10 in [10, 20, 30, 40] 
    True
    >>> 10 not in [10, 20, 30, 40]
    False
    >>> "blue" in ["red", "yellow", "black"]
    False
    >>> "blue" not in ["red", "yellow", "black"]
    True
    >>> "o" in "peter paul and mary"
    False
    >>> "p" in "peter paul and mary"
    True
  2. Boolean operators
    Boolean operators

  3. Operator Precedence
    Operator Precedence


4. Iteration

for loop:

1
2
for <var> in <sequence>: 
<body>

while loop:

1
2
while <condition>:
<body>

  1. range(10): [0,10)

    range (inclusive start, exclusive stop, step)

break: immediately exit the deepest enclosing loop;
continue: immediately skip the current time of loop, go to the next time of loop;

  1. Post-test loop
    1
    2
    3
    repeat
    # do sth
    until x > 0
    NO post-test loop in Python.

5. String Data Type

  1. String

    a sequence of characters enclosed within quotation marks (“) or apostrophes (‘).
    String object are immutable

    1
    2
    myName = "Dennis Liu" 
    myName[0] = "C" # Error!
  2. String indexing
    First character is indexed by 0,
    <string>[<expr>]:value of expr determines which character is selected from the string

  3. String slicing
    <string>[<start>:<end>]: [inclusive start, exclusive end)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    str[:5] = str[0:5]
    str[5:] = str[5:<end>]

    #start from left to end at right

    str[-3:-1]√
    str[-1:-3]x

    str[1:3]√
    str[3:1]x
  4. String operations
    String operations

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> str = 'Liu'

    >>> str[7] # Error!
    IndexError: string index out of range

    >>> str[0:7] # OK!
    'Liu'
    >>> str[7:] # OK!
    ''
  5. String methods

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    split()
    lower()
    upper()
    append()
    capitalize()

    >>> student = "first_name last_names student_ID"

    >>> student.split()
    ['first_name', 'last_names', 'student_ID']

    >>> student.lower()
    'first_name last_names student_id'

    >>> student.upper()
    'FIRST_NAME LAST_NAMES STUDENT_ID'

    >>> student.capitalize()
    'First_name last_names student_id'

6. String formatting

"{<index>:<width>.<precision><type>}".format(<values>)

  • index: indicate which parameter to insert here
  • width: the number of spaces for printing the parameter
  • precision: the number of decimal places
  • f: will print out 0 to fill up the number of decimal places.

String formatting


7. List

a sequence(order) of arbitrary objects of any date type

  1. List operations

List operations

  1. Common Sequence Operations
    Common Sequence Operations

  2. Turning a list into a string

    s.join(list): concatenate list into a string, using s as a separator

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    >>> aList = ["Hong-Va", "Leong"] 

    >>> "Dennis Liu".join(aList)
    'Hong-VaDennis LiuLeong'

    >>> " ".join(aList)
    'Hong-Va Leong'

    >>> aList = ["A", "B", "C", "D"]
    >>> "".join(aList)
    'ABCD'

8. Tuple

  1. An immutable linear data structure(has order).

  2. Tuples of one element must include a comma.

    1
    2
    3
    4
    5
    6
    >>> t = (1)
    >>> t
    1
    >>> t = (1,)
    >>> t
    (1,)
  3. NO append(), insert(), sort(), reverse(), and del() on a tuple


9. Dictionary

  1. A dictionary is a mutable, associative data structure of variable length.
  • The key can be of any immutable type.
  • The values can be of any type and are unordered.
  1. Dictionary operators
    Dictionary operators

items(): Returns all the key-values pairs as a list of tuples, <class 'dict_items'>
keys(): Returns all the keys as a list, <class 'dict_keys'>
values(): Returns all the values as a list, <class 'dict_values'>

1
2
3
4
5
6
7
8
9
10
>>> dictA = {1:"a",2:"b",3:"c"}

>>> dictA.items()
dict_items([(1, 'a'), (2, 'b'), (3, 'c')])

>>> dictA.keys()
dict_keys([1, 2, 3])

>>> dictA.values()
dict_values(['a', 'b', 'c'])

Returns are view object and iterable.


10. Set

  1. A mutable collection of non-mutable objects which are elements of the set.
  2. Element: any non-mutable types (Numbers, strings, tuples are allowed, but NOT lists or sets)
  3. NO order in set.
  4. NO duplicate elements.
  5. Empty set: set(), NOT {} (a empty dictionary)

  6. Set operator
    Set operator

    | = intersection()
    & = union()
    - = difference()
    ^ = symmetric_difference()


11. Function

  1. non-value-returning function

no return statement, but has side effect
side effect is an action other than returning a function value, such as displaying output on the screen

  1. value-returning function

    has return statement

  2. allows a function to return more than one value (in terms of a tuple)

  3. Positional and keyword arguments

    positional argument: based on the position in the argument list;
    keyword argument: specified by parameter name

1
2
3
4
5
6
7
8
f(parameter = argument)
f(x = 1) # keyword argument
f(1) # positional argument

f(na,n2,n3)
f(n1=1,2,3) # Error: SyntaxError: positional argument follows keyword argument
f(n1=1,n2=2,3) # Error
f(1,2,n3=3) # OK
  1. The use of global variables is considered BAD programming practice.

  2. docstring

function_name.__doc__ to get the docstring of a function.

a string literal denoted by triple quotes used in Python for providing the specification of certain program elements.
MUST be indented at the same level.
The first block of quoted text to appear in the module.


12. File Processing

file = open("test.txt","r")

<filevar>.read():

  • returns the entire remaining contents of the file as a single (possibly large, multi-line) string.

<filevar>.readline():

  • returns the just one next line of the file. This is all text up to and including the next newline character.

<filevar>.readlines():

  • returns a list of the remaining lines in
    the file. Each list item is a single line including the newline characters.

<filevar>.close()

  • It is important to close the file.

References

Slides of COMP1002 Computational Thinking and Problem Solving, The Hong Kong Polytechnic University


个人笔记,仅供参考,转载请标明出处
FOR REFERENCE ONLY

Made by Mike_Zhang




Python Basic Note
https://ultrafish.io/post/Python-basic-note/
Author
Mike_Zhang
Posted on
December 18, 2021
Licensed under