Python语法篇

文章目录

Python中非常重视缩进,这点与Java很不一样,需要注意

冒号在python里很重要

数据类型

字符串

单引号,双引号,三引号都可以,这种设计可以直接打印带单引号或者双引号的字符串

python 复制代码
message='first string'
message="second string"
message="""third string"""

//字符串常用函数
    name.title() //首字母大写
    name.upper() //全部大写
    name.lower() //全部小写
     
    name.strip() //字符串左右空白删除
    name.lstrip() //字符串左边空白删除
    name.rstrip() //字符串右边空白删除
    
//字符串格式化输出
f-string方式(3.6版本开始支持)
name="123"
message1=f"this is {name}"

format格式
message="this is {}".formate(name)

整数

python 复制代码
a=1234124
a=1_32432  高版本支持

浮点数

python 复制代码
a=1.32
b=234.52

列表

可以装任意类型的元素

python 复制代码
list=[1,1.24,'py']
print(list)

//对list  ,索引从0开始,倒数索引-1,-2
list.append()  //添加元素
del list[1] //删除元素
list[1] //查询元素
list.insert //指定索引处插入元素
list.remove(1)  //根据值删除元素
list.pop()  //删除并且弹出最后一个元素 ,指定索引时就是删除并且弹出最后一个元素
//排序
list.sort()  
sorted(list) //临时排序不改变原表

//反转
list.reverse() 

//list的长度
len(list)


//for循环遍历list
for num in list:
    print(num)
    
对于数值列表
num=range(1,5)   # 左闭右开,步长默认1,可指定步长

列表解析
num=[value for value in range(0,10)]
ps:python中次方  a**3  //表示a的3次方

//切片(相当于new一个对象)
print(num[1:5]) #左闭右开区间
print(num[1:]) #第二个元素到结尾区间
print(num[:]) #复制列表

元组

不可变的列表叫元组

python 复制代码
num=(1,2,3)
# 不可修改元组里的元素
其他语法跟列表一模一样

字典

key value

python 复制代码
num={"name":"job"}
num["name"]="123"  //修改值
num["name2"]="124124124"  //添加键值对
del num["name"]  //删除键值对

遍历字典中键值对
  	for k,v in dict.items():
        print(k)
        print(v)
遍历字典中键
    for k in dict.keys():
        print(k)
遍历字典中值
	for v in dict.values():
        print(v)
        
 //指定顺序遍历用之前的sorted()
	for v in sorted(dict.values()):
//去重遍历  (用set集合)
	for v in set(dict.values())

条件语句

if语句

python 复制代码
if a==b:
	print(1)
else:
	print(2)
    
ps:python中字符串==区分大小写

  age = 12

❶ if age <4:
      print("Your admission cost is $0.")
❷ elif age <18:
      print("Your admission cost is $25.")
❸ else:
      print("Your admission cost is $40.")
        
//判断列表是否包含某个元素
if 'a' in list:
    print("yes")

//判断列表是否不包含某个元素
if 'a' not in list:
    print("no")

//列表判空
❶ requested_toppings = []

❷ if requested_toppings:
      for requested_topping in requested_toppings:
          print(f"Adding {requested_topping}.")
      print("\nFinished making your pizza!")
❸ else:
      print("Are you sure you want a plain pizza?")
    
 

while语句

python 复制代码
while语句和break,continue  和Java类似,只是:

输入input和int()
input读取的用户输入全是字符串
int(input())包裹则转成数值

直接判空列表还是比较好用的
  # 首先,创建一个待验证用户列表
  # 和一个用于存储已验证用户的空列表。
❶ unconfirmed_users = ['alice','brian','candace']
  confirmed_users = []

  # 验证每个用户,直到没有未验证用户为止。
  # 将每个经过验证的用户都移到已验证用户列表中。
❷ while unconfirmed_users:
❸     current_user = unconfirmed_users.pop()

      print(f"Verifying user:{current_user.title()}")
❹     confirmed_users.append(current_user)

  # 显示所有已验证的用户。
  print("\nThe following users have been confirmed:")
  for confirmed_user in confirmed_users:
      print(confirmed_user.title())

函数

python 复制代码
function_name(value_0,parameter_1='value')
#Python中函数里形参可以指定默认值
from module import function

def关键字来声明函数
def the_button_cliked():
    print("clicked!")

python 复制代码
class Dog:
	def __init__(self,name):
		self.name=name

        
//继承
❶ class Car:
      """一次模拟汽车的简单尝试。"""

      def __init__(self,make,model,year):
          self.make = make
          self.model = model
          self.year = year
          self.odometer_reading = 0

      def get_descriptive_name(self):
          long_name = f"{self.year} {self.make} {self.model}"
          return long_name.title()

      def read_odometer(self):
          print(f"This car has {self.odometer_reading} miles on it.")

      def update_odometer(self,mileage):
          if mileage >= self.odometer_reading:
              self.odometer_reading = mileage
          else:
              print("You can't roll back an odometer!")

      def increment_odometer(self,miles):
          self.odometer_reading += miles

❷ class ElectricCar(Car):
      """电动汽车的独特之处。"""

❸     def __init__(self,make,model,year):
          """初始化父类的属性。"""
❹         super().__init__(make,model,year)

❺ my_tesla = ElectricCar('tesla','model s',2019)
  print(my_tesla.get_descriptive_name())

文件

读取文件

python 复制代码
with open("a.txt") as file_object:
	content=file_object.read()    #读取整个文件
	file_object.close()
with open("a.txt") as file_object:
	for line in file_object:
		print(line)      #逐行读取文件
with open("a.txt") as file_object:
    lines=file_object.readlines()  #读取文件各行到列表中

写入文件

python 复制代码
    with open(filename,'w') as file_object:
        file_object.write("hello")			#全量写
        
    with open(filename,'a') as file_object:
        file_object.write("hello")         #覆盖写
        
python只能写入字符串到文件中,数字需要转成字符串str()才能写入。

异常

python 复制代码
try-except-else 和pass关键字
	try:
        print(1/0)
	except	Exception:
        print("Error")
    else:
        print("yes")
        
	try:
        print(1/0)
	except	Exception:
        pass   				#代码块什么都不做
    else:
        print("yes")        

JSON库

JSON 格式 dump 输出json格式到文件中

load读取json格式文件

python 复制代码
    file2="aaa.json"
    with open(file2,'w') as file2_object:
        json.dump([14124,2424],file2_object)


    with open(file2) as file_object:
        list=json.load(file_object)
        print(list)

unittest

python 复制代码
写单元测试
库 import unittest
unittest.TestCase
class TestOne(unittest.TestCase):
	def __init__(self):
		self.assert
        
继承TestCase类 里面提供了单元测试要用的assert断言        
相关推荐
夜泉_ly7 分钟前
C++ -引用-详解
c语言·开发语言·c++
程序和我有一个能跑就行。12 分钟前
【Python】递归
数据结构·python·算法·递归
秦淮渔火20 分钟前
Java_集合_单列集合Collection
java·开发语言
橘子海全栈攻城狮28 分钟前
【源码+文档+调试讲解】学生选课系统Python
java·开发语言·数据库·python·小程序·sqlite
乐思智能科技有限公司30 分钟前
C语言编写一个五子棋游戏-代码实例讲解与分析
c语言·开发语言·嵌入式硬件·算法·游戏
测试老哥31 分钟前
自动化测试实例:Web登录功能性测试(无验证码)
自动化测试·软件测试·python·selenium·测试工具·职场和发展·单元测试
葡萄城技术团队40 分钟前
如何借助Java批量操作Excel文件?
java·python·excel
木鬼与槐42 分钟前
Python(六)-拆包,交换变量名,lambda
开发语言·python
咖啡里的茶i1 小时前
C++之Swap类
开发语言·c++·算法
Neituijunsir1 小时前
2024.09.18 校招 实习 内推 面经
人工智能·python·算法·面试·自动驾驶·汽车·求职招聘