Day03 Python基础
课程目标:掌握Python基础中的必备语法知识
课程概要:
- 循环语句
- 字符串格式化
- 运算符
1. 循环语句
- while循环
- for循环(后期)
while 条件:
...
...
1.1 循环语句基本使用
示例1:
print("开始")
num = 1
while num < 5:
print("我是一名程序员")
num = num + 1
print("结束")
1.1练习题
实现一个交互系统,使得用户输入一个数字n,反馈n次我爱我的祖国。
1.2 综合小案例
请实现一个用户登录系统,如果密码错误着反复提示让用户重新输入,知道输入正确为止。
1.3 break
break,用于在while循坏中帮你终止循环。
print("开始")
while True:
user = input("请输入用户名:")
pwd = input("请输入密码:")
if user == "maxiaoyuan" and pwd == "mxy011115":
print("登录成功!")
break
else:
print("用户密码输入错误!")
print("系统结束")
1.4 continue
用于结束本次循环,开始下一次循环。
print("开始")
i = 1
while True:
if i == 7:
i = i-1
continue
print(i)
i= i+1
if i==101:
break
print("结束")
1.5 while else
while 条件:
代码
else:
代码
num = 1
while num <5:
print(num)
num = num +1
else:
print(666)
2. 字符串格式化
2.1 %格式化
2.1.1 基本格式化操作
name = "maxiaoyuan"
age = 18
text = "我叫%s,今年%d岁"%(name,age)
2.1.2 百分比
text = "%s,离成功只剩90%%了" %"各位"
2.2 format格式化(推荐)
text = "我叫{0},今年{1}岁".format("maxiaoyuan",18)
2.3 f格式化
name = "马小远"
text = f"我叫{name}"
3. 运算符
运算的优先级:
算术运算符高于比较运算符高于逻辑(not>and>or)
算术运算符:
a=10
b=20
a+b=30
a-b=-10
20%10=0 #取余数
20//10=2 #整除
比较运算符:
a=10
b=20
a == b
a != b
a <> b#判断两个值是否不相等(python3中不支持)
赋值运算符:
a=10
c+=a#c=a+c
成员运算:
a=2
b=5
c=(1,2,3,4)
a in c
b not in c
逻辑运算:
a=10
b=20
a=10 and b=20
a<10 or b=20
not(a=b)
3.1 练习题
and:前面是true,取决于后面的值,否则相反
or:前面是true,取决于前面的值,否则相反
v1 = 1 or 2
v2 = -1 or 3
v3 = -1 or 0
v4 = 0 or 100
v5 = "" or 10
v6 = "maxiaoyuan" or ""
print(v1,v2,v3,v4,v5)
Day03
-
判断下列逻辑语句的True,False
1>1 or 3<4 or 4>5 and 2>1 and 9>8 or 7<6 not 2>1 and 3<4 or 4>5 and 2>1 and 9>8 or 7<6
-
求出下列逻辑语句的值
8 or 3 and 4 or 2 and 0 or 9 and 7 0 or 2 and 3 and 4 or 6 and 0 or 3
-
写出下列结果
6 or 2>1 3 or 2>1 0 or 5<4 5<4 or 3 2>1 or 6 3 and 2>1 0 and 3>1 2>1 and 3 3>1 and 0 3>1 and 2 or 2<3 and 3 and 4 or 3>2
-
实现用户登录系统,并且支持连续三次输错后直接退出,并且在每次输错时显示剩余错误次数
-
猜年龄游戏:
要求:允许用户最多尝试3次,三次都没有成功的话则直接退出,如果猜对了打印"恭喜你"并退出。
-
猜年龄游戏升级版:
要求:允许用户尝试三次,如果失败了之后还想继续游戏,则回答Y,就可以继续猜三次,如果回答N,则直接退出,当猜对时直接退出。