005、Python演示
本文最后更新于 68 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

Python演示

数学运算

简单的数学运算:

2 + 2
4
7 - 2.5
4.5
3 * 2.5
7.5
8 / 4
2.0

赋值

使用变量名=表达式赋值:

a = 0.2

字符串

字符串生成,单引号与双引号是等价的:

s = "hello world"
s = 'hello world'

三引号用来输入包含多行文字的字符串:

"""hello
world"""
'hello\nworld'

字符串的加法:

"hello" + " world"
'hello world'

字符串索引:

s[0]
'h'
s[-1]
'd'
s[:5]
'hello'

字符串的分割:

s.split()
['hello', 'world']

字符串的长度:

len(s)
11

列表

列表可以用中括号生成:

a = [1, 2.0, 'hello', 5 + 1.0]
a
[1, 2.0, 'hello', 6.0]

加法:

a + a
[1, 2.0, 'hello', 6.0, 1, 2.0, 'hello', 6.0]

列表索引:

a[1]
2.0

长度:

len(a)
4

添加元素:

len(a)
4

集合

集合可以用花括号生成:

s = {2, 3, 4, 2}
s
{2, 3, 4}

集合的长度:

len(s)
3

向集合中添加元素:

s.add(1)

集合的交:

a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
a & b
{2, 3, 4}

并:

a | b
{1, 2, 3, 4, 5}

差:

a - b
{1}

字典

Python用{key:value}来生成字典:

d = {'dogs':5, 'cats':4}
d
{'dogs': 5, 'cats': 4}

大小:

len(d)
2

查看字典某个键对应的值:

d["dogs"]
5

修改键值:

d["dogs"] = 2
d
{'dogs': 2, 'cats': 4}

插入:

d["pigs"] = 7
d
{'dogs': 2, 'cats': 4, 'pigs': 7}

NumPy数组

很多高级的数学运算可以通过数组完成。首先需要导入NumPy:

import numpy as np

a = np.array([1, 2, 3, 4])

一些数学运算:

a + 2
array([3, 4, 5, 6])
a + a
array([2, 4, 6, 8])
a * 2
array([2, 4, 6, 8])

可视化

可以用Matplotlib对数据进行可视化:

from matplotlib import pyplot as plt
plt.plot(a, a**2)
[]


png

循环

可以使用for语句进行循环:

line = '1 2 3 4 5'
fields = line.split()
fields
['1', '2', '3', '4', '5']
total = 0
for field in fields:
    total += int(field)
total
15

列表推导式,用for循环生成列表:

numbers = [int(field) for field in fields]
numbers
[1, 2, 3, 4, 5]

文件操作

写文件:

f = open('data.txt', 'w')
f.write('1 2 3 4\n')
f.write('2 3 4 5\n')
f.close()

读文件:

f = open('data.txt')
data = []
for line in f:
    data.append([int(field) for field in line.split()])
f.close()

data
[[1, 2, 3, 4], [2, 3, 4, 5]]

删除文件:

import os
os.remove('data.txt')

函数

使用括号对函数进行调用:

abs(-12.3)
12.3

def定义函数:

def poly(x, a, b, c):
    y = a * x ** 2 + b * x + c
    return y
x = 1
poly(x, 1, 2, 3)
6

用Numpy数组做参数:

x = np.array([1, 2, 3])
poly(x, 1, 2, 3)
array([ 6, 11, 18])

模块

import导入模块:

import os

当前系统分隔符:

os.sep
'/'

用class定义类:

class Person(object):
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age
    def full_name(self):
        return self.first + ' ' + self.last

构建对象:

person = Person('Mertle', 'Sedgewick', 52)

调用对象的属性:

person.first
'Mertle'

调用对象的方法:

person.full_name()
'Mertle Sedgewick'

错误处理

输入错误的代码会提示报错:

谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇