提交 800850cd 编写于 作者: W wsb

增加python基础语法学习笔记

上级 2d67e324
......@@ -84,4 +84,115 @@ print(sq2)
sq2[:] = [] # 清空列表
# 内置函数 len() 也支持列表:
print(len(sq))
\ No newline at end of file
print(len(sq))
# if语句
x = 100
y = 120
if x == y:
print("x==y")
else:
print("x!=y")
# 多层if
if x == 100:
print("x==100")
elif x == y:
print("x==y")
else:
print("x未匹配到合适的值")
# for循环:遍历集合
words = ['hello', 'world', 'cat']
for w in words:
print(w)
# range():生成数字序列
for i in range(10):
print(i)
# range指定开始0、结束100、步长20
for j in range(0, 100, 20):
print(j) # 0,20,40,60,80
# range() 和 len() 组合在一起,可以按索引迭代序列:
for i in range(len(words)):
print(i, words[i])
# sum() 是一种把可迭代对象作为参数的函数:计算集合的和
print(sum(range(0, 101))) # 计算1~100的和
# 循环中的 break、continue 语句及 else 子句¶
for n in range(1, 10):
for x in range(2, n):
if n % x == 0:
print(n, '相等', x, '*', n // x)
# continue 语句
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue # 表示继续执行循环的下一次迭代:
print("Found an odd number", num)
# pass 语句不执行任何操作。语法上需要一个语句,但程序不实际执行任何动作时,可以使用该语句。
class student:
pass
# 将一个目标值与一个或多个字面值进行比较:
x = 1
def http_error(x):
match x:
case 0:
return "错误"
case 1:
return "成功"
print(http_error(1))
print(http_error(0))
# 函数使用关键字 def,后跟函数名与括号内的形参列表。函数语句从下一行开始,并且必须缩进。
def func(n, m, s):
"""文档字符串,用于说明方法的作用"""
return n * m + s
print(func(12, 34, 78))
print(func) # 不返回值
f = func # 把函数赋值给临时变量f
print(f(2, 8, 7)) # 使用F来调用函数
# 为参数指定默认值是非常有用的方式。调用函数时,可以使用比定义时更少的参数,
def test(x, y=10, z=20):
return x * y * z
print(test(10))
# 调用函数时,使用任意数量的实参
def fc(*hubby):
s = [hubby]
print(len(s))
return s
# 输入任意多个参数
print(fc('qq', 'wechat', 'basketball', 'car', 'deck'))
# Lambda 表达式¶
def sum(n): # 返回两个数的和
return lambda x: x + n # lambda表达式
f = sum(100)
print(f(0))
print(f(100))
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册