【Python】语法基础---1、基本数据

第一章 语法基础

软件的定义

是指一系列按照特定顺序组织的计算机数据与指令的集合。

数据:计算机所能够识别的一些数据。硬盘当中:avi,doc,txt,py,内存当中:常量、变量、函数、对象、类。

指令:操作这些数据进行先关计算的步骤。

软件的运行流程

    由Python写出的代码叫做源代码,源代码是否能够直接被计算机识别?将源代码编译成计算机所能够识别的机器码,然后计算机执行机器码即可。

软件的两种操作方式:

  • 图形化界面操作方式

  • 命令行操作方式

高级编程语言分为两类:

  • 静态编译型:C、C++、Java

    • 编译:必须将源代码完全编译成机器码文件,再去执行机器码文件,运行程序

    • 静态:变量必须有明确的数据类型定义

  • 动态解释型:Python、JavaScript、Mathlab、Ruby、Go

    • 解释:没有必要将代码完全必成机器码,读取一句源码-编译一句-运行一句

    • 动态:变量没有明确的数据类型定义,任何数据类型变量都可以存

1.1 基本数据

整数 int

通常被称为整型,是零、正数和负数,不带小数点。

表示数字的时候,我们也可以使用进制的形式 二 、八、 十 、十六进制

>>> print(10)
10
>>> print(1001)
1001
>>> print(0b1001)
9
>>> print(0o1234)
668
>>> print(0x9C1A)
39962
>>> print(0x9W2Y)
  File "<stdin>", line 1
    print(0x9W2Y)
             ^
SyntaxError: invalid syntax

注意:打印的结果一律为十进制

     Python的整数长度为32位-4字节,并且通常是连续分配内存空间 id()函数

>>> id(0)
2034812832
>>> id(1)
2034812848
>>> id(2)
2034812864

      Python在初始化环境的时候就在内存里划分出一块空间,专门用于整数对象的存取。当然,这块空间也不是无限大的,能保存的数据是有限的。

>>> id(251)
2034816848
>>> id(260)
13647712
>>> id(-10)
13647696

小整数对象池

    Python初始化的时候会自动创建一个小整数对象池,方便我们调用,避免后期重复生成,这里面只包含-5~256,这些数字是我们最常用的数字,所以就预先被Python加载进内存。对于整数的使用而言,不在-5~256之间,一律重新创建。

>>> id(-5)
2034812752
>>> id(-6)
13647728
>>> id(256)
2034816928
>>> id(257)
13647648
>>> id(300)
13647696
>>> id(300)
13647712
>>> id(300)
13647680

浮点型 float

浮点数也就是小数,如果小数过于长,也可以用科学计数法表示。

>>> print(3.14)
3.14
>>> print(1.298765e10)
12987650000.0
>>> print(0.89e-5)
8.9e-06
>>> print(1.23e-8)
1.23e-08

复数 complex

复数由实部和虚部组成,a+bj

>>> print(1+2)
3
>>> print(1+2j)
(1+2j)
>>> (1+2j)*(1-2j)
(5+0j)
>>> complex(1,2)*complex(1,-2)
(5+0j)

布尔型 bool

对与错、0和1,正与反,都是传统意义上的布尔类型

在Python里面,布尔类型只有两个 True,False

布尔类型只能在逻辑运算和比较运算中存在

>>> True + False
1
>>> True - False
1
>>> 3 > 2
True
>>> 2 < 1
False
>>> 3 > 2 and 2 < 1
False

None空值 NoneType

空值不能理解为数字0,是空集φ;我们主要用在创建序列,和面向对象编程中使用。

>>> None + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> [None] * 10  # 创建一个长度为10的列表 没有数据 但有空间
[None, None, None, None, None, None, None, None, None, None]

字符串 str

字符串有三种表现形式:单引号,双引号,三引号(一般用在注释)

>>> print("HelloWorld")
HelloWorld
>>> print('你好')
你好
>>> print(" '' ")
 ''
>>> print(' "" ')
 ""
>>> print(' ' ')
  File "<stdin>", line 1
    print(' ' ')
               ^
SyntaxError: EOL while scanning string literal
>>> print(' \' ')
 '

转义符

  • \\:反斜杠

  • \':单引号

  • \":双引号

  • \n:换行

  • \t:横向制表符

>>> print(' \' ')
 '
>>> print("\")
  File "<stdin>", line 1
    print("\")
             ^
SyntaxError: EOL while scanning string literal
>>> print("\\")
\

变量

变量:在程序运行过程中,值会发生改变的量。

常量:在程序运行过程中,值不会发生改变的量 。(字面量,直接在代码中出现的数据)

无论是变量还是常量,在创建时都会在内存中开辟一个空间,用于保存它们的值。

# Java中基本数据类型变量a,b 和 引用数据类型变量c d e
int a = 3;
int b = 8;
Object c = new Object();
Object d = new Object();
Object e = c;

在Python当中,一律皆对象!

>>> a = 1
>>> b = 1
>>> c = 1
>>> a == b
True
>>> id(1)
2034812848
>>> id(a)
2034812848
>>> id(b)
2034812848
>>> d = a
>>> d == b
True
>>> num1 = 300
>>> num2 = 300
>>> num3 = 300
>>> id(num1)
13647712
>>> id(num2)
13647696
>>> id(num3)
13647680
>>> num1 == num2
True

 不能一味的去比地址,还要比两个对象的内容是否相等。

变量这个空间中,只能存某个数据对象的地址,变量就是该对象的一个引用而已

变量必须在赋值后才能被调用。

>>> print(num4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'num4' is not defined

变量可以连续赋值:

>>> a=b=c=10
>>> a
10
>>> b
10
>>> c
10
>>> a,b,c =10,20,30
>>> a
10
>>> b
20
>>> c
30
>>> a=b=c=1000
>>> id(a)
13647776
>>> id(b)
13647776
>>> id(c)
13647776
>>> a=1000
>>> b=1000
>>> c=1000
>>> id(a)
13647792
>>> id(b)
13647648
>>> id(c)
13647824

 Python中变量本身是没有数据类型约束的,它只是一个对象的引用,存的是对象数据的内存地址

只有数据对象之间有数据类型的区分。

标识符

所谓的标识符就是我们对变量、常量、函数、类等起的名称。

如下规定:

  • 第一个字符必须是字母或者下划线_

    • 虽然Python支持中文,我们也可以使用中文来命名,但是我们不推荐

    • 以下划线开头的话,在面向对象编程当中,有特殊含义-私有

  • 标识符的其他的部分由字母、数字、下划线组成

  • 标识符对字母大小写敏感

  • 变量名全部小写,常量名全部大写(Python当中不存在常量PI = 3.14,本质还是一个变量)

  • 函数名用小写加下划线方式,等同于变量名

  • 类名用大驼峰式命名方法:如果名称由多个单词组成,则每个单词首字母大写

变量的命名不要使用关键字和内置函数的名称!

>>> True = 2
  File "<stdin>", line 1
SyntaxError: cannot assign to True
>>> if = 3
  File "<stdin>", line 1
    if = 3
       ^
SyntaxError: invalid syntax

关键字

指的是已经被高级编程语言赋予特殊含义的单词。

>>> import keyword
>>> keyword.kwlist
['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']

同样也不能使用内置函数(将内置函数的名称 改变为了别的用途)

>>> id(2)
2034812864
>>> id = 3
>>> id + 1
4
>>> id(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Python中,一切皆对象,函数本身也是对象!

>>> id(2)
2034812864
>>> id(id)
45545184
>>> abc = id
>>> abc(1)
2034812848
>>> id(1)
2034812848
>>> id = 10
>>> print(id)
10
>>> abc(id)
2034812992

一共有多少内置函数?

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

注释

注解说明程序使用的一段文本信息,不算是程序的一部分。

  • 单行注释:# 注释内容

  • 多行注释:多个单行注释

  • 文档注释:"""注释内容 可以说明类信息 函数信息"""

猜你喜欢

转载自blog.csdn.net/trichloromethane/article/details/107800214