01. python 基础语法
python基础语法
1. else语句
"""
if else
#循环结束之后,没有遇到break,则执行else。遇到break则不再执行
while else
for else
"""
1.1 while ... else...
s = 0
while s < 3:
s += 1
pwd = input("请输入密码:\n")
if pwd == "8888":
print('输入密码正确!')
break
else:
print('输入密码错误')
else:
print('三次密码都输入错误')
1.2 if ... else...
for item in range(3):
pwd = input("请输入密码:\n")
if pwd == "8888":
print('输入密码正确!')
break
else:
print('输入密码错误')
else:
print('三次密码都输入错误')
2. 内置还是range
"""
range(stop)
range(start,stop)
range(start,stop,step) #开始,结束,步长
"""
for i in range(5): #0~4
print(i)
for x in range(6,9): #6~8
print(x)
for y in range(10,40,5):
print(y)
3. 分支结构
"""
单分支 if
双分支 if...else
多分支 if elif elif else
分支嵌套 if嵌套
"""
4. 循环结构
4.1 循环
"""
while:
for ... in ...;
"""
"""
break 结束整个循环,后面循环语句不再执行,如果是多重循环,跳出最break所在循环
continue 结束这次循环,后面循环语句继续执行
"""
4.2 嵌套循环
#输出一个四行三列的矩形
for i in range(4):
for j in range(3):
print("*", end='\t') #不换行输出
print('\n') #换行
5. 条件表达式
注意:int型不可以于str型进行拼接
num_a = int(input('请输入一个数字:\n'))
num_b = int(input('请输入一个数字:\n'))
print('使用条件表达式进行比较两个数')
#int型不可以于str型进行拼接
#True输出前面,False输出后面
print(str(num_a)+'大于'+str(num_b) if num_a>num_b else str(num_a)+'小于' +str(num_b))
6. 转义字符
show code
print('hello world\n !') #换行
print('hello \t world!') #\t一个制表位 四个字符的位置(可能不是四个)
print('hello\tworld!') #三个字符,因为算上了o字符,一共四个
print('hello\r world') #\r 回车 world将hello进行覆盖
print('hello\bworld\n') #回退一个空格
print('http:\\www.baidu.ocm') #/转义字符
print('http:\www.baidu.ocm')
print('http:\\\\www.baidu.ocm\n')
# print('同学们说:'老师好!'')
print('同学们说:\'老师好!\'\n') #将需要转义的字符前加上 \
#原字符,不希望 \ 在字符串中起作用。 在字符串之前加上r或者R
print(r'hello\nworld!')
#注意,最后一个字符不可以为\
# print(r'hello\nworld\')
print(r'hello\nworld\\')
7. 数据类型&运算符
7.1 数据类型
show code
"""
整数
十进制
二进制 0b开头
八进制 0o开头
十六进制 0x开头
"""
#整型 int 整数,负数,0
#浮点型 float
"""
浮点数存储不精确,计算是可能出错
需要导入模块
"""
x = 1.1
y = 2.2
print(x+y) #3.3000000000000003 可能出错
from decimal import Decimal
print(Decimal('1.1')+Decimal('2.2'))
#布尔型 bool True(1),False(0)
s = True
print(type(s))
print(s+1) #bool型可当作整型计算
#字符串型 “字符”
7.2 运算符



show code
#算数运算符 + - * / //(整除) %(取模) **(幂运算)
#除 一正一负向下取正
print(9 % -4) # 商-3 余数=被除数-除数*商
print(-9 % 4) #
#赋值运算符 = += -= *= /= //= %=
a, b, c = 20, 30, 40
print(a, b, c)
#比较运算符 == != >= <= > < 结果是true,false
#布尔运算符
"""
and (两真为真,一假则假)
or (一真则真)
not (取反)
"""
f = True
print(not f)
#in 与 not in (在与不在)
#位运算和优先级
"""
位于& : 都真则真
位于| : 都假才假
左移位运算符<< : 高位溢出舍弃,低位补0
右移位运算符 >>: 低位溢出舍弃,高位补0 #二进制算
"""
print(4&8)
print(4|8)
print(4<<1)
print(4>>2)
8. 提供学习链接(转载)
再坚持一下下,会越来越优秀

浙公网安备 33010602011771号