python 基础 补充(1)

print 字符串叠加

可以使用 + 将两个字符串链接起来, 如以下代码.

>>> print('Hello world'+' Hello Hong Kong')
"""
Hello world Hello Hong Kong
"""

int() 和 float();当int()一个浮点型数时,int会保留整数部分,比如 int(1.9),会输出1,而不是四舍五入。

>>> print(int('2')+3) #int为定义整数型
"""
5
"""
>>> print(int(1.9))  #当int一个浮点型数时,int会保留整数部分
"""
1
"""
>>> print(float('1.2')+3) #float()是浮点型,可以把字符串转换成小数
""""
4.2
""""

python当中符号,区别于Matlab,在python中,用两个表示,如3的平方为32 , **3表示立方,**4表示4次方,依次类推

>>> 3**2   # **2 表示2次方
""""
9
""""
>>> 3**3   #  **3 表示3次方
""""
27
""""
>>> 3**4
""""
81
""""

取余数 %

余数符号为“%”,见代码.

>>> 8%3
"""
2
"""

实例

example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
    print(i)

输出的结果为 1,2,3,4,5,6,7,12,543,876,12,3,2,5, 内容依次为 example_list 中的每一个元素 注意 Python 是使用缩进表示程序的结构,如果程序这样编写,

example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
    print(i)
    print('inner of for')
print('outer of for')

那么每次循环都会输出 inner of for,在循环结束后,输出 outer of for 一次。

range使用

在 Python 内置了工厂函数,range 函数将会返回一个序列,总共有三种使用方法

1 range(start, stop)

其中 start 将会是序列的起始值,stop为结束值,但是不包括该值,类似 数学中的表达 [start, stop),左边为闭区间,右边为开区间。

for i in range(1, 10):
    print(i)

上述表达将会返回 1-9 所有整数,但不包含 10

2 range(stop)

如果省略了 start 那么将从 0 开始,相当于 range(0, stop)

3 range(start, stop, step)

step 代表的为步长,即相隔的两个值得差值。从 start 开始,依次增加 step 的值,直至等于或者大于 stop

for i in range(0,13, 5):
    print(i)

将会输出 0, 5, 10。

4.1 内置集合

Python 共内置了 list、 tuple 、dict 和 set 四种基本集合,每个 集合对象都能够迭代。

tuple 类型

tup = ('python', 2.7, 64)
for i in tup:
    print(i)

程序将以此按行输出 ‘python’, 2.7 和 64。

dictionary 类型

dic = {}
dic['lan'] = 'python'
dic['version'] = 2.7
dic['platform'] = 64
for key in dic:
    print(key, dic[key])

输出的结果为:platform 64,lan python, version 2.7, 字典在迭代的过程 中将 key 作为可迭代的对象返回。注意字典中 key 是乱序的,也就是说和插入 的顺序是不一致的。如果想要使用顺序一致的字典,请使用 collections 模块 中的 OrderedDict 对象。

set 类型

s = set(['python', 'python2', 'python3','python'])
for item in s:
    print(item)

将会输出 python, python3, python2 set 集合将会去除重复项,注意输出的 结果也不是按照输入的顺序。

4.2 迭代器

Python 中的 for 句法实际上实现了设计模式中的迭代器模式 ,所以我们自己也可以按照迭代器的要求自己生成迭代器对象,以便在 for 语句中使用。 只要类中实现了 iter 和 next 函数,那么对象就可以在 for 语句中使用。 现在创建 Fibonacci 迭代器对象,

# define a Fib class
class Fib(object):
    def __init__(self, max):
        self.max = max
        self.n, self.a, self.b = 0, 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < self.max:
            r = self.b
            self.a, self.b = self.b, self.a + self.b
            self.n = self.n + 1
            return r
        raise StopIteration()

# using Fib object
for i in Fib(5):
    print(i)

将会输出前 5 个 Fibonacci 数据 1,1, 2, 3, 5

4.3 生成器

除了使用迭代器以外,Python 使用 yield 关键字也能实现类似迭代的效果,yield 语句每次 执行时,立即返回结果给上层调用者,而当前的状态仍然保留,以便迭代器下一次循环调用。这样做的 好处是在于节约硬件资源,在需要的时候才会执行,并且每次只执行一次。

def fib(max):
    a, b = 0, 1
    while max:
        r = b
        a, b = b, a+b
        max -= 1
        yield r

# using generator
for i in fib(5):
    print(i)

将会输出前 5 个 Fibonacci 数据 1,1, 2, 3, 5

if elif else 判断
基本使用

if condition1:
    true1_expressions
elif condition2:
    true2_expressions
elif condtion3:
    true3_expressions
elif ...
    ...
else:
    else_expressions

如果有多个判断条件,那可以通过 elif 语句添加多个判断条件,一旦某个条件为 True,那么将执行对应的 expression。 并在之代码执行完毕后跳出该 if-elif-else 语句块,往下执行。

实例

x = 4
y = 2
z = 3
if x > 1:
print (‘x > 1’)
elif x < 1:
print(‘x < 1’)
else:
print(‘x = 1’)
print(‘finish’)
因为 x = 4 那么满足 if 的条件,则将输出 x > 1 并且跳出整个 if-elif-else 语句块,那么紧接着输出 finish。 如果将 x = -2 那么将满足 elif x < 1 这个条件,将输出 x <1, finish。

全局变量

那如何在外部也能调用一个在局部里修改了的全局变量呢. 首先我们在外部定义一个全局变量 a=None, 然后再 fun() 中声明 这个 a 是来自外部的 a. 声明方式就是 global a. 然后对这个外部的 a 修改后, 修改的效果会被施加到外部的 a 上. 所以我们将能看到运行完 fun(), a 的值从 None 变成了 20.

APPLY = 100 # 全局变量
a = None
def fun():
    global a    # 使用之前在全局里定义的 a
    a = 20      # 现在的 a 是全局变量了
    return a+100

print(APPLE)    # 100
print('a past:', a)  # None
fun()
print('a now:', a)   # 20

\n 换行命令

定义 text 为字符串, 并查看使用 \n 和不适用 \n 的区别:

text='This is my first test. This is the second line. This the third '
print(text)  # 无换行命令

"""
This is my first test. This is the second line. This the third
"""

text='This is my first test.\nThis is the second line.\nThis the third line'
print(text)   # 输入换行命令\n,要注意斜杆的方向。注意换行的格式和c++一样

"""
This is my first test.
This is the second line.
This the third line
"""

open 读文件方式
使用 open 能够打开一个文件, open 的第一个参数为文件名和路径 ‘my file.txt’, 第二个参数为将要以什么方式打开它, 比如 w 为可写方式. 如果计算机没有找到 ‘my file.txt’ 这个文件, w 方式能够创建一个新的文件, 并命名为 my file.txt

my_file=open('my file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text)               #该语句会写入先前定义好的 text
my_file.close()                   #关闭文件 

\t tab 对齐

使用 \t 能够达到 tab 对齐的效果:

text='\tThis is my first test.\n\tThis is the second line.\n\tThis is the third line'
print(text)  #延伸 使用 \t 对齐

"""
	This is my first test.
	This is the second line.
	This is the third line

“”"

给文件增加内容

我们先保存一个已经有3行文字的 “my file.txt” 文件, 文件的内容如下:

This is my first test.
This is the second line.
This the third
然后使用添加文字的方式给这个文件添加一行 “This is appended file.”, 并将这行文字储存在 append_file 里,注意\n的适用性:

append_text='\nThis is appended file.'  # 为这行文字提前空行 "\n"
my_file=open('my file.txt','a')   # 'a'=append 以增加内容的形式打开
my_file.write(append_text)
my_file.close()

""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""

#运行后再去打开文件,会发现会增加一行代码中定义的字符串

读取文件内容 file.read()

使用 file.read() 能够读取到文本的所有内容.

file= open('my file.txt','r') 
content=file.read()  
print(content)

""""
This is my first test.
This is the second line.
This the third line.
This is appended file.    
""""

按行读取 file.readline() ¶

如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:

file= open('my file.txt','r') 
content=file.readline()  # 读取第一行
print(content)

""""
This is my first test.
""""

second_read_time=file.readline()  # 读取第二行
print(second_read_time)

"""
This is the second line.
"""

读取所有行 file.readlines()

如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果, 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.

file= open('my file.txt','r') 
content=file.readlines() # python_list 形式
print(content)

""""
['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']
""""

# 之后如果使用 for 来迭代输出:
for item in content:
    print(item)
    
"""
This is my first test.

This is the second line.

This the third line.

This is appended file.
"""

猜你喜欢

转载自blog.csdn.net/weixin_43758551/article/details/89245755