python语法入门


title: python语法入门
author: Sun-Wind
date: August 25, 2021

python语法入门

博主最近参加一项比赛,因为需要用到python,所以在这里记录自己学习python的一些语法知识,希望能够帮助初学者
注意:该学习过程要求有c或者C++基础

python与C++的区别

  • python用新行来完成命令,而C++使用分号
  • python 用空格来定义范围而c++使用花括号
  • python是一种面向对象的解释性语言,C++是一种面向对象的编译性语言
  • python中的几乎所有东西都是对象,拥有属性和方法

输出和输入

#This is a comment
print("Hello, World!")
x = 10
y = "Bill"
print(x)
print(y)

可以看到其语法十分直观
​​print("Python is " + x)print语句可以和变量组合。(除字符串也是变量)
裁切语法:指定开始索引和结束索引,用冒号分隔,返回对应变量的一部分如print(b[2:5])
存在负的索引,可以用负索引从字符串末尾开始切片
利用input进行输入

print("Enter your name:")
x = input()
print("Hello ", x)

语句

与C++的语法十分类似,下面仅介绍不同点
elif 相当于else if

a = 66
b = 66
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

如果只有一条语句要执行,可以放到同一行,
如果ifelse都只有一个语句要执行可以放到同一行
if语句内容不能为空如果一定要为空,可以用pass代替

a = 66
b = 200

if b > a:
  pass

while 有break和continue,else可以和while语句配合

i = 1
while i < 7:
  print(i)
  if i == 3:
    break
  i += 1
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

for 循环和in关键字配合,相当于创建了一个迭代器对象,并且为每个循环执行next()方法

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

变量

python用类来定义数据类型​python不用申明变量,在首次赋值时,才会创建变量并且变量没有特定申明类型,随时可以发生变化并且python允许在一行中给多个变量赋值如:
<x, y, z = "Orange", "Banana",>'
“Cherry”·变量的数据类型可以type(x)获取

print(type(x))
print(type(y))
print(type(z))
  • 文本类型: str
  • 数值类型: int, float, complex
  • 序列类型: list, tuple, range映射类型: dict
  • 集合类型: set, frozenset
  • 布尔类型: bool
  • 二进制类型: bytes, bytearray, memoryviewcomplex是复数类型如x=1j,j作为虚部的书写字符串类型
    例如
x = 10    # int
y = 6.3  # float
z = 2j   # complex

可以用函数int(),float(),complex()。

x = int(1)   # x 将是 1
y = int(2.5) # y 将是 2
z = int("3") # z 将是 3

str()——从一种类型转换为其他类型,但是复数类型不能转换

x = str("S2") # x 将是 'S2'
y = str(3)    # y 将是 '3'
z = str(4.0)  # z 将是 '4.0'

int 类型长度不限
list是列表类型
print "list1[0]: ", list1[0]print "list2[1:5]: ", list2[1:5]t = (0,1,2,3,4,5,6,7,8,9)

thislist = ["apple", "banana", "cherry"]
print(thislist)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

tuple用小括号建立而且tuple中的元素不能修改列表(List)是一种有序和可更改的集合。允许重复的成员。
元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
集合(Set)是一个无序和无索引的集合。没有重复的成员。
词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。并且也有负索引等适用于字符串得操作
append()可以追加元素

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

insert()可以在指定得索引处增加项目

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

remove()可以删除指定得项目

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

pop()删除指定得索引,如果没有指定,就删除最后一项

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

del 关键字也可以删除指定的索引,并且可以删除列表

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

clear()方法可以清空列表

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

​​
注意:

内置的=只是对变量的引用,
列表的合并可以直接用+法
进行copy()和list()都可以复制列表,同时list()还可以构建列表
元组值是不可改变的,但是可以先将元组变成列表在变回去,元组构建函数是tuple()
元组不能删除元素,但是可以直接删除元组

字符串语法

可以用len()函数获取字符串的长度

a = "Hello, World!"
print(len(a))

strip()可以删除字符串开头和结尾的空白字符

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

lower()返回小写的字符串
upper()返回大写的字符串
replace()用另一段字符串来替换字符串

a = "Hello, World!"
print(a.replace("World", "Kitty"))

split()在找到分隔符时将字符串拆分为子字符串

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

可以用in not in 关键字查找文本中是否出现短语字符串

txt = "China is a great country"
x = "ina" in txt
print(x)

可以用+和” “ 拼接format()可以使得字符串和任意变量拼接,

a = "Hello"
b = "World"
c = a + b
print(c)

原字符串需要有大括号,format方法不限参数

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

集合和字典

​​set是无序的,构建set要用花括号

thisset = {"apple", "banana", "cherry"}
print(thisset)

add()方法添加一个项目,

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

update()可以添加多个项目

thisset = {"apple", "banana", "cherry"}

thisset.update(["orange", "mango", "grapes"])

print(thisset)

有remove,del,clear操作
union方法可以合并后两个集合

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

set也有自己的构造函数

thisset = set(("apple", "banana", "cherry")) # 请留意这个双括号
print(thisset)

字典是无序,可变和有索引的集合,用花括号编写,有键和值,且都是字符串可以对新的项目赋值,这样的话新的元素会被自动创建

thisdict =	{
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}
print(thisdict)

字典中字典可以嵌套

函数

利用def来定义函数,函数也有return 语句
可以传送任意个参数,只需要在参数名称前面加个*

def my_function():
  print("Hello from a function")
def myfunction:
  pass

模块

py中的模块相当于c++中头文件,用import引入datetime模块
可以用datetime类创建日期对象,年月日

import datetime

x = datetime.datetime.now()
print(x)

re模块专门用于匹配,
findall()返回包含所有匹配项的列表
split()返回一个列表,字符串在每次匹配时被拆分,还可以指定第三个参数判定时第几次出现进行拆分

import re

str = "China is a great country"
x = re.findall("a", str)
print(x)
import re

txt = "China is a great country"
x = re.search("^China.*country$", txt)
import re

str = "China is a great country"
x = re.split("\s", str)
print(x)
import re

str = "China is a great country"
x = re.sub("\s", "9", str)
print(x)

其中使用了正则表达式匹配

  • [] 一组字符 “[a-m]”
  • \ 示意特殊序列(也可用于转义特殊字符) “\d”
  • . 任何字符(换行符除外) “he…o”
  • ^ 起始于 “^hello”
  • {} 确切地指定的出现次数 “al{2}”
  • | 两者任一 “falls|stays”
  • () 捕获和分组
    sub()可以把匹配替换为所选择的文本,还可以指定第4个参数来控制替换的次数search()返回一个match对象,
import re

str = "China is a great country"
x = re.search("\s", str)

print("The first white-space character is located in position:", x.start())

span()返回的元组包含了匹配的开始和结束位置·
group()返回匹配的字符串部分如果没找到,则返回值
Nonebottle模块是一个快速小巧。轻量级的微型web框架,
@route()建立url映射,route是路由,括号里是url的路径,
def login() return 的内容将显示在页面上最后,
run() 函数启动服务器,并且我们设置它在 本机 的 8080 端口上运行


可以在命令行中运行python文件前提是已经安装了pythonpython
注释以#开头
多行注释可以采用“”“即未分配给变量的字符串文字


  • 就先写到这里吧,这一节没有写类和对象的语法
  • 以后想到什么再回来补充一下 阿巴阿巴o( ̄▽ ̄)ブ
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值