Python入门笔记整理

Python入门

Python与其他语言最大的区别就是,Python的代码块不使用大括号{}来控制类,函数以及其他逻辑判断,而是用缩进来写模块

数字和表达式

整除 //
求余 % (适用浮点数)
求幂 **
内建函数 pow/abs/round
math模块 floor/ceil/sqrt
cmath 复数模块 complex math
内建值 None

>>> import math
>>> math.floor(4.53)
4.0
>>> math.sqrt(9)
3.0
>>> foo = math.sqrt
>>> foo(9)
3.0
>>> math.ceil(4.53)
5.0

附加:
1.floor向下取整/ceil向上取整
2.Python支持变量引用函数 foo = math.sqrt

用户输入

input 保持原始输入类型
raw_input 原始输入转化为字符串

>>> x = input("x: ")
x: 12
>>> x
12

>>> x = raw_input("x: ")
x: 12
>>> x
'12'
模块导入
import somemodule
from somemodule import somefunction
from somemodule import somefunction, anothefunction, yetanotherfunction
from somemodule import *
from somemodule as selfname

tips:
查看模块内函数列表 dir(ModuleName)
查看全局/局部变量列表 globals()/locals()
重载模块 reload(ModuleName)
注释
单行注释(#)
多行注释('''/"""):

区别执行脚本首行
#/usr/bin/env python
字符串

单/双引号基本等同,特定场景可用

>>> "Hello 'world'"
"Hello 'world'"
>>> 'Hello "world"'
'Hello "world"'

或者转义
>>> "Hello \"world\""
'Hello "world"'
>>> 'Hello \'world\''
"Hello 'world'"

假如输出同时包含单/双引号,则必须转义
>>> 'Let\'s say "Hello world"'
'Let\'s say "Hello world"'

字符串拼接 +

>>> "Let's say" '"Hello world"'
'Let\'s say"Hello world"'
>>> "Hello, " + "world !"
'Hello, world !'

拼接包含数字

  • str 转换合理的字符串
  • repr 创建合理的字符串
>>> Temp = 100
>>> print "Hello world " + Temp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "Hello world " + repr(Temp)
Hello world 100
>>> print "Hello world " + str(Temp)
Hello world 100

字符串换行

  • 行末添加转义字符 \
  • 使用长字符串 三个单/双引号包含字符串,字符串中支持使用单/双引号(首尾需转义)
>>> "Hello, \
... world"
'Hello, world'

>>> """Let's say "Hello world""""
  File "<stdin>", line 1
    """Let's say "Hello world""""
                                ^
SyntaxError: EOL while scanning string literal
>>> """Let's say "Hello world\""""
'Let\'s say "Hello world"'
>>> '''Let's say "Hello world"'''
'Let\'s say "Hello world"'

原始字符串(添加r表示) 支持特殊字符

>>> print "Hello \nworld"
Hello
world
>>> print r"Hello \nworld"
Hello \nworld

Unicode(添加u表示)

  • python字符串默认8位ASCII码存储,Unicode使用16位Unicode字符存储
>>> "北京"
'\xe5\x8c\x97\xe4\xba\xac'
>>> u"北京"
u'\u5317\u4eac'

格式化输出(%)

Type "help", "copyright", "credits" or "license" for more information.
>>> format = 'Hello %s, %s enough for ya ?'
>>> values = ('world', 'Hot')
>>> print format % values
Hello world, Hot enough for ya ?

附加:若使用元组作为参数 括号不可以省略

字符串常用函数

find/join/split/lower/title/replace/strip/translate

replace/translate功能相同,区别,translate只处理单个字符,但支持同时执行多个替换,效率更高
>>> 'I love Beijing'.replace('Beijing', 'Hunan')
'I love Hunan'
>>> import string
>>> table = string.maketrans('ac','ca')
>>> table[97:123]
'cbadefghijklmnopqrstuvwxyz'
>>> 'aaaaa'.translate(table)
'ccccc'
列表(’[]’)
>>> edward = ['Edward Gumby',42]
>>> john = ['Jhon Smith', 50]
>>> database = [edward, john]
>>> database
[['Edward Gumby', 42], ['Jhon Smith', 50]]

索引/相加/相乘

#!/usr/bin/env python
months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
]

endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
        + ['st', 'nd', 'rd'] + 7 * ['th'] \
        + ['st']

year = raw_input('Year: ')
month = raw_input('Month (1-12): ')
day = raw_input('Day (1-31): ')

month_number = int(month)
day_number = int(day)

month_name = months[month_number - 1]
ordinal = day + endings[day_number]

print month_name + ' ' + ordinal + '. ' + year

分片

>>> numbers = [1, 2, 3, 4, 5, 6]
>>> numbers[0:3]
[1, 2, 3]
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> numbers[:3]
[1, 2, 3]
>>> numbers[-3:-1]
[4, 5]
>>> numbers[-3:]
[4, 5, 6]

支持步长
>>> numbers[0:6:2]
[1, 3, 5]
>>> numbers[::-2]
[6, 4, 2]

附加:指定开始/结束点,开始点元素包含在结果中,结束点元素不在结果中

成员资格

#!/usr/bin/env python

database = [
	['albert', '1234'],
	['dilbert', '4242'],
	['smith', '8520']
]

username = raw_input('User name: ')
pin = raw_input('PIN code: ')

if [username, pin] in database: print 'Access granted'
else: print 'Access failed'

长度/最小值/最大值

len/min/max 省略

字符串/列表转换

>>> say = list('HelloWorld')
>>> say
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
>>> ''.join(say)
'HelloWorld'
>>> ' '.join(say)
'H e l l o W o r l d'

赋值/删除

>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']
>>> del name[1]
>>> name
['P', 't', 'h', 'o', 'n']
>>> name[1:5] = []
>>> name
['P']

列表方法(append/count/extend/index/insert/pop/remove/reverse/sort)

>>> numbers = [1,2,3]
>>> numbers
[1, 2, 3]
>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4]
>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4, 4]
>>> numbers.count(4)
2
>>> numbers.pop(3)
4
>>> numbers
[1, 2, 3, 4]
>>> numbers.extend([5,6,7,8])
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers.index(4)
3
>>> numbers.insert(9,8)
>>> numbers
[1, 2, 3, 4, 5, 5, 6, 7, 8, 8]
>>> numbers.pop()
8
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers.remove(8)
>>> numbers
[1, 2, 3, 4, 5, 6, 7]
>>> numbers.reverse()
>>> numbers
[7, 6, 5, 4, 3, 2, 1]
>>> numbers.sort()
>>> numbers
[1, 2, 3, 4, 5, 6, 7]

简单赋值(x/y指向相同指针)
>>> x = [4,6,2,1,8]
>>> y = x
>>> y
[4, 6, 2, 1, 8]
>>> x.sort()
>>> x
[1, 2, 4, 6, 8]
>>> y
[1, 2, 4, 6, 8]

获取排序副本
>>> y = sorted(x)
>>> y
[1, 2, 4, 6, 8]

高级排序(支持参数key/reverse)
>>> x = ['Perl', 'Python', 'Erlang', 'C++']
>>> x.sort(key=len, reverse=True)
>>> x
['Python', 'Erlang', 'Perl', 'C++']
元组(’()’)
类似列表,但元组不支持二次赋值
元组用括号表示,逗号隔开
>>> (1,2,3)
(1, 2, 3)
>>> (1,)
(1,)
>>> ()
()
>>> 3 * (40 + 2)
126
>>> 3 * (40 + 2,)
(42, 42, 42)
>>> x = 1,2,3
>>> x
(1, 2, 3)
>>> x[1]
2
>>> x[0:2]
(1, 2)
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)
字典(’{}’)

Python中唯一内建的映射类型(查询效率高于列表,规模越大,两者效率差距越明显),此外字典是无序的,列表通过偏移存储,字典通过键值存储

>&g
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Python入门笔记,我可以提供一些基本的知识点: 1. 在Python中,数字和字符串不能直接进行加法运算,只能是字符串和字符串的拼接。 2. 在编写Python程序时,如果在字符串中使用单引号,需要注意使用成对出现的单引号。如果使用单个单引号,可能会导致解析器报错。 3. 在Python中,逻辑运算符'and'和'or'不一定会计算右侧表达式的值。有时只需计算左侧表达式即可得出结果。这是因为'and'和'or'会将其中一个表达式的值作为最终结果,而不仅仅是True或False。 4. Python的流程控制中,顺序结构是最基本的结构,按照代码的编写顺序依次执行。 这些是Python入门笔记中的一些要点,希望对你有所帮助。如果你有其他问题,欢迎继续提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [python入门课程笔记](https://blog.csdn.net/YV_LING/article/details/123413336)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [python入门学习笔记](https://blog.csdn.net/Lalalalazy/article/details/113181549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值