Python基础整理大全——01

学习内容

1、 变量、运算符、变量类型

1.1变量


1.1.1 注释:

#、‘’‘ ’‘’
#这是一个注释
'''print("Hello World!")'''

1.1.2运算符

  • *1.1.2 :算术运算符(+、-、、/、//、%)
 '''
在这里呢,玄宝发现算术运算符就包括了常见的四则运算
+、-、*、\、(幂)
但是有几个特殊符号需要注意:
整除://(表示取整的意思)
取余:%(表示取余数)
实际用法跟数学里面常用的无异
'''
#加法
print(1+2)
#减法
print(5-2)
#乘法
print(2*3)
#除法
print(6/2)
#整除
print(4//2)
print(5//2)
#幂运算
print(2**3)
#取余
print(3%4)
实验结果如下:
3
3
6
3.0
2
2
8
3
  • *1.1.3:*比较运算符(>、<、=、>=、<=、!=)
    ‘’‘
    跟数学里面的大于/等于/小于/不等于用法完全一致(不过经过玄宝的实验与学习,发现该运算最后返回的是一个布尔值类型的值)在这里,玄宝的理解是只需要注意不等于的写法’!='即可至于返回的True/False,可对比数学里面的1/0(0表False 1True)
    注:实践出真理!

    ‘’’
print(1>2)
print(2>1)
print(2>=1)
print(1<=2)
print(1!=2)
print(1\==True)
print(0\==False)
实验结果如下:
False
True
True
True
True
True
True
  • *1.1.4:*逻辑运算符(and、or、!)
    ‘’’
    逻辑运算符:and/or/!
    (对比高中物理里的与、或、非进行理解)
    A and B:都为真才是真
    A or B:有一个为真即为真
    !:表否定(比较运算符里面已经见过了 ‘!=’:不等于)

    ‘’’
print(1 \== 1 and 1 == True)
print(0 \== 1 or 1 == 1)
print(1 != 0)
实验结果如下:
True
True
True
  1. 1.5 位运算符(~、>>、<<、|、&、^)
'''
操作符	名称	示例
~	按位取反	~4
&	按位与	4 & 5
`	`	按位或
^	按位异或	4 ^ 5
<<	左移	4 << 2
>>	右移	4 >> 
'''
print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

0b100
0b101
-0b101 -5
0b100 4
0b101 5
0b1 1
0b10000 16
0b1 1

这对于我学习python这门语言工具来讲,仅仅只是开始!
至于结束,我想应该不会有吧…

‘’’

  1. 1.6 print函数(打印函数)
#默认参数有end/file/seq...
m = 'I love you!'
w = 'I love every beautiful girl!'
f = 'I love every beautiful girl in white skirt that have enormous knowledge!'
print(m,w,f)
tp = (m,w,f)
for i in tp:
    print(i, end="\n")

I love you! I love every beautiful girl! I love every beautiful girl in white skirt that have enormous knowledge!
I love you!
I love every beautiful girl!
I love every beautiful girl in white skirt that have enormous knowledge!
  1. 1.7 变量与赋值
'''
变量使用之前需要对变量进行赋值,
变量名可以是由数字/字母/下划线组成,数字不能开头!
'''
a = 'Whatever is worth doing is worth doing well!'
print(a)
b = 'XuanBao used to saying: '
print(b)
print(b + a)

Whatever is worth doing is worth doing well!
XuanBao used to saying: 
XuanBao used to saying: Whatever is worth doing is worth doing well!
  1. 1.8 数据类型与转换
'''
数据类型:
    基本数据类型:int/float/double/
    序列类型:列表(list)/元组(tuple)/字符串(str)
    映射类型:字典(dict)
    集合类型:集合(set)
    布尔类型:bool
数据类型判断:
    type(变量) 返回变量类型
    isinstance(变量,变量类型) 返回布尔值
查看数据类型的内置方法:
    dir(数据类型)
强制数据类型转换:
    数据类型(原数据类型)
注:元组tuple的创建如果不放值,那么一定要传入一个’,‘
'''
hyj = 'I love you!'
print(type(hyj))
print(isinstance(hyj,str))
hyj_01 = int(100.9)
print(type(hyj_01))
print(isinstance(hyj_01,float))
print(isinstance(hyj_01,int))
print(dir(str))

<class 'str'>
True
<class 'int'>
False
True
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

2、 掌握条件语句


***条件语句主要有我们比较常见的if-else类型、if-elif类型、包括一个检测关键字assert(当这个关键词后边的条件为 False 时,程序自动崩溃并抛出`AssertionError`的异常。个人感觉在开发里面十分有用!专业术语为断言)***
#简易版猜字游戏
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
    print("你太了解小姐姐的心思了!")
    print("哼,猜对也没有奖励!")
else:
    print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")

猜一猜小姐姐想的是哪个数字?666
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!

#if判断的嵌套
hi = 6
if hi > 2:
    if hi > 7:
        print('好棒!好棒!')
else:
    print('切~')

# 无输出

```python
if expression1:
    expr1_true_suite
elif expression2:
    expr2_true_suite
    .
    .
elif expressionN:
    exprN_true_suite
else:
    expr_false_suite
#assert的实际使用
assert 3 > 7

# AssertionError

3、 掌握循环语句


循环在python里面主要是以while循环跟for循环为代表的,while循环里面也有while-else的判断语句,其中跳出此循环会用到关键字‘break’,而跳出本次循环开启下一次循环会用到’contunie’;还有我们的range函数生成index为0打头的列表,enumerate为代表的循环过滤、pass占位从而使得程序正常进行、各种推导式等等也都十分常用!

#while循环
count = 0
while count < 3:
    temp = input("猜一猜小姐姐想的是哪个数字?")
    guess = int(temp)
    if guess > 8:
        print("大了,大了")
    else:
        if guess == 8:
            print("你太了解小姐姐的心思了!")
            print("哼,猜对也没有奖励!")
            count = 3
        else:
            print("小了,小了")
    count = count + 1
print("游戏结束,不玩儿啦!")

猜一猜小姐姐想的是哪个数字?
8你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!

#while-else
count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = count + 1
else:
    print("%d is not less than 5" % count)
    
0 is  less than 5
1 is  less than 5
2 is  less than 5
3 is  less than 5
4 is  less than 5
5 is not less than 5

#for循环以及for-else循环的应用
for i in 'ILoveLSGO':
    print(i, end=' ')  # 不换行输出

 I L o v e L S G O

for num in range(10, 20):  # 迭代 10 到 20 之间的数字    
for i in range(2, num):  # 根据因子迭代        
if num % i == 0:  # 确定第一个因子            
j = num / i  # 计算第二个因子            
print('%d 等于 %d * %d' % (num, i, j))            
break  # 跳出当前循环    
else:  # 循环的 else 部分        
print(num, '是一个质数')# 10 等于 2 * 5# 11 是一个质数

12 等于 2 * 6# 13 是一个质数
14 等于 2 * 7# 15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数

#range函数的使用
for i in range(2, 9):  # 不包含9
    print(i)

2
3
4
5
6
7
8

#enumerate函数
languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
    print('I love', language)
print('Done!')

 I love Python
 I love R
 I love Matlab
 I love C++
 Done!

#pass占位
def a_func():
    pass

#列表、元组、字典、集合的推导式高效运用
#列表推导式
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)

[-8, -4, 0, 4, 8]

#元组推导式
a = (x for x in range(10))
print(a)

<generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

#字典推导式
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)

{0: True, 3: False, 6: True, 9: False}

#集合推导式
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)

{1, 2, 3, 4, 5, 6}


4、异常处理


官方解释:异常就是运行期检测到的错误。计算机语言针对可能出现的错误定义了异常类型,某种错误引发对应的异常时,异常处理程序将被启动,从而恢复程序的正常运行。(个人见解:异常处理就是运行时捕捉异常并按自己想的方式去显示它甚至解决它)

常见的异常处理语句有:try-except/try-except-else/try-except-finally(其中else表示try中的代码块正常所以才会去执行else中的代码块;而finally中无论如何,最后都会执行该语句) 还有我们的raise抛出指定异常

#try-except使用
try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError:
    print('打开文件出错')

打开文件出错

#try-except-else使用
try:
    fh = open("testfile.txt", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print("Error: 没有找到文件或读取文件失败")
else:
    print("内容写入文件成功")
    fh.close()

内容写入文件成功

#try-except-finally使用
def divide(x, y):
    try:
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        print("executing finally clause")


divide(2, 1)
result is 2.0
executing finally clause

divide(2, 0)
division by zero!
executing finally clause

divide("2", "1")
executing finally clause
TypeError: unsupported operand type(s) for /: 'str' and 'str'

#raise抛出指定异常(目前并不懂其使用价值)
try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    
An exception flew by!

学习时间

1、2020年08月27日晚九点到十点半进行阅读学习
2、2020年08月28日进行实际操作与博客撰写
r style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

学习产出与总结

1、CSDN博客一篇
2、python基础框架脑图逐步搭建
3、对自身基础知识体系的梳理与完善

注:学习网址:https://tianchi.aliyun.com/specials/promotion/aicamppython

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alexander plus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值