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
2. Basic Data Types
2.1 Rounding functions
1 |
|
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
Expressed inside double quotes or single quotes, usually single quote for char, double quote for string, but both ok.
A string can be empty.
1
2
3
4
5ord() # returns the numeric (ordinal) code of a single character
ord("A") = 65
chr() # converts a numeric code to the corresponding character
chr(65) = 'A'ASCII table
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
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: "))Expressions Print
1
2
3
4
5>>> print("A"+"B"+"C")
ABC
>>> print("A","B","C")
A B C
>>>Python built-in numeric operations
- Operator precedence and associativity
2.4 Data types
-
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 -
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() -
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 |
|
- Relational Operators
Can be used for Number comparison and Lexicographical ordering for string comparison
in
operator1
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"
TrueBoolean operators
Operator Precedence
4. Iteration
for loop:1
2for <var> in <sequence>:
<body>
while loop:1
2while <condition>:
<body>
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;
- Post-test loopNO post-test loop in Python.
1
2
3repeat
# do sth
until x > 0
5. String Data Type
String
a sequence of characters enclosed within quotation marks (“) or apostrophes (‘).
String object are immutable1
2myName = "Dennis Liu"
myName[0] = "C" # Error!String indexing
First character is indexed by 0,
<string>[<expr>]
:value ofexpr
determines which character is selected from thestring
String slicing
<string>[<start>:<end>]
: [inclusive start, exclusive end)1
2
3
4
5
6
7
8
9
10str[: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]xString 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!
''String methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19split()
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 herewidth
: the number of spaces for printing the parameterprecision
: the number of decimal placesf
: will print out 0 to fill up the number of decimal places.
7. List
a sequence(order) of arbitrary objects of any date type
- List operations
Common Sequence Operations
Turning a list into a string
s.join(list)
: concatenatelist
into a string, usings
as a separator1
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
An immutable linear data structure(has order).
Tuples of one element must include a comma.
1
2
3
4
5
6>>> t = (1)
>>> t
1
>>> t = (1,)
>>> t
(1,)NO
append()
,insert()
,sort()
,reverse()
, anddel()
on a tuple
9. Dictionary
- 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.
- 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 |
|
Returns are view object and iterable.
10. Set
- A mutable collection of non-mutable objects which are elements of the set.
- Element: any non-mutable types (Numbers, strings, tuples are allowed, but NOT lists or sets)
- NO order in set.
- NO duplicate elements.
Empty set:
set()
, NOT{}
(a empty dictionary)Set operator
|
=intersection()
&
=union()
-
=difference()
^
=symmetric_difference()
11. Function
- 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
value-returning function
has
return
statementallows a function to return more than one value (in terms of a
tuple
)- Positional and keyword arguments
positional argument: based on the position in the argument list;
keyword argument: specified by parameter name
1 |
|
The use of global variables is considered BAD programming practice.
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