Python 小白必看!万字示例代码块,零基础也能无痛入门

Python基础语法


目录

Python基础语法

1.输出一个 "hello world"

2.常量和表达式

3.变量和类型

4.动静态类型

5.格式化字符串

6.输入与输出

7.算术运算符

8.关系运算符

9.赋值运算符

10.条件语句

11.while循环语句

12.for循环语句

13.函数

14.列表

15.元组

16.字典

17.哈希

18.文件操作

19.python中库的使用


1.输出一个 "hello world"

print('hello world')    #hello world

2.常量和表达式

**示例:输出常量和表达式值**

print(1+2-3)    #0
print(1+2*3)    #7
print(1+2/3)    #1.6666666666666665
print((67.5+89.0+12.9+32.2)/4)    #50.400000000000006

3.变量和类型

**示例1:整形和浮点**

    1.整数int::python中的int表示的数据范围是“无穷”的,可以根据要表示数据的大小进行自动扩容;

    2.浮点数float:python中的float就是双精度浮点数,等同于C/C++中的double;

a=10
b=a
print(a)    #10
print(b)    #10
print(type(a))     #<class 'int'>
b=0.15
print(type(b))     #<class 'float'>

**示例2:字符串**

c='str1'
print(c)
print(type(c))     #<class 'str'>

d="str2"
print(d)
print(type(d))     #<class 'str'>

e='My name is "xxx"'
print(e)     #My name is "xxx"
print(type(e))     #<class 'str'>

f=''' My 'name' is "xxx" '''
print(f)        # My 'name' is "xxx"
print(type(f))     #<class 'str'>

**示例3:字符串的拼接**

g='hello'
h='world'
print(len(g)) #5
print(len(h)) #5
print(g+h)    #helloworld 
              #字符串类型在python中通过+操作直接实现拼接

**示例4:布尔类型**

i=True
print(type(i))    #<class 'bool'>
print(i)

j=False
print(type(j))    #<class 'bool'>
print(j)
#True/False首字母不能小写

注意:

    1.不同的类型,占用的内存空间是不同的:int 默认是4个字节,动态扩容;float固定8个字节;string是变长;bool一个字节就足够了;

    2.不同的类型,对应能够进行的操作也是不同的:int/float  +-*/是可以的,但是不能使用len;str +和len是可以的,但是不可以-*/;

**示例5:计算方差**

avg=(67.5+89.0+12.9+32.2)/4
total=(67.5-avg)**2+(89.0-avg)**2+(12.9-avg)**2+(32.2-avg)**2   
#注意:(num)**2 为 num^2
res=total/4
print(res)

4.动静态类型

**示例1:python的动态变量**

    1.动态类型:程序运行过程中,变量的类型可能会发生改变;(python)

    2.静态类型:程序在运行过程中,变量的类型始终不变;(c/c++)

x=10
print(type(x))    #<class 'int'>

x=3.14
print(type(x))    ##<class 'float'>

x='hello'
print(type(x))    #<class 'str'>

x=True
print(type(x))    #<class 'bool'>

**示例2:python中类型的显示定义**

x:int =10

x:float =3.14

x:str ='hello'

x:bool=True

5.格式化字符串

**示例:格式化格式**

aa=10
print(f"aa={aa}")    #aa=10
print(f"aa={aa+10}")    #aa=20

6.输入与输出

**示例1:输入操作**

num=input('请输入一个整数:')
#print(num)  这样输出会直接报错,因为我们输入是以字符串形式输入的,所以需要通过格式化形式输出,或者进行一次类型转换;
print(f'输入的整数为:{num}')

num1=input('请输入一个整数:')
num2=input('请输入一个整数:')
print(f'输入的整数为:{num1+num2}')
num1=int(num1)
num2=int(num2)
print(num1+num2)

**示例2:输入四个小数,求出四个小数的平均值**

num3=input('请输入一个小数:')
num4=input('请输入一个小数:')
num5=input('请输入一个小数:')
num6=input('请输入一个小数:')
num3=float(num3)
num4=float(num4)
num5=float(num5)
num6=float(num6)
avg1=(num3+num4+num5+num6)/4
print(f'平均值:{avg1}')

7.算术运算符

**示例1:整数除以整数可以为小数**

print(1/2)    #0.5
print(1/3)    #0.3333333333333333

**示例2:取余**

print(7%3)    #1
print(9%3)    #0

**示例3:乘方运算既可以整数次方也可以是小数次方**

print(2**2)    #整数次方是乘方
print(2**0.5)    #小数次方是开方

**示例4:取整除法**

print(7//2)    #3
print(-7//2)    #-4

8.关系运算符

**示例1:python中直接使用==和!=来比较字符串内容**

print('hello'=='Hello')    #False
print('hello'!='Hello')    #True

**示例2:python中比较运算符可连用**

bb=0.1+0.2
cc=0.3
print(-0.000001<(bb-cc)<0.000001)    #True 误差之内

**示例3:比较运算符和与或非逻辑**

print(10<20 and 20<30)    #True
print(10<20 and 20>30)    #False
print(10>20 and 20<30)    #False

print(10>20 or 20<30)    #True
print(10<20 or 20>30)    #True
print(10>20 or 20>30)    #False

print(not 10<20)    #False
print(not 10>20)    #True

注意:短路求值,当左边的结果满足符号后就直接停止向后比较,直接出结果;

9.赋值运算符

**示例:多元赋值,使用多元赋值完成一步交换**

a,b=10,20
print(a,b)    #10 20
a,b=b,a
print(a,b)    #20 10

注意:

    1.python中不支持a++/++a(a–/–a)这种自增或自减操作,而支持a+=1/a=a+1(a-=1/a=a-1);

    2.python中字符串之间能够相加/整数和浮点数之间可以相加/整数和布尔值可以相加,但是没有意义;

    3.python中,一句语句结束后可以加;也可以不加;

10.条件语句

**示例1:普通判断**

choice=input("输入1or2:")
if choice=='1':
    print('输入的是1')
elif choice=='2':
    print('输入的是2')
else:
    print('非法输入')

choice1=input("输入3:")
if choice1=='3':
    print('输入的是3')
print('非法输入')

a=input("请输入一个奇数:")
a=int(a)
if a%2==0:
    print('不是奇数')
else:
    print('是奇数')

**示例2:嵌套判断**

choice2=input("输入4:")
choice3=input("输入5:")
if choice2=='4':
    if choice3=='5':
        print('输入的是5')
    else:
        print('输入的是4')
else:
    print('非法输入')

**示例3:使用pass空语句进行占位,否则破环python语法结构**

情况一:
b=int(input("请输入-1:"))
if b==-1:
    print('输入正确')
else:
#File "D:\Python环境\PythonProject\StudyText.py", line 203
#IndentationError: expected an indented block after 'else' statement on line 199

情况二:
b=int(input("请输入-1:"))
if b==-1:
    print('输入正确')
else:
    pass

11.while循环语句

**示例1:打印1~10的整数**

cnt=1
while cnt<=10:
    print(cnt) 
    cnt+=1

**示例2:计算1~100的和**

sum=0
cnt=1
while cnt<=100:
    sum+=cnt
    cnt+=1
print(sum)

**示例3:计算5的阶乘**

num=5
res=1
while num>0:
    res*=num
    num-=1
print(res)

**示例4:计算1!+2!+3!+4!+5!**

num=1
sum=0
while num<=5:
    res=1
    cnt=1
    while cnt<=num:
        res*=num
        cnt+=1
    num+=1
    sum+=res
print(sum)

12.for循环语句

**示例1:for循环的使用**

for i in range(1,11):
    print(i)    
#1 2 3 4 5 6 7 8 9 1O

**示例2:for循环中的步长**

for i in range(2,12,2):
    print(i)
#2 4 6 8 10

**示例3:for循环中的步长**

for i in range(10,0,-1):
    print(i)
#10 9 8 7 6 5 4 3 2 1

注意:

    1.python中的continue与break与其他语言中的用法相同;

    2.python中表示循环有两种方法,while和for;

13.函数

**示例1:函数普通调用**

def calcsum(start,end):
    sum=0
    for i in range(start,end+1):
        sum+=i
        i+=1
    #print(sum)
    return sum    #return语句并不是必须的,可以有可以没有
#calcsum(1,100)
ret=calcsum(200,300)
print(ret)

**示例2:python中,形参与实参之间只要求个数匹配,而不要求类型也匹配(动态类型) **

def test(a):
    print(a)
test(10)    
test('hello world')
test(True)

def Add(x,y):
    print(x+y)
Add(10,20)
Add(19.1,20.9)
Add('hello','world')

**示例3:python中的一个函数可以返回多个值**

def getpoint():
    x=10
    y=20
    z=30
    return x,y,z
a,b,c=getpoint() #多元赋值
print(a,b,c)    #10 20 30

#_,_,c=getpoint() 占位符_,最终只用c获取z
#注意变量的作用域,一个变量只在其作用域范围内生效,在作用域外部是不会生效的
x,y,z=getpoint()
print(x,y,z)    #10 20 30

**示例4:有局部用局部,没有局部找全局**

x=10 #全局变量

def func():
    x=20 #局部变量 没有global就当作一个新声明的局部变量
    print(f'函数内部{x}')
def func1():
    global x #声明全局变量,对该变量要进行修改
    x=30
    print(f'函数内部{x}')

func()
print(f'函数外部{x}')
func1()
print(f'函数外部{x}')

#函数内部20
#函数外部10
#函数内部30
#函数外部30

**示例5:函数链式调用**

#链式调用:一个函数的返回值是另一个函数的参数;
def Add(x,y):
    return x+y
def isOdd(num):
    if num%2==0:
        return True
    else:
        return False
print(isOdd(Add(10,10)))    #True

**示例6:函数嵌套调用**

def test4():
    num=1
    print("调用4成功!")
def test3():
    num=1
    test4()
    print("调用3成功!")
def test2():
    num=1
    test3()
    print("调用2成功!")
def test1():
    num=1
    test2()
    print("调用1成功!")
test1()
#每个变量虽然同名,但保存在各自的栈帧中属于不同的作用域,互相不影响;
#调用4成功!
#调用3成功!
#调用2成功!
#调用1成功!

**示例7:函数递归调用**

def factor(n):
    if n==1:
        return 1
    return n*factor(n-1)
ret=factor(5)
print(ret)

**示例8:函数形参的默认值**

def Add(x,y,debug): 
#def Add(x,y,debug=False): 默认缺省
    if debug:
        print(f"x:{x},y:{y}")     #x:1,y:2
        return -1
    else:
        return x+y
print(Add(1,2,True))    #-1 
print(Add(3,4,False))    #7

**示例9:函数的关键字参数**

def test(x,y):
    print(f"x={x}")
    print(f"y={y}")
test(x=20,y=10)
test(y=100,x=200) #使用关键字参数,可以不去管函数传参顺序
                    #关键字参数一般是搭配默认参数来使用的

14.列表

**示例1:列表的基本操作**

1.直接使用字面值来创建,[]就表示一个空的列表
a=[]
print(type(a))    #<class 'list'>

2.使用list来创建
b=list
print(type(b))    #<class 'list'>

3.可以在创建列表的时候,在[]中指定列表的初始值;元素之间使用,来分割
c=[1,2,3,4]
print(c)    #[1, 2, 3, 4]

4.可以在同一个列表中放不同类型的变量
d=[1,"hello",True,[1,2,3]]
print(d)     #[1, 'hello', True, [1, 2, 3]

5.使用下标对列表进行访问和修改
print(c[2])     #3
c[2]+=100
print(c[2])     #103

6.超出下标有效范围,就会出现访问异常
print(c[100])
#File "D:\Python环境\PythonProject\StudyText.py", line 389, in <module>
#    print(c[100])
#          ~^^^^^
#IndexError: list index out of range

7.可以使用内建函数len来获取列表长度,即元素个数
e=[1,2,3,4,5]
print(len(e))    #5

8.python中的下标可以写为负数,-1=len(a)-1
print(e[-1])    #5
print(len(e)-1)    #5

**示例2:列表的切片操作**

f=[1,2,3,4,5,6]
print(f[0:5]) #[1, 2, 3, 4, 5]
print(f[0:]) #[1, 2, 3, 4, 5, 6]
print(f[:5]) #[1, 2, 3, 4, 5]
print(f[:]) #[1, 2, 3, 4, 5, 6]
#切片+步长(与range相似)
print(f[::2]) #[1, 3, 5]
print(f[::3]) #[1, 4]
print(f[::-1]) #[6, 5, 4, 3, 2, 1]

**示例3:列表的遍历操作**

g=[1,2,3,4]
for elem in g:
    print(elem)    #1 2 3 4
        elem+=10    #对g无影响
    
for i in range(0,len(g)):
    print(g[i])    #1 2 3 4
    g[i]+=10    
    print(g[i])    #11 12 13 14

j=0
while j<len(g):
    print(g[j])    #11 12 13 14
    j+=1

**示例4:列表的插入操作**

1.使用append往链表表尾新增一个元素,搭配对象来使用的函数叫做方法
i=[1,2,3,4]
i.append(5)    
print(i)    #[1, 2, 3, 4, 5]
i.append('hello')    
print(i)    #[1, 2, 3, 4, 5, 'hello']
i.append('world')
print(i)    #[1, 2, 3, 4, 5, 'hello', 'world']

2.使用insert方法,往列表中任意位置插入新元素
j=[1,2,3,4]
j.insert(0,'hello')
print(j)    #['hello', 1, 2, 3, 4]
j.insert(len(j),'world')
print(j)    #['hello', 1, 2, 3, 4, 'world']

**示例5:列表的查找和删除**

1.使用in查找列表中的指定元素
k=[1,2,3,4]
res=1 in k
print(res)    #True
print(10 in k)    #False
print(1 not in k)    #False

2.使用index方法,来判定当前元素在列表中的位置,得到一个下标
m=[1,2,3,4]
print(m.index(2))    #1
print(m.index(3))    #2

3.使用pop删除列表中的最末尾元素/删除列表中任意的元素
n=[1,2,3,4]
n.pop()
print(n)    #1 2 3
n.pop(1)
print(n)    #1 3

4.使用remove方法按照值来进行删除
o=['a','b','c','d']
o.remove('a')
print(o)    #['b', 'c', 'd']
o.remove('d')
print(o)    #['b', 'c']

**示例6:列表的拼接**

1.使用+针对两个列表进行拼接
p=[1,3,5,7]
q=[2,4,6,8]
print(p+q)    #[1, 3, 5, 7, 2, 4, 6, 8]
print(p)    #[1,3,5,7]
print(q)    #[2,4,6,8]

2.使用extend来进行拼接,把后一个列表的内容拼接到前一个列表里面
p=[1,3,5,7]
q=[2,4,6,8]
p.extend(q) 
print(p)    #[1, 3, 5, 7, 2, 4, 6, 8]
print(q)    #[2,4,6,8]

3.#使用+=来进行拼接
p=[1,3,5,7]
q=[2,4,6,8]
p+=q
print(p)    #[1, 3, 5, 7, 2, 4, 6, 8]
print(q)    #[2,4,6,8]

15.元组

**示例:元组的基本操作**

1.创建元组
a=()
print(type(a))    #<class 'tuple'>
b=tuple()
print(type(b))    #<class 'tuple'>

2.元组中的元素是任意类型的
c=(1,2,'hello',True,[1,2,3])
print(c)    #(1, 2, 'hello', True,[1,2,3])

3.通过下标来访问元组中的元素
d=(1,2,3,4)
print(d[1])    #2
print(d[-1])   #4

4.通过切片来获取元组中的一个部分
e=(1,2,3,4,5)
print(e[1:3])    #(2, 3)

5.通过for循环等方式来进行便利
f=(1,2,3,4)
for elem in f:
    print(elem)    #1 2 3 4
for i in range(0,len(f)):
    print(f[i])    #1 2 3 4

6.使用in判断元素是否存在,使用index查找元素的下标
g=(1,2,3,4,5)
print(1 in g)    #True
print(g.index(3))    #2

7.使用+来拼接两个元组
h=(1,3,5,7)
i=(2,4,6,8)
print(h+i)    #(1, 3, 5, 7, 2, 4, 6, 8)

注意:元组只支持读操作,不能支持修改操作

16.字典

**示例:字典的基本操作**

1.创建字典
a={}
print(type(a))    #<class 'dict'>
b=dict()
print(type(b))    #<class 'dict'>

2.初始化字典
a={
    'id':1,
   'name':'zhangsan',
    100:'list'
}
print(a)    #{'id': 1, 'name': 'zhangsan', 100: 'list'}
#字典对于key是啥类型,有约束;对于value是啥类型,没约束;

3.使用in来判定某个key是否在字典中,in只是判定key是否存在,与value无关
print('id' in a)    #True
print('classid' in a)    #False
print('classid' not in a)    #True

4.使用[]来根据key获取value
print(a['id'])    #1
print(a['name'])    #zhangsan
print(a[100])    #list

注意:
#对于字典来说,使用in或者[]来获取value,都是非常高效的
#对于列表来说,使用in比较低效,而使用[]是比较高效的

5.字典新增,使用[]来进行
b={
    'id':1,
   'name':'zhangsan',
}
b['score']=90 #不存在->新增
print(b)    #{'id': 1, 'name': 'zhangsan', 'score': 90}
b['score']=100 #存在->修改
print(b)    #{'id': 1, 'name': 'zhangsan', 'score': 100}

6.使用pop方法,根据key来删除键值对
b.pop('id')
print(b)    #{'name': 'zhangsan', 'score': 100}

7.遍历字典
c={
    'id':1,
   'name':'zhangsan',
    'sex':0,
    'card':1006
}
for key in c:
    print(key,c[key])
#id 1
#name zhangsan
#sex 0
#card 1006

print(c.keys())    #使用x.keys()直接输出所有的key值
#dict_keys(['id', 'name', 'sex', 'card'])

print(c.values())    #使用x.values()直接输出所有的values值
#dict_values([1, 'zhangsan', 0, 1006])

print(c.items())    #使用x.items()直接输出所有的key,values键值对
#dict_items([('id', 1), ('name', 'zhangsan'), ('sex', 0), ('card', 1006)])

17.哈希

**示例:哈希展示**

#使用hash函数能够计算出一个变量的哈希值
#不可变对象,一般可以哈希
print(hash(0))
print(hash(3.14))
print(hash(True))
print(hash('hello'))
print(hash((1,2,3)))

#哈希函数不可以计算列表/字典
#可变对象,一般不可以哈希
#print(hash([1,2,3])) error
#print(hash({})) error

18.文件操作

**示例1:基本操作**

#使用open打开一个文件    #r读 w写 a加
f=open('D:/Python环境/PythonProject/text.txt','w')
print(type(f))    #<class '_io.TextIOWrapper'>
print(f)

#使用write写文件
f.write('hello world\n')
f=open('D:/Python环境/PythonProject/text.txt','a')
f.write('你好 世界')

#使用read读文件
f=open('D:/Python环境/PythonProject/text.txt','r')
res=f.read(12)
print(res)

#使用close关闭文件
f.close()

**示例2:按行读取文件**

f=open('D:/Python环境/PythonProject/text1.txt','r',encoding='utf8')
for line in f:
    print(f'{line}',end='')
f.close()
#床前明月光
#疑是地上霜
#举头望明月
#低头思故乡

f=open('D:/Python环境/PythonProject/text1.txt','r',encoding='utf8')
lines=f.readlines()
print(lines)
f.close()
#['床前明月光\n', '疑是地上霜\n', '举头望明月\n', '低头思故乡\n']

**示例3:上下文管理器**

def func():
    with open('D:/Python环境/PythonProject/text1.txt','r',encoding='utf8') as f:
        #代码
        #代码
        #代码
        if cond:
            return
        #代码
        #代码
        #代码
        if cond:
            return
        #代码
        #代码
        #代码
    f.close()

19.python中库的使用

 The Python Standard Library — Python 3.10.16 documentation


作者:张同学的IT技术日记

物联沃分享整理
物联沃-IOTWORD物联网 » Python 小白必看!万字示例代码块,零基础也能无痛入门

发表回复