您的位置:首页 > 财经 > 金融 > Python语法篇

Python语法篇

2024/10/5 13:54:44 来源:https://blog.csdn.net/qq_42936379/article/details/139249546  浏览:    关键词:Python语法篇

文章目录

  • 数据类型
    • 字符串
    • 整数
    • 浮点数
    • 列表
    • 元组
    • 字典
  • 条件语句
    • if语句
    • while语句
  • 函数
  • 文件
  • 异常
  • JSON库
  • unittest

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

冒号在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)

整数

a=1234124
a=1_32432  高版本支持

浮点数

a=1.32
b=234.52

列表

可以装任意类型的元素

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[:]) #复制列表

元组

不可变的列表叫元组

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

字典

key value

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语句

if a==b:print(1)
else:print(2)ps:python中字符串==区分大小写age = 12if 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语句

while语句和break,continue  和Java类似,只是:输入inputint()
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())

函数

function_name(value_0,parameter_1='value')
#Python中函数里形参可以指定默认值
from module import functiondef关键字来声明函数
def the_button_cliked():print("clicked!")

class Dog:def __init__(self,name):self.name=name//继承
❶ class Car:"""一次模拟汽车的简单尝试。"""def __init__(self,make,model,year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def 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 = mileageelse: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())

文件

读取文件

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()  #读取文件各行到列表中

写入文件

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

异常

try-except-elsepass关键字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格式文件

    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

写单元测试
库 import unittest
unittest.TestCase
class TestOne(unittest.TestCase):def __init__(self):self.assert继承TestCase类 里面提供了单元测试要用的assert断言        

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com