python认识和语法实践
【摘要】 python认识和基础语法学习实践
python认识和基础语法
接下来我们就进行一些简单的练习掌握一些Python必须的语法,这里我们的练习主要是以python3部分的新语法为主
这里我们主要就是参照菜鸟教程
(https://www.runoob.com/python3/python3-tutorial.html)
然后学习一些简单的入门语法,一些复杂的语法我们在之后的版本之中在不断进行完善补充
版本认识
Python 3.0 于 2008 年 12 月 3 日发布,此版不完全兼容之前的 Python 源代码,我们这里主要针对的就是3.0以后的版本
基础语法
标识符
标识符有点类似js中的标识符,
- 首字母必须是字母表中字母或下划线 _ 。
- 标识符的其他部分由字母、数字和下划线组成。(也就是可以多个数字呗)
- 大小写敏感。(区分大小写😀 )
保留字
在python代码之中我们可以直接查看他给我们留下的保留字
import keyword
print(keyword.kwlist)
// 运行输出以后可以查看到下面的代码 --haha 有点万物皆数组的既视感
['False', 'None', 'True', 'and', 'as', 'assert',
'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']
注释
python之中的单行注释以 # 开头
多行注释可以用多个 # 号,还有 ‘’’ 和 “”"
//单行注释
#print(keyword.kwlist)
// 多行注释1
# 第一个注释
# 第二个注释
// 多行注释2
'''
第三注释
第四注释
'''
"""
第五注释
第六注释
"""
注释还行但是有点不习惯 感觉怪怪的
行与缩进
在我们学习js或者java的时候可能觉得多个空格没啥,但是在Python里面,绝对不行,它就是靠这个来识别函数的
python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {}
同一个代码块的语句必须包含相同的缩进空格数,正常代码是下面这样子的
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
而这个下面的代码错误的时候会直接警告我们(我们可以看到只有print前面的空格是不一样的)
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
// 缩进不一致,会导致运行错误
多行语句
python编程里面通常只写一行代码(不禁好奇,真的是要一行代码就能实现?)
使用反斜杠 ** 来实现多行语句
print("item_one + \
item_two + \
item_three")
在 [], {}, 或 () 中的多行语句,不需要使用反斜杠 **
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
print(total[1])
数字(Number)类型
python中数字有四种类型:整数、布尔型、浮点数和复数(看起来像是阉割版本的js类型)
- int (整数), 如 1, 只有一种整数类型 int,表示为长整型
- bool (布尔), 如 True。
- float (浮点数), 如 1.23、3E-2
- complex (复数) - 复数由实部和虚部组成,形式为 a + bj,其中 a 是实部,b 是虚部,j 表示虚数单位。如 1 + 2j、 1.1 + 2.2j
上面这个格式可以猜测出(complex这种格式也许正是为了数学而准备的)
字符串(String)
python中字符串也是一些常见的字符串的格式
● Python 中单引号 ’ 和双引号 " 使用完全相同。
● 使用三引号(’’’ 或 “”")可以指定一个多行字符串。
● 转义符 \。
● 反斜杠可以用来转义,使用 r 可以让反斜杠不发生转义。 如 r"this is a line with \n"
则 \n 会显示,并不是换行。
● 按字面意义级联字符串,如 "this " "is " “string” 会被自动转换为 this is string。
● 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
● Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
● Python 中的字符串不能改变。
● Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
● 字符串切片 str[start:end],其中 start(包含)是切片开始的索引,end(不包含)是切片结束的索引。
● 字符串的切片可以加上步长参数 step,语法格式如下:str[start:end:step]
从这里我们也可以看出上面的切片的使用方法
// 比如我们上面输出的
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
print(total[1:-1])
//输出不包含最后一个
// 也就是输出 ['item_two', 'item_three', 'item_four']
total = 'ABCDE'
print(total[1:-1])
//输出不包含最后一个
//也就是输出 BCD
空行||等待用户输入||同一行显示多条语句
// 空行就直接输入即可
print("程序执行结束。")
print("程序执行结束。")
// 等待用户输入
input("\n\n按下 enter 键后退出。")
// 语句之间使用分号 ; 分割
import sys; x = 'runoob'; sys.stdout.write(x + '\n')
多个语句构成代码组
在python之中缩进相同的一组语句构成一个代码块,称之代码组,比如像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。
pyhton 将首行及后面的代码组称为一个子句(clause)。
类似这种
x = 10
if x > 5:
print("x is greater than 5")
print("This is still inside the if block")
输出
python默认输出换行,如果想要不换行就得在变量末尾加上 end=""
x="a"
y="b"
# 换行输出
print( x )
print( y )
print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()
// 最终输出的效果
a
b
---------
a b
导入
python里面的导入和导入特定一部分也非常简单
//导入整个模块
import math
# 使用 math 模块中的函数
print(math.sqrt(16)) # 输出:4.0
print(math.pi) # 输出:3.141592653589793
// 只导入 math 模块中的 sqrt 函数
from math import sqrt
# 直接使用 sqrt 函数
print(sqrt(16)) # 输出:4.0
// 导入模块中的多个特定部分
from math import sqrt, pi
# 使用导入的部分
print(sqrt(16)) # 输出:4.0
print(pi) # 输出:3.141592653589793
//导入模块中的所有内容
# 导入 math 模块中的所有内容
from math import *
# 使用模块中的函数和常量
print(sqrt(16)) # 输出:4.0
print(pi) # 输出:3.141592653589793
查看命令行参数信息
python -h
可以帮助我们查看一些常见的各参数帮助信息
👉3.0的python版本查看以后,会给我们提示以下的信息
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options (and corresponding environment variables):
-b : issue warnings about converting bytes/bytearray to str and comparing
bytes/bytearray with str or bytes with int. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : turn on parser debugging output (for experts only, only works on
debug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also -? or --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-P : don't prepend a potentially unsafe path to sys.path; also
PYTHONSAFEPATH
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
--check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
--help-env: print help about Python environment variables and exit
--help-xoptions: print help about implementation-specific -X options and exit
--help-all: print complete help information and exit
Arguments:
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
标准数据类型
Python3 中常见的数据类型有:
- Number(数字)(1)
- String(字符串)( ‘a’ 或者 “A” )
String(字符串)
Python中的字符串用单引号 ' 或双引号 " 括起来,同时使用反斜杠 \ 转义特殊字符。
字符串的截取的语法格式如下:
变量[头下标:尾下标]
索引值以 0 为开始值,-1 为从末尾的开始位置
这个格式其实跟我们看到的其他的格式是差不多的
- bool(布尔类型)(true || false)
- List(列表)([])
- Tuple(元组)
tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 )
tinytuple = (123, 'runoob')
- Set(集合)
// 创建集合
parame = {value01,value02,...}
或者
set(value)
# 输出集合,重复的元素被自动去掉
sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}
print(sites)
- Dictionary(字典)(🙂 字典看着就是我们js的对象)
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}
Python3 的六个标准数据类型中:
- **不可变数据(3 个):**Number(数字)、String(字符串)、Tuple(元组);
- **可变数据(3 个):**List(列表)、Dictionary(字典)、Set(集合)。
此外还有一些高级的数据类型,如: 字节数组类型(bytes)。
在 Python3 中,bytes 类型表示的是不可变的二进制序列(byte sequence)
bytes 类型通常用于处理二进制数据,比如图像文件、音频文件、视频文件等
//创建方式一
x = bytes("hello", encoding="utf-8")
//创建方式二
x = b"hello"
y = x[1:3] # 切片操作,得到 b"el"
z = x + b"world" # 拼接操作,得到 b"helloworld"
检测数据类型
检测数据类型可以使用isinstance
来进项检测
a = 111
print(isinstance(a, int))
// true
常见的运算
- 加法 (
**+**
):将两个数相加。 - 减法 (
**-**
):将两个数相减。 - 乘法 (
*****
):将两个数相乘。 - 除法 (
**/**
):将两个数相除,结果为浮点数。 - 整数除法 (
**//**
):将两个数相除,结果取整数部分,丢弃小数。 - 取余 (
**%**
):计算两个数相除后的余数。 - 乘方 (
******
):将第一个数作为底数,第二个数作为指数,进行乘方运算。
# 加法
result_add = 5 + 4 # 5 加 4
print(result_add) # 输出:9
# 减法
result_sub = 4.3 - 2 # 4.3 减 2
print(result_sub) # 输出:2.3
# 乘法
result_mul = 3 * 7 # 3 乘 7
print(result_mul) # 输出:21
# 除法(结果为浮点数)
result_div = 2 / 4 # 2 除以 4
print(result_div) # 输出:0.5
# 整数除法(只保留整数部分)
result_floor_div = 2 // 4 # 2 除以 4,取整数部分
print(result_floor_div) # 输出:0
# 取余(模运算)
result_mod = 17 % 3 # 17 除以 3 的余数
print(result_mod) # 输出:2
# 乘方
result_pow = 2 ** 5 # 2 的 5 次方
print(result_pow) # 输出:32
数据类型转换
也是分为隐式类型转换和显示数据类型转换
隐式类型转换
显示数据类型转换
数字类型转换
x = int(1) # x 输出结果为 1
y = int(2.8) # y 输出结果为 2
z = int("3") # z 输出结果为 3
x = float(1) # x 输出结果为 1.0
y = float(2.8) # y 输出结果为 2.8
z = float("3") # z 输出结果为 3.0
w = float("4.2") # w 输出结果为 4.2
对象 =>字符串
str(x)
x = str("s1") # x 输出结果为 's1'
y = str(2) # y 输出结果为 '2'
z = str(3.0) # z 输出结果为 '3.0'
条件控制
// 条件控制 if elif else
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
// python里面0 不执行 为false
var1 = 100
if var1:
print ("1 - if 表达式条件为 true")
print (var1)
var2 = 0
if var2:
print ("2 - if 表达式条件为 true")
print (var2)
print ("Good bye!")
//输出
1 - if 表达式条件为 true
100
Good bye!
match…case
Python 3.10 增加了** match…case** 的条件判断,不需要再使用一连串的 if-else 来判断了
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
mystatus=400
print(http_error(400))
// def 用于定义一个函数。后面跟着函数名 http_error
// 括号中的参数(status)。这表示该函数会接受一个输入参数 status。
一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如
case 401|403|404:
return "Not allowed"
循环语句
while 循环
while 判断条件(condition):
执行语句(statements)……
案例
计算0-100的累加
a=100
sum=0
count=1
while count<=a:
sum=sum + count
count+=1
print("1 到 %d 之和为: %d" % (a,sum))
// 5050
while搭配else使用
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
for 语句
Python for 循环可以遍历任何可迭代对象,如一个列表或者一个字符串
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
print(site)
// 最后输出结果
Baidu
Google
Runoob
Taobao
for…else 语句用于在循环结束后执行一段代码
for x in range(6):
print(x)
else:
print("Finally finished!")
for搭配break使用
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")
range() 函数
range() 函数可创建一个整数列表,一般用在 for 循环中
range(start, stop, step)
参数说明:
- start: 计数从 start 开始。默认是从 0 开始。例如 range(5)等价于 range(0, 5);
比如我们经常使用
for i in range(5,9) :
print(i)
// 输出
5
6
7
8
//这里3就是我们每次增加的步长
for i in range(0, 10, 3) :
print(i)
// 输出
0
3
6
9
结合 range() 和 len() 函数以遍历一个序列的索引
a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
for i in range(len(a)):
print(i, a[i])
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
len() 返回列表中的元素数量
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # 输出:5,因为列表中有 5 个元素
list() 可以将任何可迭代对象(如元组、集合、字符串等)转换为列表
使用 range() 函数来创建一个列表
print(list(range(5)))
// 输出
[0, 1, 2, 3, 4]
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)