python 0基础-01

数据类型

可变类型:列表,字典
不可变类型:元组, 字符串,整数, 集合

变量

作用:

​ 变量是用来存储内容,方面后面掉调用的一个东西。他可用来被赋值、被修改、被调用。

命名规则:

1. 只能是以字母,数字,_ 来命名;不可以是空格、特殊字符等;
2. 不能以中文为变量名;
3. 不能以数字开头;
4. 保留字不能用来当作变量;
5. 命名最好简单易懂;
6. python属于严格模式,字母的大小写表示不同的东西。
eg:
	name = "Alex li"
	
	name2 = name
	
	print(name, name2)
    # Alex li Alex li
    
    name = "Jack"
    
    print(name, name2)
    # Jack Alex li

编码

编码方式:

1. ASCII :美国人使用的,一共128个字符
2. GB2312:支持中文的第一张表,国标2312
3. GBK:国标K
4. Unciode:万国码(UTF-8, UTF-16, UTF-32)

注释

注释方法:注释后面默认带1个空格,看起来比较美观,不加也行。

# 单行注释,也可以放到代码行的后面

'''
多行注释
'''

"""
多行注释
"""

# print("hello")
print("hello") # 这是一个打印语句

'''
这里面的内容
不会被编译
'''

算数运算符

+: print(1+2)
-: print(2-1)
*: print(1*2)
/: print(1/2) 
//:print(1+2) # 取整数
%: print(1+2) # 取余数

逻辑运算符

1. or :逻辑或, 找False
2. and: 逻辑与,找True
3. not: 逻辑非
4. 逻辑运算符的优先级
   **not > and > or**
eg:
a = 1 or 2 and 3
print(a) # 1

b = 1 and 2 or 3
print(b) # 2

查看变量的类型

使用type()函数来查看当前变量的类型。

一般类型有:

str: 字符串                a = ""         print(type(a)) <class 'str'>
int:整数                  b = 12         print(type(b)) <class 'int'>
float: 浮点数              c = 3.14       print(type(c)) <class 'float'>
bool: 布尔值(True, False) d = True       print(type(d)) <class 'bool'>
set: 字典                  e = {}         print(type(e)) <class 'dict'>
list:列表                 f = []         print(type(f)) <class 'list'>
tuple: 元组                j = ()         print(type(j)) <class 'tuple'>
set:集合                   h = set()      print(type(h)) <class 'set'>

表达式语句

if...else...语句 + while语句

age_of_princal = 54

input_num = 0

while input_num < 3:
    guess_asr = int(input(">>:"))
    if age_of_princal > guess_asr:
        print(f"太小了,试着往大了猜!还有{2 - input_num }次机会哦!")
    elif age_of_princal < guess_asr:
        print(f"太大了,试着往小了猜!还有{2 - input_num }次机会哦!")
    else:
        print("恭喜你,猜对了!")

    input_num += 1

类型的强制转化

a = 12 # type为number
print(str(a)) # 转为str

b = "12" # 字符串
print(int(b))    # 转为整数 
print(float(b))  # 转为浮点数

c = 1
print(bool(c))  # 转为布尔值

格式化输出

使用format方法或者%占位符来完成

name = input("Enter your name: ")
age = input("Enter your age: ")
job = input("Enter your job: ")
salary = input("Enter your salary: ")

if salary.isdigit():
    salary = int(salary)
else:
    exit("must input isdigit")

msg = '''
-------- info of %s ----------
Name: %s
Age: %s
Job: %s
salary: %s
-------- end ----------
''' % (name, name, age, job, salary)


print(msg)

数据类型

数字:

​ 整数:int

​ 浮点数: float

字符串:

列表:

  1. 增删改查:
有三个参数:list[起始位置:结束位置:步长]
最后一个参数代表没隔多少增加
# 增删改查
list_ = ["唐僧", "孙悟空", "猪悟能", "沙悟净"]
增  切片
print(list_[1:]) # 从1取到最后
print(list[1:-1] # 从1取到倒数第二个
print(list_[1:-1:1]) # 从1取到倒数第二个,一个一个的取 ,步长为1
print(list_[1::-1:2]) # 从1取到倒数第二个,隔一个值取,步长为2
print(list_[1::-1]) # 从1开始倒着取

增 添加(两个方法:append(), insert())
list_.append("小白龙") # 在列表的末尾追加
print(list_) # ["唐僧", "孙悟空", "猪悟能", "沙悟净", "小白龙"]

list_.insert(1, "小白龙") # 在1的位置插入一个值
print(list_)# ["唐僧", "小白龙", "孙悟空", "猪悟能", "沙悟净"]

删 (三个方法:del, remover, pop)
del list_[0]  # 把位置0上的元素删掉了,返回一个新的列表
print(list_) #  ["孙悟空", "猪悟能", "沙悟净"]
注:del 方法可以直接把列表变量从内存中删除,一般不建议使用
    eg: del list_
    print(list_) # 报错:NameError: name 'list_' is not defined. Did you mean: 'list'?

# pop中可以有一个参数,也可以没有参数,当有参数时,表示删除某个位置上的元素,
								当没有参数时,表示删除最后一个元素
list_.pop()  # 删除最后一个元素,并返回删除的那个元素的值
print(list_) # ["唐僧", "孙悟空", "猪悟能"]

list_.pop(1) # 删除位置1上的元素,并返回被删除的元素的值
print(list_) # ["唐僧", "猪悟能", "沙悟净"]

# remove 有一个参数, 该参数为被删除元素的值, 并返回被删除后的新列表
list_.remove("沙悟净")
print(list_) # ["唐僧", "孙悟空", "猪悟能"]
# 注:remove方法只能删除列表中查到的第一个值,如果该值存在多次,则需要循环删除

list_.clear() # 清空列表

改
# 通过索引位置修改
list_[0] = "白骨精"
print(list_) # ["白骨精", "孙悟空", "猪悟能", "沙悟净"]

list_[start:end] = [a, b, c] # 修改获取到索引位置的
2. 排序
# sort方法,可以对列表中的元素进行排序,改变原列表,其中默认为升序,倒序时,需要传参 reverse=True
# 该排序顺序时按照ASCII表中的位置进行排序的
list_ = [1,5,3,4,8,6,12,11,16,1,4,56]
list_.sort() # 默认升序
print(list_) # [1, 1, 3, 4, 4, 5, 6, 8, 11, 12, 16, 56]

list_.sort(reverse=True) # 降序
print(list_) # [56, 16, 12, 11, 8, 6, 5, 4, 4, 3, 1, 1]

# sorted() 临时排序, 其中默认为升序,倒序时,需要传参 reverse=True
print(sorted(list_)) # 临时排序,不改变原数组,[1, 1, 3, 4, 4, 5, 6, 8, 11, 12, 16, 56]
print(list_) #原数组不变 [1, 5, 3, 4, 8, 6, 12, 11, 16, 1, 4, 56]

print(sorted(list_, reverse=True)) # 临时倒序 [56, 16, 12, 11, 8, 6, 5, 4, 4, 3, 1, 1]
  1. 列表反转(反向打印)
# reverse()方法,反转原列表,改变原列表
list_m = ["唐僧", "孙悟空", "猪悟能", "沙悟净"]
list_.reverse()
print(list_) # ['沙悟净', '猪悟能', '孙悟空', '唐僧']
  1. 获取列表的长度
# len()方法,获取到列表的长度, 返回一个数值
list_m = ["唐僧", "孙悟空", "猪悟能", "沙悟净"]
print(len(list_)) # 4
  1. 统计元素次数
# count()方法,统计列表中某个元素出现的次数,该方法需要一个参数
# 该方法只能统计到第一层列表的值出现的次数,如果出现嵌套列表,则嵌套列表中出现的元素则不会被统计
list_= [1,2,3,4,5,4,2,1,3,5,[1,2,5,43,]]
print(list_.count(1)) # 2
  1. 合并两个列表
# extend()方法,可以将b列表中的元素添加到a列表中取,且不改变b列表
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a) # [1,2,3,4,5,6]
print(b) # [4,5,6]

# 列表拼接
c = a+ b
print(c)
  1. 获取元素的索引值
# index()方法获取某个列表中元素的索引值, 只有一个参数,每次只能获取一个,且每次只返回在列表中查找到的第一个值的索引位
list_= ["唐僧", "孙悟空", "猪悟能", "沙悟净"]
print(list_.index("孙悟空")) # 1

# 小练习
# 取第二个孙悟空的索引值
list_ = ["唐僧", "孙悟空", "猪悟能", "沙悟净", "孙悟空", "白骨精"]
# 获取第一个孙悟空的位置
first_sun_index = list_.index("孙悟空")

# 从第一个孙悟空的位置开始切片取到最后,取第二个孙悟空的
sec_list = list_[first_sun_index+1:]

# 取小列表中红孙悟空的位置
second_sun_index = sec_list.index("孙悟空")

# 将大列表中第一个孙悟空的位置加上切片后小列表中孙悟空的位置相加,即得到大列表中第二个孙悟空的索引位置
sec_sun_index_in_list = first_sun_index + second_sun_index + 1
print("sec_sun_index_in_list", sec_sun_index_in_list,
      list_[sec_sun_index_in_list])
  1. 判断是否是个列表
list_ = []
type(list) is list # True

字典

​ 唯一的映射类型,是以键值对的方式存储数据的。python中的key会被以哈希的方式计算,并根据计算的结果决定key值的存储地址,因此,字典是无序的。

dict = {"name","孙悟空", "age":872}
# 增
# setdefault() 两个参数,第一个参数为新增的键,第二个参数为值
# 			 如果新增的内容在字典中已经存在,则会覆盖掉原来的内容,并返回修改后的值
# 			 如果新增的内容在字典中不存在,则将键值对添加到字典中,并返回新增的值
dict.setdefault("name", "唐三藏") # 唐三藏
dict.setdefault("hobby", "弄枪舞棍") # 弄枪舞棍

# 查
# 通过键名取查值
print(dict['name']) # 孙悟空
# 通过keys()方法获取到字典中所有的键名
print(list(dict.keys())) # ['name', 'age']
# 通过valus()方法获取到字典中所有值
print(list(dict.valus())) # ['孙悟空', 723]
# 通过items()获取到列表中的所有内容
print(list(dict.keys())) # [('name', '猪悟能'), ('age', 723)]

# 改
# 通过重新给键赋值来修改值
dict['name'] = "猪悟能"
print(dict) # dict = {"name","猪悟能", "age":872}

# 使用update()方法来修改
dict2 = {"a":"12", "b":"34"}
dict.update(dict2) # 将dict2中的内容更新到dict中,如果存在相同的key,则更新为dict2中的值
print(dict) # {'name': '孙悟空', 'age': 723, 'a': '11', 'b': '22'}

# 删
del dict['name'] # 删除指定的键值对,返回删除后的新字典
print(dict) # {'age': 723}

# pop()方法,删除指定的键值对,有一个参数,该参数为传入的要删除的键名
dict.pop("name") # 孙悟空(返回的是被删除的值)

# popitem() 随机删除某组键值对, 并以元组的形式返回被删除的键值对
dict.popitem()
print(dict) # {'name': '孙悟空'}

# clear() 清空字典, 返回一个空的字典
dict.clear() # {} 

del dict # 删除整个字典

# 其他操作
a = dict.fromkeys(['key1', 'key2', 'key3'], "test")
print(a) # {'key1': 'test', 'key2': 'test', 'key3': 'test'}

b = dict.fromkeys(['key1', 'key2', 'key3'], ["test", "test1"])
print(b) # {'key1': ['test', 'test1'], 'key2': ['test', 'test1'], 'key3': ['test', 'test1']}

b['key2'] = "abc"
print(b) # {'key1': ['test', 'test1'], 'key2': 'abc', 'key3': ['test', 'test1']}

b['key2'][1] = "1111"
print("b") # {'key1': ['test', '1111'], 'key2': ['test', '1111'], 'key3': ['test', '1111']}

排序

​ sorted()方法,根据键名在ASCII表中的位置进行排序的

dict_ = {"b":123, "c":456, "a":789}
print(sorted(dict_)) # ['a', 'b', 'c']
print(sorted(dict_.items())) # [('a', 789), ('b', 123), ('c', 456)]

遍历

# 使用for循环进行遍历
dict = {"b":123, "c":456, "a":789}
for i in dict:
	print(i) # b,c,a

for i in dict.items():
	print(i) # ('b', 123), ('c', 456), ('a', 789)

for i in dict.keys():
	print(i) # b,c,a

for i in dict.values():
	print(i) # 123, 456, 789

for i, v in dict.items():
	print(i) # b,c,a
	print(v) # 123, 456, 789

字符串

str = "hello"
str1 = “hello world"
# 字符串遍历
print(i for i in str) # h,e,l,l,o

# 格式化字符串
print("%s world!" % (str)) # hello world!
print(f"{str} world!") # hello world!

# 字符串拼接
str1 = "world"
print(str + str1) # helloworld

# join()方法
" ".join([str, "world"]) # hello world

# count()统计字符串中某个元素出现的次数
str.count("l") # 2

# capitalize() 首字母大写
str1.capitalize() # Hello world

# center() 居中
print(str3.center(50, "-")) # -------------------hello world--------------------

# encode() 编码 
print(str3.encode()) # b'hello world'

# find() 查找某个元素的,并返回查找到的第一个元素的索引位置
print(str3.find("w")) # 6
# rfind() # 从左往右找
# lfind() # 从右往左找

# format() 格式化输出
str4 = "hello {name}"
print(str4.format(name="小样")) # hello 小样

# format_map()
str4 = "hello {name} {age}"
print(str4.format_map({"name":"雄安养", "age":89})) # hello 雄安养 89

# index()存在返回索引值,不存在则会报错
print(str3.index("w")) # 6

# startswith() 以什么开头
print(str3.startswith("h")) # True

# endswith()以什么结尾
print(str3.endswith("l")) # False

# isdigit() 是否为整数,
# isnumeric() 是否为一个整数
# isidentifier() 是否为非法字符
# islower() 是否为全小写
# isupper() 是否为全大写
# isspace() 是否为一个空格
# istitle() 是否为标题,符合每个单词首字母大写的
# lower() 全部变小写
# upper() 全部变大写
# swapcase() 大小写反转(大写变小写,小写变大写)
# ljust() 在左边加东西 str3.ljust("*", 20) # 在左边加20个*
# rjust() 在右边加东西 str3.rjust("*", 20) # 在右边加20个*
# strip() 去掉两端的空格 print(str3.strip())
# rstrip() 去掉左边的空格
# lstrip() 去掉右边的空格
# replace() 
replace("被替换的内容", "待替换的内容")# 全部替换
replace("被替换的内容", "待替换的内容", 1) # 只替换的第一个
# split() 字符串分割,返回分割后的列表
str3.split(" ") # 以空格分隔,['hello', 'world']
# title() 首字母大写
posted on 2025-06-20 16:30  小小荞麦片  阅读(15)  评论(0)    收藏  举报