注释在程序开发的过程起着非常重要的作用,往往在一个优秀的项目中,注释的行数不比代码少
方便自己一段时间后再回头看或修改代码
多人开发同一个项目的时候,使别人能读懂你的代码
# 这是一个注释
""" 这里面可以注释 多行代码 """
ctrl + /
什么是变量,变量名,变量值
变量:容器 变量名:名字 变量值:内容
变量定义格式
a=1 #变量名=变量值
不能以数字开头 区分大小写 不能使用内置关键字 尽量和用途相匹配
#python查看内置关键字 import keyword print(keyword.kwlist)
a = a + 5 #将右边的值赋值给左边
Number #数字 String #字符串 List #列表 Tuple #元组 Set #集合 Dictionary #字典
a = 1 print(type(a)) #查看a的数据类型
python 3 支持 int 、float、 bool、complex(复数)
a = 1 b = -1
pi=3.14
t =Ture f =False
内置函数:python内置的写好了的代码,可以直接调用
a = 3 b = 3.14 print(float(a)) print(int(b))
程序运行的过程中,有时需要和用户交互,要求用户来输入信息,有时也需要打印一些信息给用户看,或者方便用户调试,这就要用到输入和输出函数
num =input("请输入内容:")
print()
print("" end="")
python 提供了非常丰富的运算符,包括算数运算符、逻辑运算符、比较运算符等各种运算符、帮助我们进行各种计算和比较
字符串或串(String)是由数字、字母、下划线组成的一串字符
# -*- coding: utf-8 -*-
#字符串类型的变量使用双引号或单引号括起来 new_str ="welcome to xf1433.com" #拼接 name = input("please enter you username:") new_str1 ="hello" +name
占位符 | 替换内容 |
---|---|
%d | 整数 |
%f | 浮点数 |
%s | 字符串 |
%x | 十六进制整数 |
#试例 name ="abc" age =8 height = 180.5 print("姓名:{},年龄:{},身高:{}" .format(name,age,height))
# new_str.find(str[,start,end]) # 查找字符串坐在位置,str:字符串,start:起始位置,end:结束位置 new_str = "hello,Welcome to the programming world" print(new_str.find("o", 5, 11)) # new_str.count(str) # 计数,查询当前字符串中出现 str字符串的次数 print(new_str.count("o")) # new_str.replace(old,new[,count]) # 替换,将old值替换为new值,count:替换次数,不写就是全部替换 print(new_str.replace("o","哦", 2)) # new_str.split(sep[,maxsplit]) # 切割,将sep字符串前后进行切割,maxsplit:切割次数 print(new_str.split(",",2)) # new_str.startswith(prefix[,start,end]) # new_str.endswith(suffix[,start,end]) # 判断,判断起始字符或结束字符是否为prefix或suffix print(new_str.startswith("hello")) print(new_str.endswith("aaa")) # new_str.upper() # 将内容同一转化为大写 print(new_str.upper()) # 将内容同一转化为小写 # new_str.lower() print(new_str.lower()) # new_str.strip() # 将文本内容前后空格取消 new_str = " hello,Welcome to the programming world " print(new_str) print(new_str.strip())
if条件判断语句在平常项目开发中经常被用到,理解掌握,灵活运用
if 表达式1: 执行语句 elif 表达式2: 执行语句 elif 表达式3: 执行语句 elif 表达式4: 执行语句 …… else: 执行语句
num = input("请输入您的预约号:") if int(num) == 7: print("验证成功") sex = input("请输入您的性别,f代表女性(female),m代表男性(male):") if sex == "f": print("请在女生队伍等待!") elif sex == "m": print("请在男生队伍等待!") else: print("输入错误!") else: print("验证失败")
while 表达式: 循环内代码块
i = 1 n = 4 while i<=n: #打印空格 print(" "*(n-i),end="") #打印*号 j=1 while j<=2*i-1: print("*",end="") j+=1 print("") i += 1
i = 1 while i <= 20: i += i if i % 2 == 0: if i % 10 == 0: break print(i,end=" ")
i = 1 while i <= 20: i += i if i % 2 == 0: if i % 10 == 0: continue print(i,end=" ")
python 为我们提供了便利序列时更简单的语句,即for循环。for循环使用非常广泛,通常用于便利各种类型的序列,例如列表,元组,字符串等
for 变量 in 序列: 代码块
for i in range(0,10,2): print(i)
for i in range(1, 21): if i % 2 == 0: if i % 10 == 0: break print(i, end=" ")
for i in range(1, 21): if i % 2 == 0: if i % 10 == 0: continue print(i, end=" ")
列表是用来顺序存储相同或不同数据类型的集合,需要注意的是,列表内存的元素是有序的
new_list = ["first","second",thrid] new_list = [1,"second","thrid"] new_list = [["first","second"],"second","third"]
new_list = ["first", "second", "third"] print(new_list[0]) for i in range(0, len(new_list)): print(new_list[i]) ################################ for item in new_list: print(item)
old_list = ["first", "second", "third"] new_list = [1, 2, 3] # append()方法 # 向末尾添加元素 # old_list = old_list.append(new_list) old_list.append(new_list) print(old_list) # insert()方法 # 向列表任意位置添加元素 old_list.insert(1, new_list) # 1:元素位置 print(old_list) # "+" 拼接组成新的列表,注:拼接的事列表,列表不能与元素拼接 add_list = old_list + new_list print(add_list) # extend()方法 # 用于在列表末尾一次性追加另一个序列中的多个值 old_list.extend(new_list) print(old_list)
# 将元素位置重新赋值到达效果 old_list = ["first", "second", "third"] old_list[0] = 1 print(old_list)
old_list = ["first", "second", "third","fourth", "fifth"] # del 删除 del old_list[1] print(old_list) # remove()方法 old_list.remove("first") print(old_list) # pop()方法 # 默认从末尾删除一个元素,也可以传入一个索引 old_list.pop() print(old_list) old_list.pop(1) print(old_list)
old_list = ["first", "second", "third", "fourth", "fifth"] # list[start:end:step] # start:开始位置,end:结束位置,step:步长 # 切片的截取方位是左闭右开(右边不包含) print(old_list[:2]) # 取0位到2位,即"first", "second" print(old_list[1:]) # 从1位开始取,即"second", "third","fourth", "fifth" print(old_list[0::2]) # 从0开始,步长为2,即['first', 'third', 'fifth']
num_list = [3,8,1,4,9,2] #升序 num_list.sort() num_list.sort() print(num_list) # 降序 num_list.sort(reverse=True) reverse:颠倒,反转 num_list.sort(reverse=True) print(num_list)
可以理解为一个 一旦被定义只会,其中的元素不可再修改的列表
new_tuple = (1,2,"3")
info = ("192.168.1.1", 3066, "root", "root") ip = info[0] port = info[1] print("ip:{},port:{}" .format(ip,port))
info = ("192.168.1.1", 3066, "root", "root") for item in info: print(item)
字典主要用于存储key-value形式的数据
#定义字典 new_dict = {键名(key):键值(value)} new_dict = {"name":"zsc","age": 21}
new_dict = {"name":"zsc","age": 21} print(new_dict["name"]) #通过键名(key)取出,key不存在,会报错 print(new_dict.get("name")) #通过key取出,如果key不存在,则返回None
new_dict = {"name": "zsc", "age": 21} print(new_dict) # 向字典中添加 key,value(简称 键值对) new_dict["hobby"] = "reading" print(new_dict) # 向字典中修改key,并设置value new_dict["name"] = "joker" print(new_dict) # 向字典中删除键值对 del new_dict["age"] print(new_dict)
new_dict = {"name": "zsc", "age": 21} # 通过key值遍历字典 for key in new_dict.keys(): print(key) print("{}: {}".format(key, new_dict[key])) # 格式化打印输出 print(new_dict[key]) # 打印value值 ### for value in new_dict.values(): print(value) # 打印value值 for item in new_dict.items(): print(item) # 元组形式取出 for key, value in new_dict.items(): print("key:{},value:{}".format(key, value)) # 格式化打印
集合也是使用{}定义,但集合内存储的不是键值对,而是独立的数值
new_set1 = {"123", "345", "456", "789"} print(new_set1) new_list = ["a", "a", "a", "b", "c", "d"] #列表 print(new_list) # set()方法,去除重复部分 new_set2 = set(new_list) # 集合是无序的,即每次输出结果不一样 print(new_set2) #空集合 变量名=set() a=set()
new_set = {"123", "345", "456", "789"} # 实现单个元素的添加 new_set.add("111") print(new_set) # 实现多个元素的添加 new_set.update({"222", "333"}) print(new_set) new_set.update(["444", "555"]) print(new_set)
new_set = {"123", "345", "456", "789"} new_set.remove("123") # 若值不存在,会报错 print(new_set) new_set.discard("345") # 值不存在,不会报错,也不会执行任何操作 print(new_set) new_set.pop() #删除随机元素 print(new_set)
new_set1 = {1, 2, 3, 4} new_set2 ={3,4,5,6} # 交集 & result = new_set1 & new_set2 print(result) # 并集 | result = new_set1 | new_set2 print(result) # 差集 - result = new_set1 - new_set2 print(result)