python入门详解 1

本文章内容:

简介,命令行参数,
print,keyword,type,arithmetic,
赋值-比较-布尔-位 运算符,条件表达式,
pass,range,for,break,continue,else子句,
list (创建-生成式-索引-获取-切片-判断-遍历-增加-删除-排序)

# author: ljt
# 2023/5/30 20:28


# python一切皆对象,所有对象都有一个布尔值
# 获取对象的布尔值,使用内置函数bool()
# False None 数值0 空字符串 空列表 空元组 空字典 空集合, 布尔值均为False
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(0.0))
print(bool(''))
print(bool(""))
print(bool([]))  # 空列表
print(bool(list()))  # 空列表
print(bool(()))  # 空元组
print(bool(tuple()))  # 空元组
print(bool({}))  # 空字典
print(bool(dict()))  # 空字典
print(bool(set()))  # 空集合
# 例子
age = int(input("pls input your age:"))
if age:  # 使用对象的 bool 值来做判断
    print(age)
else:
    print('age is:', age)


'''
解释器读取命令行参数,把脚本名与其他参数转化为字符串列表存到 sys 模块的 argv 变量里。
执行 import sys,可以导入这个模块,并访问该列表。该列表最少有一个元素;未给定输入参数时,
sys.argv[0] 是空字符串。给定脚本名是 '-' (标准输入)时,sys.argv[0]'-'。
使用 -c command 时,sys.argv[0]'-c'。如果使用选项 -m module,sys.argv[0] 就是包含目录的模块全名。
解释器不处理 -c command 或 -m module 之后的选项,而是直接留在 sys.argv 中由命令或模块来处理。
例如:执行 python.exe build.py -env "%BUILD_TOOLS_PATH%" %* , 则 sys.argv[0] 值为 build.py
'''


# print
# print the integer type data
print(520)

# print the float type data
print(1.5)

# print the arithmetic
print(1.5 + 1)

# print the string
print('hello')
print("nihao")

print("ni", "hao", "ma")  # the result : ni hao ma
print("ni" + "hao" + "ma")  # the result : nihaoma

print('merry\'hello')  # the result : merry'hello
print('merry\"hello')  # the result : merry"hello
print('merry\nhello')  # the result : merry
                                    # hello
print('merry\rhello')  # the result : hello
print('merry\thello')  # the result : merry   hello
print('merry\bhello')  # the result : merrhello
print('merry\\hello')  # the result : merry\hello
print('merry\\\\hello')  # the result : merry\\hello

# print the many lines string
print("""   草
离离原上草,
一岁一枯荣。
野火烧不尽,
春风吹又生。""")

# print the many lines string with format
# 1
print("""   {0}
离离原上{0}{1}{1}枯荣。
野火烧不尽,
春风吹又生。""".format("草", "一"))
# 2
name = "草"
num = "一"
print("""   {name}
离离原上{name}{num}{num}枯荣。
野火烧不尽,
春风吹又生。""".format(name=name, num=num))
# 3
c = "草"
y = "一"
print(f"""   {c}
离离原上{c}{y}{y}枯荣。
野火烧不尽,
春风吹又生。""")

# print the content to file
f = open("test.txt", "a+", encoding="utf-8")
print("print a new line", file=f)
print(520, file=f)
f.close()


#  所有的保留字
# ['False', 'None', 'True', 'and', 'as',
# 'assert', 'async', 'await', 'break', 'class',
# 'continue', 'def', 'del', 'elif', 'else',
# 'except', 'finally', 'for', 'from', 'global',
# 'if', 'import', 'in', 'is', 'lambda',
# 'nonlocal', 'not', 'or', 'pass', 'raise',
# 'return', 'try', 'while', 'with', 'yield']
import keyword
print(keyword.kwlist)


# variable info
name = 'alice'
print("标识", id(name))
print("类型", type(name))
print("值", name)

#  integer info
n1 = 90
n2 = 0
n3 = -89
print(n1, type(n1))
print(n2, type(n2))
print(n3, type(n3))

print('十进制', 180)
print('二进制', 0b10110100)
print('八进制', 0o264)
print('十六进制', 0xb4)

# float
print(1.1 + 2.2)  # the result is 3.300000003
from decimal import Decimal
print(Decimal('1.1') + Decimal('2.2'))

# bool
b1 = True
b2 = False
print(b1, type(b1))
print(b2, type(b2))
print(b1 + 1)  # True means 1
print(b2 + 1)  # False means 0

# string
s1 = 'alice is a good girl.'
s2 = "alice is a good girl."
s3 = '''alice
is a good
girl.'''
s4 = """alice
is a good
girl."""
print(s1, type(s1))
print(s2, type(s2))
print(s3, type(s3))
print(s4, type(s4))


# arithmetic
# // 整除(一正一负向下取整)
print(11//2)  # result is 5
print(9//-4)  # result is -3
print(-9//4)  # result is -3
# % 取余(一正一负要公式,余数=被除数-除数*商)
print(9 % -4)  # result is -3=9-(-4)*(-3)=9-12
print(-9 % 4)  # result is 3=-9-4*(-3)=-9+12

# 赋值运算符
a = b = c = 20  # 支持链式赋值
a += 10  # 支持参数赋值 += -= *= /= //= %=
m, n, p = 20, 30, 40  # 支持系列解包赋值
m, n = n, m  # 使用系列解包赋值实现交换两个变量的值

# 比较运算符
# 一个变量由三部分组成:标识,类型,值
# == 比较的是值还是标识呢? 比较的是值
# 比较对象的标识使用 is/is not
a = 10
b = 10
print(a == b)  # result is True
print(a is b)  # result is True
# 分析:python 中首先为变量 a 创建一个对象,标识id 类型int 值10
#      变量 b ,发现已经有该对象了,则不会再创建新的对象,而是直接将该对象的标识给b
#      从而 a==b 结果为ture, a is b 结果也为ture。即变量 a b 值相等,标识也一样
list1 = [1,2,3,4]
list2 = [1,2,3,4]
print(list1 == list2)  # result is True
print(list1 is list2)  # result is False
# list1 id != list2 id ???

# 布尔运算符
# and 与, or 或, not 取反, in, not in
a, b = 1, 2
# and 与
print(a == 1 and b == 2)
print(a == 1 and b < 2)
# or 或
print(a == 1 or b < 2)
print(a < 1 or b == 2)
# not 取反
print(not a == 1)
print(not False)
# in
s = 'helloworld'
print('w' in s)
print('k' in s)
# not in
print('k' not in s)

# 位运算符
# & 按位与, | 按位或, << 左移, >> 右移

# 运算符的优先级
# 算术运算 位运算 比较运算 布尔运算 赋值运算
# 1.1 **
# 1.2 * / // %
# 1.3 + -
# 2.1 << >>
# 2.2 &
# 2.3 |
# 3.1 > < >= <= == !=
# 4.1 not
# 4.2 and
# 4.2 or
# 5.1 =


# 顺序结构,选择结构,循环结构


# 条件表达式
a = int(input("pls input a num:"))
b = int(input("pla input b num:"))
print(str(a) + '>=' + str(b) if a >= b else str(a) + '<' + str(b))
#                            --------------
# 其中 if a >= b else 为判断条件,但 a >= b 成立时,执行 左侧的语句,不成立则执行 右侧的语句


# pass语句
# 什么也不做,只是一个占位符,用在语法上需要语句的地方
# 先搭建语法结构,还没想好代码怎么写的时候,用 pass 来占位置


# 内置函数 range(): 生成一个整数序列
# range(stop) 创建一个[0, stop)之间的整数序列,步长为1
# range(start, stop) 创建一个[start, stop)之间的整数序列,步长为1
# range(start, stop, step) 创建一个[start, stop)之间的整数序列,步长为step
# 返回值是一个迭代器对象
# range 类型的优点:不管range对象表示的整数序列多长,所有range对象占用的内存空间都是相同的,
#   因为仅仅需要存储start,stop和step,只有当用到 range 对象时,才会去计算序列中的相关元素。
# in/not in 判断整数序列中是否存在(不存在)指定的整数
a = range(10)
print(a)  # range(0, 10)
print(list(a))  # [0, 1, 2..., 8, 9]
print(10 in a)  # False
print(10 not in a)  # True
print(9 in a)  # True


# for-in 循环
# for 自定义变量 in 可迭代对象:
# ....循环体
# in表达从字符串、序列等中依次取值,又称为遍历
# 遍历的对象必须是可迭代对象
# 如果在循环体中不需要使用到自定义变量,可将自定义变量写为“_”
for i in 'python':
    print(i)
for item in range(1, 11):
    print(item)
for _ in range(5):
    print("人生苦短,我用python")

# 打印 100-999 之间的水仙花数
# 153 = 3*3*3 + 5*5*5 + 1*1*1
cnt = 0
temp = 0
ge = 0
shi = 0
bai = 0
for i in range(100, 1000):
    ge = i % 10
    shi = (i // 10) % 10
    bai = i // 100
    if ge**3 + shi**3 + bai**3 == i:
        print(i)
        cnt += 1
print('cnt is', cnt)  # 153 370 371 407


# break 语句
# 用于结束循环结构,通常与分支结构 if 一起使用,非正常结束循环
a = 0
while a < 3:
    pwd = input('pls input pwd:')
    if pwd == '8888':
        print('pwd is ok')
        break
    else:
        print('pwd is error')
        a += 1


# continue 语句
# 用于结束当前循环,进入下一次循环,通常与分支结构 if 一起使用
for i in range(1, 101):
    if i % 5 != 0:
        continue
    else:
        print(i)


# else 语句
# 与 else 语句配合使用的三种情况
# 1. if ... else ...  if条件表达式不成立时执行else
# 2. while ... else ...  没有碰到break时执行else
# 3. for ... else ... 同上
for i in range(3):
    pwd = input('pls input pwd:')
    if pwd == '8888':
        print('pwd is ok')
        break
    else:
        print('pwd is error')
else:
    print('sorry, too many error')


# 嵌套循环
# 打印 九九乘法表
for x in range(1, 10):
    for y in range(1, x + 1):
        print(f'{x}*{y}', end='\t')  # 不换行输出
    print()  # 只换行,什么都不打印

# 流程控制语句
# 二重循环中的 break 和 continue 用于控制本层循环
for i in range(5):
    for j in range(1, 11):
        if j % 2 == 0:
            break
        print(j)
for i in range(5):
    for j in range(1, 11):
        if j % 2 == 0:
            # break
            continue
        print(j, end='\t')
    print()


# 列表
# 变量可以存储一个元素,而列表是一个大容器,可以存储N多个元素,程序可以方便地对这些数据进行整体操作
# 列表相当于其他语言中的数组
# 特点
# 1. 列表元素按顺序排序
# 2. 索引映射唯一数据
# 3. 列表可以存储重复数据
# 4. 任意数据类型混存
# 5. 根据需要动态分配和回收内存
a = 10  # 变量存储的是一个对象的引用
lst = ['hello', 'world', 98]
print(id(lst))
print(type(lst))
print(lst)

# 列表的创建
# 使用[], 或者内置函数 list()
lst1 = ['hello', 'world', 98]
lst2 = list(['hello', 'world', 98, 'hello'])
print(lst1[0], lst[-3])
# 列表生成式
# [i for i in range(1, 10)]
# 第一个i是 表示列表元素中表达式
lst = [i*i for i in range(1, 10)]
print(lst)  # [1, 4, 9, 16, 25, 36, 49, 64, 81]
lst1 = [i*2 for i in range(1, 6)]
print(lst1)  # [2, 4, 6, 8, 10]

# 列表元素索引
# 列表中存在N个相同元素,只返回相同元素中的第一个元素的索引
# 如果查询的元素在列表中不存在,则会抛出 ValueError
# 还可以在指定的 start 和 stop 之间查找
lst = ['hello', 'world', 98, 'hello']
print(lst.index('hello'))  # 0
print(lst.index('python'))
print(lst.index('hello', 1, 4))  # 3

# 获取单个元素
# 正向索引从 0 到 N-1,如 lst[0]
# 逆向索引从 -N 到 -1,如 lst[-N]
# 指定索引不存在,抛出 IndexError
lst = ['hello', 'world', 98, 'hello', 'world', 234]
print(lst[2])  # 98
print(lst[-3])  # hello
print(lst[10])  # IndexError: list index out of range

# 列表切片
# 获取列表中的多个元素,list_name[start:stop:step]
# 结果:原列表片段的拷贝,原列表不变,产生新的列表对象
# 范围:[start, stop)
# step 默认为 1,简写为 [start:stop]
# step 为正数,[:stop:step] 切片的第一个元素默认是列表的第一个元素     |
# step 为正数,[start::step] 切片的最后一个元素默认是列表的最后一个元素 |->从start开始往后计算切片
# step 为负数,[:stop:step] 切片的第一个元素默认是列表的最后一个元素   |
# step 为负数,[start::step] 切片的最后一个元素默认是列表的第一个元素  |->从start开始往前计算切片
lst = [10, 20, 30, 40, 50, 60, 70, 80]
print(lst[1::2])
print(lst)  # lst not changed
print(lst[::-1])  # 将原列表反过来
print(lst[7::-1])
print(lst[6:0:-2])

# 列表元素判断及遍历
lst = [10, 20, 'python', 'hello']
print(10 in lst)  # True
print(100 in lst)  # False
print(10 not in lst)  # False
for i in lst:
    print(i)

# 列表元素的增加
# append() 在列表的末尾添加一个元素
# extend() 在列表的末尾至少添加一个元素
# insert() 在列表的任意位置添加一个元素
# 切片 在列表的任意位置添加至少一个元素
lst = [10, 20, 30]
print('previous ', id(lst))
lst.append(100)
print('after ', id(lst))  # 没有增加新的列表
print(lst)
lst2 = ['hello', 'world']
lst.append(lst2)  # 将lst2作为一个元素添加到lst的末尾
print(lst)
lst.extend(lst2)  # 向列表一次性添加多个元素
print(lst)
lst.insert(1, 'alice')  # 在任意位置
print(lst)

lst3 = [True, False, 'hello']
lst[1:] = lst3  # 从index=1的地方将原列表切掉,并将新列表添加到末尾
print(lst)

# 列表元素删除
# remove() 一次删除一个元素,重复元素只删除第一个,元素不存在抛出ValueError
lst = [10, 20, 30, 40, 50, 60, 70, 80]
lst.remove(30)
#lst.remove(90)  # ValueError: list.remove(x): x not in list
print(lst)

# 根据索引移除元素
# pop() 删除一个指定索引位置上的元素,指定索引不存在抛出IndexError,不知道索引则删掉最后一个元素
lst.pop(0)
#lst.pop(8)  # IndexError: pop index out of range
lst.pop()
print(lst)

# 切片,一次至少删除一个元素
lst[1:3] = []
print(lst)

# 清除列表中元素,列表为空
lst.clear()
print(lst)

# 删除列表
del lst
print(lst)  # NameError: name 'lst' is not defined. Did you mean: 'list'?

# 修改一个元素
lst = [10, 20, 30, 40]
lst[0] = 20
print(lst)

# 切片修改至少一个元素
lst[1:3] = [300, 400, 500, 600]
print(lst)

# 排序
# 调用sort()方法
lst = [10, 60, 50, 89, 3]
print('排序前列表', lst, id(lst))
lst.sort()  # 升序排列
print('排序后列表', lst, id(lst))
lst.sort(reverse=True)
print('排序后列表', lst, id(lst))
# 使用内置函数sorted(),将产生新的列表
lst1 = sorted(lst)
print('排序后列表', lst1, id(lst1))
lst1 = sorted(lst, reverse=True)
print('排序后列表', lst1, id(lst1))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值