Python 第一节
一、循环while、如果语句 if …
无限循环:
import time
while 1 == 1:
print('ok',time.time())
1 使用while 循环输入 1 2 3 4 5 6 7 8 9 10:
n = 1
while n < 11:
if n == 7:
pass # 如果n=7,去掉
else:
print(n)
n = n + 1
1
2
3
4
5
6
8
9
10
- pass 不执行当前结果
2 求1-100所有数的和:
a = 1
b = 0
while a < 101:
b = b+a
a = a + 1
print(b)# b为总和,每次加1-100的数值:0+1=1,1+2=3,3+3=6......
5050
3 输出1-100内的所有奇数:
n1 = 1
while n1 < 101:
n_1 = n1 % 2# 求余数
if n_1 == 0:# 如果余数为零,那么去掉
pass
else:
print(n1)
n1 = n1+1
4 输出1-100内的所有偶数:
n2 = 1
while n2 < 101:
n_2 = n2 % 2# 求余数
if n_2 == 0:# 如果余数为零,那么去掉
print(n2)
else:
pass
n2 = n2+1
5 求1-2+3-4+5-6+7…100:
a1 = 1
b1 = 0
while a1 < 100:
c = a1 % 2
if c == 0:
b1 = b1 - a1
else:
b1 = b1 + a1
a1 = a1 + 1
print(b1)
50
6 用户输入,3次机会重试:
m = 0
while m < 3:
name = input('请输入您的用户名:')
m_ = input('请输入您的用户密码:')
if name == 'MOKE' and m_ == '123yyy':
print('欢迎进入python世界!')
else:
print('您的用户名或密码错误,请重新输入:')
m = m + 1
print('对不起,今日输入次数已用完,请明天再登陆!')
请输入您的用户名:1
请输入您的用户密码:1
您的用户名或密码错误,请重新输入:
请输入您的用户名:
二、运算符 (+ - * / )幂运算(**)求余数(%) 整除(//)
print(1+2)
print(3-2)
print(2*3)
print(4*2)
print(10**2)
print(11%4)
print(11//4)
3
1
6
8
100
3
2
三、 判断某个值是否在包含在某个值内
in 包含
not in 不包含
name = '123456'
if '1'in name:
print('ok')
else:
print('no')
print('________end____________')
if '1' not in name:
print('ok')
else:
print('no')
ok
end____
no
四、 布尔值:(真(True) 假(False))
v = 1 ==1
print(v)
v = 1 ==2
print(v)
True
False
五、 and(且),or(或)
user = 'alex'
pwd = '123'
m = user == 'alex' and pwd == '123' or 1 == 2 and pwd == '6789'
print(m)
True
计算机解析公式从前往后一步一步走
m = ((user == 'ale' and pwd == '123') or (1 == 2 and pwd == '6789'))
print(m)
False
加括号分优先级
执行顺序:
True or (True)
True and (继续走)
False or (继续走)
False and (False)
六、 赋值运算符
x = 0
x = x + 1 #等于x += 1
print(x)
x += 2
print(x)
1
3
比较运算符:
== < > <= >= !=
逻辑运算符:
and(与) or(或) not(非)
成员运算符:
in
not in
七、 数字:猎人
num = 123
v1 = num.bit_length()
print(v1)
# 字符串:女巫
name1 = 'wangbo'
name2 = 'Li Zhaohui'
v_1 = name1.upper()
v_2 = name2.upper()
print(v_1)
print(v_1)
7
WANGBO
WANGBO
各有各的功能:
数字:整形 int 123456
字符串:str ‘’ ""
列表:list
元组:tuple
字典:dict
布尔值:bool
- int 将字符串转换为数字
a1 = '123'
b1 = int(a1)
b1 = b1 +1000
print(b1)
1123
注:字符串内容为数字,否则转换失效。
a1 = '123'
print(type(a1),a1)
b1 = int(a1)
print(type(b1),b1)
<class ‘str’> 123
<class ‘int’> 123
type 可将内容格式展示出来,更加直观
二进制: .bit_length() 表示当前数字二进制位数
1 1
2 10
3 11
4 100
5 101
当前数字的二进制,至少用n位来表示
age = 10
r = age.bit_length()
print(r)
4
字符串功能:
ctrl + 鼠标左键点击打开功能
.capitalize() 首字母大写
test = 'alex'
# str
v = test.capitalize()
print(v)
Alex
.count() 去字符串中寻找,寻找子序列出现次数
test = 'alexalex'
v = test.count('ex')
print(v)
2