My Python Notes

1 Something about print

syntaxexplanation
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
syntaxexplanation
+, -, *, /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

syntaxexplanation
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:

syntaxexplanation
and, or, notlogical operators
==, <, <=, !=comparison operators

3.3 Numbers

Floating points numbers: 1.0e-6 is 1 × 1 0 − 6 1 \times 10^{-6} 1×106.

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:

syntaxexplanation
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]
syntaxexplanation
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, then a[i:j] and a[i:j:k] are empty lists, for any value of k.
  • If j < < < i, then a[i:j] and a[i:j:k] are empty lists, for positive values of k.

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
syntaxexplanation
range(j) 0 0 0, 1 1 1, 2 2 2, …, j − 1 j-1 j1; 共 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 j1; 共 j − i j-i ji个.
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+mj1.

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 access my_list[4], but my_list only has elements up to my_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 type
  • ValueError: raised when an operation or function is applied to an object with the right type, but an invalid value. For example, the int() function can cast a string to an integer, if the string can be interpreted as a number.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值