Contents
1 Something about print
syntax | explanation |
---|---|
print(str1, str2, sep = "") | print strings separately |
print(str1 + str2) | print strings as one string |
print(f'{my_var}') | f-string interpret what inside the {} |
print('%type' %my_var) | %d : integer; %f : float; %s : string; %b : binary; (doc) |
print(\n) | print use escape characters |
print(f'{my_var:n[type]}') | print the variable at a certain length |
{:<} , {:>} , {:^} | left aligned, right aligned, centred |
syntax | explanation |
---|---|
+ , - , * , / | addition, subtraction, multiplication, division |
** | exponentiation |
// | integer division |
% | modulus; the remainder of a deviation |
2 Import modules
import numpy as np
print(np.sin(np.pi))
3 Variables and objects
type()
: check data types.
-
Numeric: int, float, complex;
-
Sequence: str, list, range, tuple
-
Boolean
-
Set
-
Dictionary
-
number objects and string objects
3.1 Strings
syntax | explanation |
---|---|
my_str[i] | returns the
i
+
1
i+1
i+1th character in string |
my_str[-i] | returns the i i ith from the end |
len(my_str) | the length of the string |
max(my_str) , min(my_str) | alphabetically |
sorted(my_str) | from smallest to largest |
my_str.capitalize() | capitalize the first letter of the string |
my_str.split() | split the string |
3.2 Booleans
Operators:
syntax | explanation |
---|---|
and , or , not | logical operators |
== , < , <= , != | comparison operators |
3.3 Numbers
Floating points numbers: 1.0e-6
is
1
×
1
0
−
6
1 \times 10^{-6}
1×10−6.
3.4 Type casting
int()
, float()
, str()
.
bool(0)
and bool('')
are false.
3.5 List
List can contain almost any other object.
my_list = ['my', 1, 4.5, ['you', 'they'], 432, -2.3, 33]
emplist = []
print(list_1 + list_2)
print('hellow'+'world') # "helloworld"
my_list.append('extar') # add an item to the end of a list
print(my_list[3][1]) # the outcome is "they"
print(sorted(numberlist)) # sort a list
print(12 * my_list) # create a list with 12 repetition of my_list
print('you' in my_list[3]) # check if something is in a list
Useful tools:
syntax | explanation |
---|---|
len(my_list) | the length of the list |
my_list.append('a new element') | add a new element to the list |
Slicing:
a = [2, 5, 4, 8, 8]
print(a[1:3]) # the 2nd and 3rd | [5, 4]
print(a[2:]) # the 3rd to the last | [4, 8, 8]
print(a[:-2]) # the 1st to the 3rd from the last | [2, 5, 4]
syntax | explanation |
---|---|
my_list[start:stop] | from start to stop-1 共stop-start个 |
my_list[start:] | from start to len(l)-1 |
my_list[:stop] | from 0 to stop-1 |
my_list[start:stop:step] | from start to stop-1, with increment step |
my_list[::step] | from 0 to len(l)-1, with increment step |
my_list[::] , my_list[:] | all the elements |
- If
j
= = =i
, thena[i:j]
anda[i:j:k]
are empty lists, for any value ofk
. - If
j
< < <i
, thena[i:j]
anda[i:j:k]
are empty lists, for positive values ofk
.
4 if
statements
if my_condition:
[some instructions]
my_condition
is a Boolean object.
if cond_1:
[some instructions]
elif cond_2:
[other instructions]
else:
[other instructions]
5 Loops
5.1 for
loops
for i in my_seq:
[some instructions]
- ranges: a sequence type
syntax | explanation |
---|---|
range(j) | 0 0 0, 1 1 1, 2 2 2, …, j − 1 j-1 j−1; 共 j j j个. |
range(i, j) | i i i, i + 1 i+1 i+1, i + 2 i+2 i+2, …, j − 1 j-1 j−1; 共 j − i j-i j−i个. |
range(i, j, k) | i i i, i + k i+k i+k, i + 2 k i+2k i+2k, …, i + m i+m i+m; i + m ≤ j − 1 i+m \leq j-1 i+m≤j−1. |
5.2 while
loops
while my_condition:
[some instructions]
Use break
to exit the loop conditionally:
while my_condition:
[some instructions]
if my_condition:
break
6 Defining function
def my_func(inputs):
[function body]
return outputs
Outputs can be variables separated by commas.
7 Debugging and troubleshooting
Built-in exception types:
IndexError
: a sequence subscript is out of range. r instance, here, we’re trying to accessmy_list[4]
, butmy_list
only has elements up tomy_list[3]
.NameError
: the variable referred to does not exist – there is no box in memory with this label. This often comes up when you mistype a variable name.SyntaxError
: the code is not syntactically correct – it is not valid Python, so Python doesn’t know how to interpret it.TypeError
: a very common error to see when learning Python! This means that an operation or a function is applied to an object of the wrong typeValueError
: raised when an operation or function is applied to an object with the right type, but an invalid value. For example, theint()
function can cast a string to an integer, if the string can be interpreted as a number.