Python 基础(一)

1. if the string contains both ' and " can be identifified by the escape character

print("I\'m \"OK\"")

2. None can't be understood as 0, because 0 is meaningful, and none is a special null value

3. A chinese character usually occupies 3 bytes after UTF-8 encoding, while an English character only occupies 1 byte.

print(len("中文".encode("utf-8")))

4. new features in python3.8

name = 'miku'
age = 16
print(f"{name}\'s age is {age}")

5. # type of tuple

a = ()
b = (3,)
c = (3, 4, 5)

6. for -> new features

L = ['Bart', 'Lisa', 'Adam']
for name in L:
    print(f"Hello, {name}")

7. Parameter check

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if  x >= 0:
        return x
    else:
        return -x

8. Solving equations

import math

def quadratic(a, b, c):
    if b * b - 4 * a * c < 0:
         print("测试失败")
    else:
         return (-1 * b + math.sqrt(b*b - 4 * a * c)) / (2 * a), (-1 * b - math.sqrt(b*b - 4 * a * c)) / (2 * a)

print(quadratic(1, 4 ,0))

9. One thing to keep in mind when defining default parameters: Default parameters must point to immutable objects!

10. Variable parameters, keywords parameters

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum


nums = [1, 2, 3]
print(calc(1, 2))
print(calc())
print(calc(*nums))

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)


person('Adam', 45, gender='M', job='Engineer')
*args是可变参数,args接收的是一个tuple;
**kw是关键字参数,kw接收的是一个dict。
定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。

11. 请编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法

# 利用递归函数移动汉诺塔:
def move(n, a, b, c):
    if n == 1:
        print('move', a, '-->', c)
    else:
        move(n-1, a, c, b)
        move(1, a, b, c)
        move(n-1, b, a, c)

move(4, 'A', 'B', 'C')

12. 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

def trim(s):
    index_1 = -1
    index_2 = 0
    flag_1 = False
    flag_2 = False
    for i in range(len(s)):
        if s[i].isalpha():
            flag_1 = True
        if s[len(s) - 1 - i].isalpha():
            flag_2 = True
        #  解决前面的空格
        if s[i] == " " and not flag_1:
            index_1 = i
            print(index_1)
         # 解决后面的空格
        if s[len(s) -1 - i] == " " and not flag_2:
            index_2 -= 1
            print(index_2)
    if index_2 == 0:
        return s[index_1 + 1 :]
    else:
        return s[index_1 + 1 : index_2]

print(trim("   hello  World"))

13. how to judge an object is an iterable object ? The method is to determine the Iterable type of the collections module

from collections.abc import Iterable
import collections
isinstance('abc', Iterable)  # str是否可迭代
isinstance(123, Iterable) # 整数是否可迭代
凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
Python的for循环本质上就是通过不断调用next()函数实现的
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() if isinstance(s, str) else s for s in L1]
print(L2)

# Incoming function
def add(x, y, f):
    return f(x) + f(y)

print(add(-5, 6, abs))
posted @ 2020-08-12 12:18  小喵钓鱼  阅读(14)  评论(0编辑  收藏