python基础语法使用

"""
多行注释
"""
# 单行注释
print("hello world")

# 变量赋值
money = 50
print("钱包有:",money)

# 输出类型信息
print(type(1))

# 类型转换
str(1)
int("2")
float("2.1")

# 算术运算符
print("1 + 1 = ",1 + 1)
print("2 - 1 = ",1 + 1)
print("3 * 3 = ",3 * 3)
print("4 / 2 = ",4 / 2)
print("11 // 2 = ",11 // 2) # 整除
print("9 % 2 = ",9 % 2)
print("2 ** 2 = ",2 ** 2) # 指数

# 转义字符\
print("\"h\"")

# 字符串拼接
name = "hdb"
print("==" + name + "==") # 不允许非字符类型
age = 18
height = 1.75
print("==%s==%d==%f" % (name, age, height))

# 浮点数精度控制
f = 1.12545
print("==%.2f==" % f) # 会四舍五入 1.13

# 字符串格式化
name = "hdb"
print(f"=={name}==")

# 输入
name = input("提示语:") # 输入类型都为字符串
print("name:%s" % name)

# bool 类型
b1 = True
b2 = False

# if语句
age = 1
if age > 18:
    print(1)
elif age >10:
    print(0)
else:
    print(-1)
# 随机数
import random
num = random.randint(1,10)

# while 语句
i = 1
sum = 0
while i <= 100:
    sum += i
    i += 1
print(sum)

# for 语句
name = "hdb"
for x in name:
    print(x)

# range 获取简单数据序列 range(num1,num2,step) (含头不含尾)
arr = range(5) # [0,1,2,3,4]
arr = range(5,10) # [5,6,7,8,9]
arr = range(0,10,2) # [0,2,4,6,8]

# continue break 语句
for x in arr:
    print(x)
    continue
    break
    print("===")

# 函数定义 def
def my_len(data):
    count = 0
    for x in data:
        count += 1
    return count

my_len("xxx")

# None 可以理解为False
def check_age(age):
    if age < 0 :
        return None
    else:
        return 1

result = check_age(-1)
if not result:
    print("error")

# 函数说明
def add(x,y):
    """
    add 函数
    :param x:
    :param y:
    :return:
    """
    return x + y

# 函数内部声明局部变量
num = 100
def test():
    global num
    num = 200

test()
print(num) # 200

# 列表 list使用
name_list = ['java','python','C++']
print(name_list[0]) # java
print(name_list[-1]) # C++
print(type(name_list)) # 
print(name_list.index('C++')) # 2
name_list[0] = 'go' # 修改
name_list.insert(1,'C#') # 插入
name_list.append('scale') # 追加一个
name_list.extend(['JS','LUA']) # 追加一批元素
del name_list[2] # 删除指定元素
element = name_list.pop(0) # 取出元素
name_list.remove('C#') # 删除出现的第一个元素
count = name_list.count('JS') # 统计某元素数量
count = len(name_list) # 统计容器内元素个数
name_list.clear() # 清空元素

# 元组 tuple
t1 = ('java',True,1)
type(t1) # 
t1[0] # java
t1.index("java") # 0
t1.count("java") # 1
len(t1) # 3

# 字符串定义操作 只读不能被修改
my_str = "java python C++ go javascript"
my_str[1] # a
my_str[-1] # t
my_str.index("ava") # 1
my_str.replace("java","mysql") # mysql python C++ go mysqlscript
my_str.split(" ") # ['java', 'python', 'C++', 'go', 'javascript']
my_str = "  java python C++ go javascript  "
my_str.strip() # 去除前后空格
my_str = "12java python C++ go javascript21"
my_str.strip("12") # java python C++ go javascript
my_str.count("java") # 2
len(my_str) # 33

# 序列切片 序列包含(列表,元组,字符串)
my_list = [0,1,2,3,4,5,6,7,8,9]
my_list[1:4] # [1, 2, 3]
my_list[1:9:2] # [1, 3, 5, 7]  1到9步长为2
my_list[:] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 起始到结尾 步长为1
my_list[::2] # [0, 2, 4, 6, 8] 起始到结尾 步长为2
my_list[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
my_list[3:1:-1] # [3, 2]

# 集合 set 去重、乱序
my_set = {"java","python","scale","java","python","scale"}
print(my_set) # {'python', 'scale', 'java'}
type(my_set) # 
my_set.add("javascript")
my_set.remove("java")
my_set.pop() # 随机取一个元素
my_set.clear() # 清空集合

set1 = {1,2,3}
set2 = {1,4,5}
set3 = set1.difference(set2) # 集合差集,原集合不变
set1.difference_update(set2) # 集合差集,set1集合改变,set2不变
set3 = set1.union(set2) # 合并集合 , set1、set2不变


# 字典 dict key-value 不重复
my_dict = {} # 空字典
my_dict = dict() # 空字典
my_dict = {"java": 99,"python":88}
type(my_dict) # 
my_dict['java'] # java
my_dict['java'] = "100" # 赋值/添加
my_dict.pop("java") # 取出
my_set.clear() # 清空
my_dict.keys() # 获取全部key
len(my_dict) # 计算元素数量

# 函数 max()  min()
my_list = [1,2,3,4,5,6]
max(my_list) # 最大元素 6
min(my_list) # 最小元素 1

# 容器转换 list() tuple() str() set()
my_list = [1, 2, 3, 4, 5, 6]
my_tuple = (1, 2, 3, 4, 5, 6)
my_str = "abcdefg"
my_set = {1, 2, 3, 4, 5, 6}
my_dict = {"java": 1, "python": 2}

list(my_list)  # [1, 2, 3, 4, 5, 6]
tuple(my_list) # (1, 2, 3, 4, 5, 6)
str(my_list)   # [1, 2, 3, 4, 5, 6] 字符串
set(my_list)   # {1, 2, 3, 4, 5, 6}

# 排序 sorted()
my_list = [3, 4, 2, 1, 6, 5]
my_tuple = (3, 4, 2, 1, 6, 5)
my_str = "abcdefg"
my_set = {3, 4, 2, 1, 6, 5}
my_dict = {"java": 1, "python": 2}
# 升序
sorted(my_list) # [1, 2, 3, 4, 5, 6]
sorted(my_tuple) # [1, 2, 3, 4, 5, 6] 会自动转为列表
sorted(my_str) # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
sorted(my_set) # [1, 2, 3, 4, 5, 6]
sorted(my_dict) # ['java', 'python']
# 降序
sorted(my_list,reverse=True) # [6, 5, 4, 3, 2, 1]
# 多返回值
def test_return():
    return 1, 2, 3


x, y, z = test_return()

# 函数传参方式
def fun1(p1, p2):
    return 0


fun1(1, 2) # 位置传参
fun1(p2=2, p1=1) # 关键字传参


def fun2(p1=1, p2=2): # 缺省函数
    return 0


def fun3(*args): # 不定长传参  args为元组
    print(args)


fun3(1,"a") # (1, 'a', 3)


def fun4(**kwargs): # 不定长传参 key-value形式传参 kwargs为字典
    print(kwargs)

fun4(name="java",age =18) # {'name': 'java', 'age': 18}

# 函数回调
def fun5(sum):
    print(sum(1,2))

def sum(a,b):
    return a+b

fun5(sum)

# lambda 匿名函数
fun5(lambda x,y:x+y)
# 文件读取
f = open("1.txt","r",encoding="UTF-8")
print(type(f)) # 
content = f.read() # 读取所有内容
content = f.read(2) # 读取前两个字符
lines = f.readlines() # 读取所有行 (受指针影响)
line = f.readline() # 一次读取一行

for line in f: # 读取文件每一行
    print(line)

f.close() # 文件关闭

with open("1.txt","r",encoding="UTF-8") as f: # 会自动关闭close
    for line in f:  # 读取文件每一行
        print(line)

# 文件写入 w模型覆盖写入  a追加写入
with open("1.txt","w",encoding="UTF-8") as f:
    f.write("java")

with open("1.txt","a",encoding="UTF-8") as f:
    f.write("python")

# 异常所有捕获
try:
   f = open("2.txt", "r", encoding="UTF-8")
except:
   print("异常:文件不存在")
   f = open("2.txt", "w", encoding="UTF-8")
else:
    print("没有异常")
finally:
    f.close()

try:
    print(1/0)
except Exception as e:
    print(e)
else:
    print("没有异常")

# 捕获指定异常
try:
    1 / 0
    print(name)
except (NameError,ZeroDivisionError) as e:
    print("变量未定义异常")
    print(e)

# 模块导入
import time # 导入全部函数
time.sleep(5)

import time as t # as特定别名
t.sleep(5)

from time import sleep # 导入指定函数
sleep(5)

from time import sleep as sl # 导入指定函数
sl.sleep(5)

from time import * # 导入全部函数
sleep(5)
# main 函数
if __name__ == '__main__':
    print(1)

__all__ = ["testA"] # 指定外部能引用函数

def testA():
    print("A")

def testB():
    print("B")

你可能感兴趣的:(python,python)