python学习小记(python3)(一)

1.python解释器

#!/usr/bin/env python与#!/usr/bin/python的区别

分成两种情况:

(1)如果调用python脚本时,使用:

python script.py
#!/usr/bin/python 被忽略,等同于注释

(2)如果调用python脚本时,使用:

./script.py
#!/usr/bin/python 指定解释器的路径

脚本语言的第一行,只对Linux/Unix用户适用,用来指定本脚本使用什么interpreter来执行。

有这句的,加上执行权限后,可以直接用./执行,不然会出错,因为找不到python解释器。

#!/usr/bin/python 是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器;

#!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。

#!/usr/bin/python 相当于写死了python路径;

#!/usr/bin/env python会去环境设置寻找python目录,可以增强代码的可移植性,推荐这种写法

2.python保留字

保留字即关键字,我们不能把它们用作任何标识符名称。Python的标准库提供了一个keyword模块,可以输出当前版本的所有关键字:

import keyword
keywork.kwlist
['False',
 'None',
 'True',
 'and',
 'as',
 'assert',
 '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']

3.python多行语句

Python通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠(\)来实现多行语句,例如:

total = item_one + \
        item_two + \
        tiem_three

在[],{},()中的多行语句,不需要使用反斜杠(\),例如:

total = ['item_one','item_two','item_three',
        'item_four','item_five']

4.数字(Number)类型

python中数字有四种类型:整数、布尔型、浮点和复数。

  • int(整数),如1,只有一种整数类型int,表示为长整型,没有python2中的Long
  • bool(布尔),如True
  • float(浮点数),如1.23、3E-2
  • complex(复数),如1+2j、1.1+2.2j

5.字符串(String)

  • 使用三引号('''或""")可以指定一个多行字符串
  • 反斜杠 可以用来转义,使用r可以让反斜杠不发生转义
  • 按字面意义级联字符串,如“this”“is”“string”会被自动转换为this is string
  • 字符串可以用 + 运算符连接在一起,用*运算符重复
  • python中的字符串有两种索引方式,从左往右以0开始,从右往左从-1开始
  • python没有单独的字符类型,一个字符就是长度为1的字符串
  • 字符串的截取的语法格式如下:变量[头下标:尾下标:步长]
paragraph = """这是一个段落
可以由多行组成"""

r"this is a line with \n" 则\n会显示,并不是换行

str= 'Runoob'
print(str * 2) 输出字符串两次


RunoobRunoob

6.等待用户输入

执行下面的程序在按回车键后就会等待用户输入:

input("\n\n 按下 enter 键后退出。")

以上代码中,'\n\n'在结果输出前会输出两个新的空行。一旦用户按下enter键时,程序将退出。

7.同一行显示多条语句

python可以在同一行中使用多条语句,语句之间使用分号(;)分割,以下是一个简单的实例:

import sys; x = 'runoob'; sys.stdout.write(x + '\n')

ruboob

ps:当我们使用print(obj)在console上打印对象的时候,实质上调用的是sys.stdout.write(obj+'\n'),print在打印时会自动加个换行符,以下两行等价

sys.stdout.write('hello' + '\n')
print('hello')

8.Print输出

print默认输出是换行的,如果要实现不换行需要在变量末尾加上end="":

x = "a"
y = "b"
#换行输出
print(x)
print(y)

print('-------------')
#不换行输出
print(x, end = " ")
print(y, end = " ")
print()


a
b
-------------
a b 

9.命令行参数

很多程序可以执行一些操作来查看一些基本信息,python可以使用-h参数查看各参数帮助信息:

python -h

usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-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     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --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
-q     : don't print version and copyright messages on interactive startup
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-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
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:]

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ':'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>:<exec_prefix>).
               The default module search path uses <prefix>/lib/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
   to seed the hashes of str, bytes and datetime objects.  It can also be
   set to an integer in the range [0,4294967295] to get hash values with a
   predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
   on Python memory allocators. Use PYTHONMALLOC=debug to install debug
   hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
   coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
   locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
   debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.

10.Python3中为多个变量赋值

在python中,变量就是变量,它没有类型,我们所说的“类型”是变量所指的内存中对象的类型

python允许你同时为多个变量赋值。例如:

a = b = c = 1

以上实例,创建一个整型对象,值为1,从后向前赋值,三个变量被赋予相同的数值。

您也可以为多个对象指定多个变量。例如:

a, b, c = 1, 2, "runoob"

以上实例,两个整型对象1和2的分配给变量a和b,字符串对象"runoob"分配给变量c

11.标准数据类型

python3中有六个标准的数据类型:

  • Number(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Set(集合)
  • Dictionary(字典)

python3的六个标准数据类型中:

  • 不可变数据(3个):Number(数字)、String(字符串)、Tuple(元组)
  • 可变数据(3个):List(列表)、Set(集合)、Dictionary(字典)

python3中内置的type()函数可以用来查询变量所指的对象类型,此外,还可以用isinstance来判断:

a,b,c,d = 20,5.5,True,4+3j
print(type(a), type(b), type(c), type(d))


<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

a = 111
isinstance(a,int)

True

isinstance和type的区别在于:

  • type()不会认为子类是一种父类类型
  • isinstance()会认为子类是一种父类类型
class A:
    pass
class B(A):
    pass
isinstance(A(),A)
type(A())==A

True
True

isinstance(B(),A)
type(B())==A

True
False

python中的字符串不能改变,向一个索引位置赋值,比如word[0] = 'm'会导致错误

12. python中可以使用del语句删除一些对象引用

del语句的语法是:

del var1[,var2[var3[.....,varN]]]

也可以通过使用del语句删除单个或多个对象,例如:

del var
del var_a,var_b

13.数值运算

2/4    #除法,得到一个浮点数
2//4   #除法,得到一个整数
17%3   #取余
2**5   #乘方

0.5
0
2
32

14.List(列表)

List(列表)是Python中使用最频繁的数据类型

列表可以完成大多数集合类的数据结构实现。列表中元素的类型可以不相同,它支持数字、字符串甚至可以包含列表(所谓嵌套)。

列表是写在方括号[ ]之间,用逗号隔开的元素列表

和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表

list = ['abcd',786,2,23,'runoob',70.2]
tinylist = [123,'runoob']
print(tinylist * 2)     #输出两次列表
print(list + tinylist)  #连接链表


[123, 'runoob', 123, 'runoob']
['abcd', 786, 2, 23, 'runoob', 70.2, 123, 'runoob']

python列表截取可以接收第三个参数,参数作用是截取的步长,以下实例在索引1到索引4的位置并设置为步长2(间隔一个位置)来截取字符串:

                          

如果第三个参数为负数表示逆向读取,以下实例用于翻转字符串:

def reverseWords(input):
    
    #通过空格将字符串分割,把各个单词分隔为列表
    inputwords = input.split(" ")
    
    #翻转字符串
    #假设列表list = [1,2,3,4]
    #第一个参数-1表示最后一个参数
    #第二个参数为空,表示移动到列表末尾
    #第三个参数为步长,-1表示逆向
    inputwords = inputwords[-1::-1]
    
    #重新组合字符串
    output = ' '.join(inputwords)
    
    return output


if __name__ == '__main__':
    input = 'I like runoob'
    rw = reverseWords(input)
    print(rw)

runoob like I

15.元组

元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号()里,元素之间用逗号隔开。

元组中的元素类型也可以不相同:

tuple = ('runoob',786,2.23,'john',70.2)
tinytuple = (123,'john')
print(tinytuple*2)
print(tuple + tinytuple)

(123, 'john', 123, 'john')
('runoob', 786, 2.23, 'john', 70.2, 123, 'john')

16.字典

字典是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象集合,字典是无序的对象集合。

两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典用“{}”标识,字典由索引(key)和它对应的值value组成。

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name':'john','code':'6734','dept':'sales'}

print(dict['one'])
print(dict[2])
print(tinydict)
print(tinydict.keys())
print(tinydict.values())


This is one
This is two
{'name': 'john', 'code': '6734', 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', '6734', 'sales'])

17.Python数据类型转换

数据类型的转换,只需要将数据类型作为函数名即可,以下这些函数返回一个新的对象,表示转换的值。

int(x)         将x转换为一个整数
long(x)        将x转换为一个长整数
float(x)       将x转换到一个浮点数
complex(real)  创建一个复数
str(x)         将对象x转换为字符串
repr(x)        将对象转换为表达式字符串
eval(str)      用来计算在字符串中的有效python表达式,并返回一个对象
tuple(s)       将序列s转换为一个元组
list(s)        将序列s转换为一个列表
set(s)         转换为可变集合
dict(d)        创建一个字典,d必须是一个序列(key,value)元组
frozenset(s)   转换为不可变集合
chr(x)         将一个整数转换为一个字符
unichr(x)      将一个整数转换为unicode字符
ord(x)         将一个字符转换为它的整数值
hex(x)         将一个整数转换为一个十六进制字符串
oct(x)         将一个整数转换为一个八进制字符串

参考链接:https://blog.csdn.net/qq_34638161/article/details/80377730

                  https://www.runoob.com/python3/python3-tutorial.html

                  https://blog.csdn.net/u011244839/article/details/79932148

发布了38 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/u014090429/article/details/92984575
今日推荐