Python基础(6)------基本数据类型 运算符
num = 1
while num <= 100:
val = num % 2
if val == 1:
print(num)
num =num + 1
例2输出 1-100相加结果
num = 1
count = 0
while num <= 100:
count = count + num
num =num + 1
print(count)
例3输出 1-2+3-4+5-6….100的结果
num = 1
count = 0
while num <= 100:
val = num % 2
if val == 1:
count = count + num
else:
count = count - num
num = num + 1
print(count)
count += 1 等价于 count = count + 1
2.11.3逻辑运算符
and 与 or 或 not 非
数据类型转换
字符串转换数字 int(val)
数字转字符串 str(num)
转换bool类型只有 bool(数字0)和bool(字符串””)等于Flase,其他都是True
str(False)=”False” str(True)=”True” int(False)=0 int(True)=1
逻辑运算符的特殊情况(一般只出现于面试题)
1.or
value = 1 or 9
第一个值如果是转换成布尔值,如果是True,则value=第一个值
第一个值如果是转换成布尔值,如果是False,则value=第二个值
v1 = 0 or 1
v2 = 8 or 10
v3 = 0 or 9 or 8
结果:v1=1 v2=8 v3=9
2.and
第一个值如果是转换成布尔值,如果是True,则value=第二个值
第一个值如果是转换成布尔值,如果是False,则value=第一个值
如果有多个and条件,则从左到右依次进行上述流程
V1=1 and 9 #v1=9
V2=1 and 0 #v2=0
V3=0 and 1 #v3=0
V4=0 and "" #v4=0
V5=a and 0 and 9 #v5=0
优先级 not > and > or
V1= 1 and 9 or 0 and 6 #9 or 0 v1=9
2.11.4 in 和 not in
例4 判断字符串是否存在敏感词汇
while True:
content = input("请输入内容:")
if "ab" in content:
print("存在敏感词汇")
else:
print(content)
break
优先级 not 2 > 1 --> not True -->False
2.12 单位转换
2.13练习
1.
age = 18
new_age = age + 1
print(new_age)
#结果 19
2.
name = 'abc'
new_name = name + 'de'
print(new_name)
结果: abcde
3.
age = '666'
new_age = age + '555'
print(new_age)
结果:666555
4.
age = '666'
new_age = age + 555
print(new_age)
结果:报错 不同数据类型运算错误
5.
age = 18
new_age = age * 2
print(new_age)
结果:36
6.(特殊)
name = 'abc'
new_name = name *2
print(new_name)
结果: abcabc
7.
age = 18
value = age >=19
print(value)
结果:Flase
8.判断成绩
number = raw_input("请输入数字")
score = int(number)
if score > 100:
print("输入错误")
elif score >= 90:
print("优秀")
elif score >= 70:
print("良好")
elif score >= 60:
print("及格")
elif score > 0:
print("不及格")
else:
print("输入错误")
9.致电10086
message = """ 欢迎致电10086
1.话费查询
2.流量服务
3.业务办理
4.人工服务"""
print(message)
index = raw_input("请输入你要选择的业务")
index = int(index)
if index == 1:
print("话费查询")
elif index == 2:
print("流量服务")
elif index == 3:
content = """业务办理
1.修改密码
2.更改套餐
3.停机 """
print(content)
value = raw_input("请输入要办理的业务")
value = int(value)
if value == 1:
print("修改密码")
elif value == 2:
print("更改套餐")
elif value == 3:
print("停机")
else:
print("输入错误")
elif index == 4:
print("人工服务")
else:
print("输入错误")
10.尝试三次登陆
#用户尝试三次登录
count = 1
while count <= 3:
col = 3 - count
user = input("请输入用户名:")
passwd = input("请输入密码:")
if user == 'zhm' and passwd == '123456':
print("登陆成功")
else:
print("登陆失败,还有",col,"次机会")
if count == 3:
break
count += 1
#是否退出功能
choice = input('请输入是否继续(Y/N):')
if choice == 'N':
break
elif choice == 'Y':
break
或
choice = input('请输入是否继续(Y/N):')
if choice == 'N':
break
elif choice == 'Y':
count = 1
continue
else:
print('输入错误')
break
写法2
count = 2
while count >= 0:
user = input("请输入用户名:")
passwd = input("请输入密码:")
if user == 'zhm' and passwd == '123456':
print("登陆成功")
break
temp = "用户名或密码输入错误,剩余%s次机会。"%(count)
print(temp)
count -= 1
else:
print(“三次机会用完”)