Python笔记(1)

本文详细介绍了Python的基本语法,包括变量的定义、类型转换、获取变量类型等。并深入探讨了字符串的操作,如访问、循环、查找及格式化。此外,还介绍了Python中不同类型的集合,例如列表、元组、集合和字典的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来源:W3school在线教程

第一节 基本语法

  1. 变量直接赋值不用定义
x = 5
y = "John"
print(x)
print(y)
  1. 强制类型转换
x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0
  1. 获取变量类型
x = 5
y = "John"
print(type(x))
print(type(y))
  1. 单双引号相同
x = "John"
x = 'John'
  1. 多变量命名
x, y, z = "Orange", "Banana", "Cherry"
x = y = z = "Orange"

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
  1. 输出
x = "awesome"
print("Python is " + x)

x = "Python is "
y = "awesome"
z =  x + y
print(z)
  1. 全局变量与局部变量
x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)
  1. 在函数中声明全局变量
def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

第二节 变量类型

x = "Hello World"	                            #str	
x = 20	                                        #int	
x = 20.5	                                    #float	
x = 1j	                                        #complex	
x = ["apple", "banana", "cherry"]	            #list	
x = ("apple", "banana", "cherry")	            #tuple	
x = range(6)	                                #range	
x = {"name" : "John", "age" : 36}	            #dict	
x = {"apple", "banana", "cherry"}	            #set	
x = frozenset({"apple", "banana", "cherry"})	#frozenset	
x = True	                                    #bool	
x = b"Hello"	                                #bytes	
x = bytearray(5)	                            #bytearray	
x = memoryview(bytes(5))	                    #memoryview
#Python没有random()函数,但可以用内置模块random生成随机数
import random
print(random.randrange(1,10)

2.1 字符串

  1. 访问
a = "Hello, World!"
print(a[1])
print(len(a))
print(a[2:5])#不包含下标5
print(a[:5])
print(a[2:])
print(a[-5:-2])#从倒数第五个到倒数第2个(不包括倒2)
  1. 循环
for x in "banana":
    print(x)
  1. 查找
txt = "The best things in life are free!"

print("free" in txt)
print("expensive" not in txt)

if "free" in txt:
  print("Yes, 'free' is present.")
  
if "expensive" not in txt:
  print("Yes, 'expensive' is NOT present.")
  1. 内置函数
a = "Hello, World!"
print(a.upper())#大写字母
print(a.lower())
print(a.strip()) #去掉空格
print(a.replace("H", "J"))#替换
print(a.split(",")) # returns ['Hello', ' World!']用固定的分割幅把字符串分开,写入列表


  1. 格式
    format()方法接受传递的参数,格式化它们,并将它们放在占位符{}所在的字符串中
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
  1. 转义字符
txt = "We are the so-called \"Vikings\" from the north."

2.2 布尔变量

print(8 > 7)
print(8 == 7)
print(8 > 7)

2.3 运算符

  1. 算数运算符
    在这里插入图片描述
  2. 赋值
    在这里插入图片描述
  3. 比较
    在这里插入图片描述
  4. 逻辑
    在这里插入图片描述
  5. 身份
    在这里插入图片描述
  6. 成员
    在这里插入图片描述
  7. 位运算
    在这里插入图片描述

2.4 集合

共有四种集合:

  • 列表(List)是一种有序和可更改的集合。允许重复的成员。
  • 元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
  • 集合(Set)是一个无序和无索引的集合。没有重复的成员。
  • 词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。
  1. 列表
#索引
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
print(thislist[-1])#-1代表倒数最后一项
print(thislist[2:5])
thislist[1] = "mango"
#循环判断
for x in thislist:
  print(x)

if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")
thislist = ["apple", "banana", "cherry"]
thislist = list(("apple", "banana", "cherry"))#用list构造函数构造列表
print(len(thislist))

#增加
thislist.append("orange")#在末尾添加
thislist.insert(1, "orange")#中间插入

#减少
thislist.remove("banana")
thislist.pop()#删除最后一项
del thislist[0]
thislist.clear()
#复制
list=thislist#浅拷贝
mylist = thislist.copy()#深拷贝
mylist=list(thislist)#制作副本

#合并
list3 = list1 + list2
list1.extend(list2)
  1. 元组
thistuple = ("apple", "banana", "cherry")
thistuple = ("apple", )#只包含一个项目时,需要括号
print(thistuple[1])
print(thistuple[-1])
print(thistuple[2:5])#搜索将从索引 2(包括)开始,到索引 5(不包括)结束
print(thistuple[-4:-1])
#转换为列表来更改
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
thistuple = ("apple", "banana", "cherry")

for x in thistuple:
  print(x)
  
if "apple" in thistuple:
  print("Yes, 'apple' is in the fruits tuple")
del thistuple
tuple3 = tuple1 + tuple2
  1. 集合
#要将一个项添加到集合,请使用 add() 方法。
#要向集合中添加多个项目,请使用 update() 方法。
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
thisset.update(["orange", "mango", "grapes"])
#删除
thisset.remove("banana")
thisset.discard("banana")
x = thisset.pop()#无法确定删哪一个,返回被删的值
thisset.clear()
del thisset
#合并
set3 = set1.union(set2)
set1.update(set2)
  1. 字典
thisdict =	{
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}

x = thisdict["model"]#获取键值
x = thisdict.get("model")#获取键值

thisdict["year"] = 2019#更改

for x in thisdict:
  print(x)#打印键名

for x in thisdict:
  print(thisdict[x])#打印值

for x in thisdict.values():
  print(x)#返回值

for x, y in thisdict.items():
  print(x, y)#返回键和值
thisdict["color"] = "red"#添加项目
thisdict.pop("model")#删除指定键名的项目
thisdict.popitem()#删除最后一个
del thisdict["model"]
#嵌套字典
myfamily = {
  "child1" : {
    "name" : "Phoebe Adele",
    "year" : 2002
  },
  "child2" : {
    "name" : "Jennifer Katharine",
    "year" : 1996
  },
  "child3" : {
    "name" : "Rory John",
    "year" : 1999
  }
}
#先创建,后嵌套
child1 = {
  "name" : "Phoebe Adele",
  "year" : 2002
}
child2 = {
  "name" : "Jennifer Katharine",
  "year" : 1996
}
child3 = {
  "name" : "Rory John",
  "year" : 1999
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值