傻蛋速成python

格式化

%

1
2
str="%s is %d years old"
>>> str % ("yst",123)
1
'yst is 123 years old'

format

1
'{:d} + {:d} ={:d}'.format(1,21,1+21)
1
'{1:d} + {0:d} ={2:d}'.format(1,21,1+21)
1
'{0:d} + {0:d} + {1:d}'.format(1,21)

f

1
f `{name} is {age} years old`

结构控制

for语句

1
2
3
4
5
6
7
scores=[90,45,85,76,89]

for score in scores:
if score >=60:
print("PASS")
else:
print("Failed")

in range

1
2
for i in range (10):
print(i)
1
2
3
4
5
scores=[90,45,85,76,89]

for i in range (len(scores)):
print(scores[i])

in enumerate

1
2
3
4
5
6
scores = [90, 45, 85, 76, 89, 900]

for i, score in enumerate(scores, 1):
print(i, score)


in zip

1
2
3
4
5
6
scores = [90, 45, 85, 76, 89, 900]
names = ["Alice", "Bob", "C", "D", "E", "F", "G"]

for name, score in zip(names, scores):
print(name, score)

字典

hash仅支持 immutable的对象 str /int /bool/float/tuple

func

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def foobar():
print("this is a python func")


def greet(name="Alice"):
"""this is a comment"""
print(f'hello {name}')


foobar()
greet()
greet("name")


def add(x, y):
res = x + y
return res


sum_res = add(10, 20)

闭包 函数作为返回值

1
2
3
4
5
6
7
8
9
10
# 函数的闭包
# 一个函数A中定义了函数B,并且另函数B调用了函数A的参数,且返回函数B作为返回值
def f2(x):
def f3(y):
return x + y

return f3

print(f2(1)(2))

lambda表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
def f(x):
return 3 * x ** 2 + 9 * x + 10


def diff(x, func):
delta = 1e-6
return (func(x + delta) - func(x)) / delta


print(diff(2, f))

print(diff(1, lambda x: 2 * x ** 3 + 9 * x + 9))

Chatgpt对于 python中函数是一等公民的解释

在编程语言中,”一等公民”(First-Class Citizen)是一个概念,用来描述对某种特性(通常是数据类型)的支持程度。如果一种编程语言将某个特性视为一等公民,那么该特性就会享有与其他标准数据类型相同的权利和特性。在Python中,函数被视为一等公民,这意味着函数在语言中具有特殊的地位和权利:

以下是Python中函数被称为一等公民的原因和表现:

  1. 可以赋值给变量:您可以将函数赋值给变量,然后通过该变量调用函数。

    1
    2
    3
    4
    5
    def greet(name):
    print(f"Hello, {name}!")

    my_function = greet # 将函数赋值给变量
    my_function("Alice") # 通过变量调用函数
  2. 可以作为参数传递:您可以将函数作为参数传递给其他函数。

    1
    2
    3
    4
    def apply(func, x):
    return func(x)

    result = apply(square, 5) # 将函数 square 作为参数传递给 apply 函数

    在上述示例中,apply 函数接受一个函数作为参数,然后将该函数应用于给定的参数 x

  3. 可以作为返回值:您可以从一个函数中返回另一个函数。

    1
    2
    3
    4
    5
    6
    7
    def multiplier(factor):
    def multiply(x):
    return x * factor
    return multiply

    double = multiplier(2) # 返回一个函数
    result = double(5) # 调用返回的函数

    在上述示例中,multiplier 函数返回了另一个函数 multiply,并且可以通过 double 变量来调用返回的函数。

  4. 可以存储在数据结构中:函数可以存储在列表、字典或其他数据结构中,以便在后续使用。

    1
    2
    functions = [square, cube, add]
    result = functions[0](3) # 从列表中获取函数并调用它

    上述示例中,functions 列表存储了不同的函数,可以根据需要选择并调用其中的一个。

因此,Python中的函数被称为一等公民,因为它们具有与其他数据类型(如整数、字符串和列表)相同的权利和特性。这种特性使得Python非常适合于函数式编程范式,并允许编写更灵活和可复用的代码。函数作为一等公民的特性在编写高阶函数和实现回调机制等编程任务时非常有用。

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
# 交换两个元素的值
x, y = 30, 50
print('x=%d,y=%d' % (x, y))
t = x
x = y
y = x
print("x=%d,y=%d" % (x, y))

x, y = 30, 50
print("x=%d,y=%d" % (x, y))
x, y = y, x
print("x=%d y=%d" % (x, y))

1
2
3
4
5
a, b, c, x = 2, 3, 4, 1.414
res = a * x ** 3 + b * x ** 2 + c

print(f"多项式的值为:{res:.2f}")

1
2
3
4
5
6
7
8
9
10
import sympy as sp

x = sp.symbols('x')

f = 5 * x ** 2 - 4 * x - 1

solution = sp.solve((f, x))

print(f"方程的解为:{solution}")

1
2
3
4
5
6
a, b, c, x, y, z = 2, 4, 5, 1.414, 1.732, 2.712

print(f"a={a:<7} b={b:<7} c={c:<7}")

print(f"x={x:<7.3f} y={y:<7.3f} z={z:<7.3f}")

1
2
3
4
5
6
7
8
9
10
11
12
num = int(input("请输入一个三位的正整数"))

gewei = num % 10
shiwei = (num // 10) % 10
baiwei = num // 100

print(f"百位数字:{baiwei}")

print(f"十位数字{shiwei}")

print(f"个位数字{gewei}")

1
2
3
4
5
c = float(input("请输入设施温度"))

f = (9 / 5) * c + 32
print(f"华氏温度为:{f:.1f}度")

1
2
3
4
result = math.exp(3.14)

print(f"e 的3.14次方的结果是{result:.5f}")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 输入三角形的三条边长
a = float(input("请输入第一条边的长度:"))
b = float(input("请输入第二条边的长度:"))
c = float(input("请输入第三条边的长度:"))

# 计算三角形的半周长
s = (a + b + c) / 2

# 计算三角形的面积
area = math.sqrt(s * (s - a) * (s - b) * (s - c))

# 打印结果
print(f"三角形的面积是:{area:.2f}")

1
2
3
4
5
6
radius = float(input("请输入球的半径:"))

volume = (4 / 3) * math.pi * radius ** 3

print(f"球的体积是:{volume:.1f}")

1
2
3
4
5
6
v1 = float(input("第一个数字"))

v2 = float(input("第二个数字"))

print(f"平均值:{(v1 + v2) / 2:.2f}")

1
2
3
4
5
6
7
8
9
10
11
r = float(input("圆柱形的半径"))

h = float(input("圆柱体的高"))

res1 = 2 * math.pi * (r ** 2) + 2 * math.pi * r * h

res2 = math.pi * (r ** 2) * h
print(f"圆柱体的表面积:{res1:.2f}")

print(f"圆柱体的体积:{res2:.2f}")


傻蛋速成python
http://example.com/2023/09/07/傻蛋速成python/
作者
Forrest
发布于
2023年9月7日
许可协议