铁丝网

互相联通的梦境

0%

「python」基础 task1

写在开始

出于习惯原因,我决定使用python 3而不是python 2。

写英文的时候能不大写就不大写,因为觉得这样比较酷。

第一次参加学习群,不知道能不能坚持到最后呢?

环境搭建

anaconda环境配置

使用spyder 3.4。python语言的版本是3.6。

解释器

python是一种解释型语言,需要解释器来处理。而相对的C和C++则是编译型语言,需要编译器。(编译型语言需要编译器将目标文件转换为与机器CPU架构相匹配的目标代码、库文件要与操作系统匹配,所以不能跨平台运行。与之相对应的解释型语言只需要不同平台的不同解释器即可。也就是说开发者不需要考虑每个平台的不同编译方式。)

解释器对源代码逐句分析,而且会形成中间代码,所以效率略低。

改进的方式比如说保存已经编译为本地机器指令的代码,再次出现时可以直接使用解释的结果。(Just-In-Time compiler)

python代码编辑后得到以.py为扩展名的文本文件,而这时需要python解释器来执行.py文件。

使用最广的是官方版本的解释器CPython,在命令行下运行python就使用了这个解释器。

ipython则在CPython的基础上增强了交互(anaconda里面的spyder应该使用的是这个解释器)

python初体验

print函数


比较官方的语法表达:

1
print(*objects, sep=' ', end = '\n', file  = sys.stdout)

  • objects表示输出的对象。复数表示可以一次输出多个对象,这时需要用”,”分隔。
  • sep表示间隔多个对象的字符。
  • end表示结尾的设定。
  • file表示要写入的文件对象。
  • 无返回值

一些常用操作:

print("hello world") 这样的方式可以输出字符串。

不加引号可以输出数字、变量、列表等。

与C中的printf类似,也支持参数格式化

1
2
str = "the length of (%s) is %d" %('runoob', len('runoob'))
print(str)

输出结果:

the length of (runoob) is 6

更多细节可以参见文末引用的资料。

input函数

接受一个标准输入数据,返回值为string类型。

语法:

1
input([prompt])

promt代表提示用户输入时显示的信息

如果想要输入一个数字的话,可以n = int(input("请输入一个数字:"))

python基础

python的变量特性

变量赋值

变量赋值不需要类型声明,赋值语句是直接的 counter = 100 或者 name = "John"

变量名的注意事项

可以使用大写和小写的英文字母、数字以及下划线 “_” 。注意变量名不能以数字开头。

三种比较常见的命名方式

  • camel case: 从第二个单词开始,每个单词的首字母大写。

    numberOfCollegeGraduates

  • pascal case: 每个单词的首字母都大写(包括第一个单词)

    NumberOfCollegeGraduates

  • snake case:用下划线隔开每个单词

    number_of_college_Graduates

保留字

变量名称不可以和保留字冲突。一般来在写程序的时候看到某个单词忽然变成了粗体就应该是保留字了。也可以通过

help("keywords")

来查看。

python中’:’的作用

分割数组

可以用于截取字符串/列表。’:’前是开始位置,’:’后是结束位置,是左闭右开区间。如果没有写就默认为开头/结尾。注意下标从0开始,而负数代表倒着访问一个列表/字符串,下标从-1开始。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> str = "Learn Python"
>>> first_5_chars = str[0:5]
>>> print(first_5_chars)
Learn
>>> substr_from_2_to_5 = str[1:5]
>>> print(substr_from_2_to_5)
earn
>>> substr_from_6_to_end = str[6:]
>>> print(substr_from_6_to_end)
Python
>>> last_2_chars = str[-2:]
>>> print(last_2_chars)
on
>>> first_2_chars = str[:2]
>>> print(first_2_chars)
Le
>>> two_chars_before_last = str[-3:-1]
>>> print(two_chars_before_last)
ho

用于循环/分支结构后

比如这样:

1
2
3
4
if flag = True:
x = 1
while i <= n:
i += 1

使用dir()和help()

dir()函数

属于python的内置函数。不带参数时返回当前模块的属性。带参数时可以返回一个函数的属性。

用于查看任意对象的属性和方法。(?我也不明白qwq)查看一些不常用的对象的定义之类的。待补充

例子:

1
2
3
4
5
6
7
def testFunc():
print("I'm just a test function.")

testFunc.attr1 = "Hello"
testFunc.attr2 = 5
testFunc()
print(dir(testFunc))

输出:

I'm just a test function.
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'attr1', 'attr2']

help()函数

顾名思义就是你有啥不懂的可以写出来问。dir()出来的那些名字输到help()里面,就会返回一些解释。
比如这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> help(__spec__)
Help on NoneType object:

class NoneType(object)
| Methods defined here:
|
| __bool__(self, /)
| self != 0
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.

或者这样:

1
2
3
4
5
6
7
8
9
10
11
12
>>> help(print)
Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

啊help()真好用!

使用import

通过import来使用其他模块(module),类似于导入外部代码,可以调用一些写好的函数。

也可以改变模块的名字:

1
import mymodule as mx

只导入特定的函数:

1
from math import pi

很多具有专门功能的函数都在一些常常被import的模块里面,避免了重复造轮子(造不出轮子的人也十分快乐😂)

pep8介绍

是一种代码规范,有人认为不这么写代码就非常丑。

宗旨是提高代码可读性。因为读某个代码的次数会远远多于写它的次数。

  • 首先一定要前后统一。比如用单引号就一直用单引号。

  • 比较长的东西要换行并和上一行保持对齐。

  • 长的算式换行用运算符号开头。

  • 使用一些空行。

  • 一些空格的具体使用方式。

请参看文末的参考资料。

p.s. 可以使用pycodestyle这样的工具来检查自己的代码是否符合pep8.

python数据基本知识

python中的数据类型

布尔值 booleans

只有真或假两个值。使用if时可以把if condition == True:简写为if condition:。 True对应的数值是1,False对应的数值是0。

数字 numbers

python中数字变量有三种:整数、浮点数、复数。

可以用type()来判断数字的类型。

整数没有长度限制。浮点数最多可以到小数点后15位。

字符串 strings

可以用’’或者””来表示字符串。多行字符串则使用

1
2
3
"""多行

字符串"""

python3中的字符串全都由unicode表示。

字节 bytes

可以储存一系列字节。主要是写给计算机看的?以后有机会用到的时候再介绍吧。

列表 lists

一种可以同时存放不同类型的数据的数组。数据以有序的方式储存。
列表里面的元素用”[]”括起来。每个元素之间用”,”隔开。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> assorted_list = [True, False, 1, 1.1, 1+2j, 'Learn', b'Python']
>>> first_element = assorted_list[0]
>>> print(first_element)
True
>>> print(assorted_list)
[True, False, 1, 1.1, (1+2j), 'Learn', b'Python']
>>> for item in assorted_list:
print(type(item))

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

一个列表里面可以包含其他的列表。

1
2
3
4
5
6
>>> nested = [[1,1,1], [2,2,2], [3,3,3]]
>>> for items in nested:
for item in items:
print(item, end=' ')

1 1 1 2 2 2 3 3 3

元组 turples

和列表非常相似,但元素用”()”括起来。
和列表的不同之处在于元组中的元素一旦确定就无法改变。相当于只读列表。但对于元组中单独的元素来说,如果它们是可变量,那么他们自身可以改变。

元组比列表占用储存空间更小,一般被用于函数返回多个值或者是储存字典中的关键字。

集合 sets

储存无序、不重复的元素。支持判断某个元素在集合中是否存在,以及其他一些数学上的集合常见操作。定义时所有元素用”{}”括起来。

frozenset是不支持修改的集合。

字典 dicionaries

储存了一些从关键字(key)到值(value)的映射,是无序的。可以直接通过关键字访问值。
keys()输出所有关键字、values()输出所有值,items()则输出所有映射关系。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31}
>>> type(sample_dict)
<class 'dict'>
>>> sample_dict
{'mar': 31, 'key': 'value', 'jan': 31, 'feb': 28}>>> sample_dict['jan']
31
>>> sample_dict['feb']
28
>>> sample_dict.keys()
dict_keys(['mar', 'key', 'jan', 'feb'])
>>> sample_dict.values()
dict_values([31, 'value', 31, 28])
>>> sample_dict.items()
dict_items([('mar', 31), ('key', 'value'), ('jan', 31), ('feb', 28)])

修改字典中的元素:

1
2
3
4
5
6
7
8
9
>>> sample_dict['feb'] = 29
>>> sample_dict
{'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}
>>> sample_dict.update({'apr':30})
>>> sample_dict
{'apr': 30, 'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}
>>> del sample_dict['key']
>>> sample_dict
{'apr': 30, 'mar': 31, 'jan': 31, 'feb': 29}

基本运算符

算数运算符

包括

  • “+”
  • “-“
  • “*”
  • “/“
  • “%” 取模
  • “**” 乘方
  • “//“ 整除

    逻辑运算符

    包括
  • “==” 判断两个值是否相等
  • “!=””<>” 判断两个值是否不相等
  • “<”
  • “>”
  • “>=”
  • “<=”

    赋值运算符

    包括
  • “=”
  • “+=”
  • “-=”
  • “*=”
  • “/=”
  • “%=”
  • “**=”
  • “/=”

“=”是变量赋值。

a += ba = a + b,其他同理。

位运算符

一些基本的位运算操作。

  • “&” 与
  • “|” 或
  • “^” 异或
  • “~” 取反
  • “<<” 左移
  • “>>” 右移

了解基本逻辑运算的都不用解释。

逻辑运算符

包括

  • “and”
  • “or”
  • “not”

成员运算符

判断是否为成员。

  • “in”
  • “not in”

身份运算符

判断两个变量是否指向同一个对象。

  • “is”
  • “is not”

参考资料/链接

解释器:廖雪峰的教程解释器与编译器的异同

print函数:print函数print函数用法总结

input函数: input函数

变量名: python variables

dir()和help()函数 python functiondir()与help()

pep8: 官方文档如何用pep8写出好看的python程序

数据类型:data types

运算符: basic opeartors


task1 完成撒花🎉