python简单快速入门(建议有代码基础的看)

一、看完这个,你就可以试着进一步学习连接数据库、文件、线程等难点部分


```python
# 第一个注释
"""
   注释1
"""
'''
    注释2
'''

# 行与缩进
print("判断开始")
if True:
    print("True")
else:
    print("False")
print("判断结束")

# 多行语句 在  () [] {}就不用反斜杠'\' 
total = item_one + \
        item_two + \
        item_three
total = ['item_one', 'item_two', 'item_three']

# 数字类型
i = 1  # int
ii = True  # bool
iii = 1.23  # float
iiii = 1 + 2j  # complex

# 字符串类型
word1 = 'String'
word2 = "String"
word3 = """这是一个段落"""
print(word1)
print(word1[0])  # 输出第一个字符
print(word1[0:-1])  # 输出0到倒数第二个的所有字符串
print(word1[1:4])
print(word1[2:])
print(word1 * 2)  # 输出字符串两次
print(word1 + "hello")  # 连接字符串
print('hello\nworld')  # 转义字符串
print(r'hello\nworld')  # 原始字符串,不会发生转义
print("%s今年%d岁了" % ('mimi', 19))  # 格式化
# 字符串方法
word1.capitalize()  # 转大写
word1.upper()
word1.lower()
word1.center(12, '12')  # 指定宽度填充字符
word1.count('s', 0, len(word1) - 1)  # 统计字符出现次数
word1.startswith("1")  # 以什么开头
word1.endswith("1")  # 以什么结尾
word1.find('i', 0, len(word1) - 1)  # 寻找字符
word1.index('i', 0, len(word1) - 1)  # 寻找字符,找不到抛异常
word1.isalpha()  # 字符串中至少有一个字母-->True
word1.isdigit()  # 字符串中至少有一个数字-->True
word1.islower()  # 都是小写-->True
word1.isupper()  # 都是大写-->True
word1.isnumeric()  # 都是数字-->True
word1.isdecimal()  # 只包含十进制数字
word1.istitle()
word1.isspace()  # 只包含空格
word1.join()
word1.ljust()  # 左对齐
word1.lstrip()
max(word1)
min(word1)
word1.split()
word1.swapcase()  # 转换大小写

# 列表
list = ['123', True, 123, 2.12]
list2 = [1, 2, 3]
print(list)
print(list[0])
print(list[-1])
print(list[1:3])
print(list[2:])
print(list * 2)
print(list + list2)

str = "1 2 3"
str_list = str.split(" ")  # 字符串转列表
str2_list = str_list[-1::-1]
str2 = ' '.join(str2_list)  # 重新组成新的字符串,并实现反转

# 列表方法
len(list)
max(list)
min(list)
list(tuple)  # 将元组转换为列表
list.append()
list.count('1')
list.extend("12")  # 在末尾追加元素
list.index()
list.insert(0, '1')  # 插入元素
list.pop(2)  # 移除元素,默认是最后一个
list.remove('12')  # 删除元素
list.reverse()  # 反转
list.sort()  # 排序
list.clear()  # 清空
list.copy()  # 复制

# 元组
tuple = ('123', True, 123, 2.12)
tuple2 = ('123', True, 123, 2.12)
print(tuple[0])
print(tuple[-2])
print(tuple[1:2])
print(tuple[2:])
print(tuple * 2)
print(tuple + tuple2)
tuple3 = ([1, 2, '1'], 1, "123", True, 1.22)  # 包含列表的元组,元祖的元素不可以修改,但是里面的列表元素可以改变
# 元组方法
len(tuple)
max(tuple)
min(tuple)
tuple(list)

# 集合
student = {'Tom', 'Jim', 'Mary', 'Jack', 'Jim'}
print(student)  # 集合可以去重
if 'Tom' in student:
    print('Tom在集合中')
else:
    print('Tom不在集合中')

"""
集合运算
"""
a = set('asasasds')
b = set('dwadadaa')
print(a - b)  # 差集
print(a | b)  # 并集
print(a & b)  # 交集
print(a ^ b)  # a和b不同时在的元素
# 集合方法
len(a)
max(a)
min(a)
a.clear()
a.add()  # 添加
a.copy()
a.discard()  # 删除
a.intersection()  # 交集
a.issubset()  # 是否是子集合
a.pop()  # 随机移除
a.remove()
a.symmetric_difference()  # 不同的
a.union()  # 并集
a.update()  # 添加

# 字典
dict = {}
dict['one'] = "1 - 菜鸟工具"
dict[2] = "2 - 菜鸟教程"
tinydict = {'name': 'runnoob', 'code': 1, 'site': 'www.baidu.com'}

# 数据类型转换
int(1.2)
float(1)
complex(12)
str(123)
tuple()
list()
set()
dict()
chr()  # 字符
ord()  # 十进制
hex()  # 十六进制
oct()  # 八进制
# 字典方法
len(dict)
str(dict)  # 输出字典
type(dict)  # 输出字典类型
dict.clear()
dict.copy()
dict.fromkeys()  # 创建一个新字典
dict.get()  # 查找
dict.setdefault()  # 查找,如果没有,会自动创建一个值为default的新键
key in dict
dict.keys()  # 遍历键
dict.update(tinydict)  # 将字典的键值信息更新给另外一个字典
dict.values()
dict.pop('121')
dict.popitem()

# 运算符
"""
算术运算符 + - * / % ** //
"""
print(1 ** 2)  # 求1的2次方
print(2 // 4)  # 整除
"""
比较运算符 == >= <= != > <
"""

"""
赋值运算符 += -= *= /= %= **= //= :=海象运算符
"""

"""
位运算符 &位与 |位或 ^位异或 ~位取反 <<<左移 >>>右移
"""

"""
逻辑运算符 and or not
"""

"""
成员运算符 in   not in
"""

"""
身份运算符 is   is not
"""

# 空行

# 等待用户输出
input("\n\n按下 enter 键退出")

# 同一行显示多条语句
import sys;

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

# 多条语句构成代码组
if exception:
    suite
elif exception:
    suite
else:
    suite

# 输出
x = 'a'
y = 'b'
print("---------------")
print(a)
print(a, end=" ")
print(b, end=" ")

# 导入
import sys

print("=================PYTHON IMPORT MODE====================")
print("命令行参数为:")
for i in sys.argv:
    print(i)
print("Python 的路径为:" + sys.path)

from sys import argv, path

print("=================PYTHON IMPORT MODE====================")
print("命令行参数为:")
for i in sys.argv:
    print(i)
print("Python 的路径为:" + sys.path)

# 条件语句
# if语句
if condition_1:
    statement_block_1
else:
    statement_block_2

if condition_1:
    statement_block_1
elif condition2:
    statement_block_2
else:
    statement_block_3
# if嵌套
if i >= 1:
    if i == 2:
        j == i
    else:
        j -= 1
else:
    i -= 1

# 循环语句
# while循环
a = 1
while a < 10:
    sum += a
    a += 1
    if a < 10:
        continue

# while循环中使用else语句
a = 1
while a < 10:
    sum += a
    a += 1
    print("a小于10")
else:
    print("a大于或等于10")

# 简单语句组
flag = 1
while (flag): print("True"), print("False")

# for语句和range函数
for i in range(5):
    print(i)
else:
    print(i - 1)

# break continue pass空语句
if i > 0:
    j += i
    i -= 1
    for k in range(j):
        print(k)
        pass
        if (k < 2):
            continue
        else:
            break
    else:
        pass
else:
    print(i)

# 迭代器与生成器
"""
    迭代器
"""
list = [1, 2, 3, 4]
it = iter(list)
for i in next(it):
    print(i)

# 创建迭代器省略

"""
    生成器
"""
import sys


def fibonacci(n):
    a, b, count = 0, 1, 0
    while True:
        if count > n:
            return
        yield a
        a.b = b, a + b
        count += 1


while True:
    try:
        print(next(f), end=" ")
    except StopAsyncIteration:
        sys.exit()

# 函数省略

# File
file = ""
file2=open(file, mode='r')
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file2.close()
file2.flush()
file2.fileno()
file2.isatty()
file2.read()
file2.readline()
file2.readlines()
file2.seek()
file2.tell()
file2.truncate()
file2.write()
file2.writelines()

# OS 省略

# 错误和异常
try:
    print()
except:
    print()
finally:
    print()

发布了11 篇原创文章 · 获赞 2 · 访问量 509

猜你喜欢

转载自blog.csdn.net/weixin_45191282/article/details/104058153