一:用户交互
与用户交互主要使用input,这里需要说明三点:
1:input会等待用户输入
2:会将输入的内容赋值给变量
3:input出的变量都是字符串类型(str)
例子1:注意,因为input输出的字符串,所以可以做拼接
name=input("你的名字:")
age=input("你的年龄:")
print("你叫"+name,"年龄是"+age+"岁")
二:if 循环
三:while 循环
示例1:计算 1-2+3.。。。99除了88意外所有数的和
分析:遇到奇数则相加,遇到偶数则相减,88不做运算
count =
sum=
while count < :
count +=
if count % == :
if count == :continue
sum -=count
else:
sum +=count
print(sum)
while else
用途: 当while循环不被break打断,正常完成循环的时候,会走else,如果被else打断,则不执行else
count = 0
while count <=5:
count +=1
if count == 3:break
print(count)
else:
print("循环正常执行")
count = 0
while count <=5:
count +=1
if count == 3:pass
print(count)
else:
print("循环正常执行")
四: 格式化输出
4.1 %s/d
格式化输出用到了format关键字和 %s %d
% 指占位符
s 指需要替换的字符串
d 指需要替换的数字
通过跟用户进行交互,对用户输入进行格式化输出
用法:在需要格式化的字符串后 空格%(与用户交互的变量,使用逗号分隔)
注意:严格按照占位符的位置,有几个占位符就传几个值,并且是按照顺序传
下面是示例
name = input("姓名:")
age = int(input("年龄:"))
height= int(input("身高:")) msg = '''
-------- Info of %s --------
Name: %s
Age: %d
Height: %d
''' %(name,name,age,height)
当我们输出得内容里有%,就是说%并不是占位符,而是一个普普通通的%的时候,就需要在之前的%前面再加一个%,前面的%相当于转义效果,后面的才是真正的%
name = input("姓名:")
age = int(input("年龄:"))
height = int(input("身高:")) msg = '''
-------- Info of %s ---------
姓名:%s
年龄:%d岁
身高:%dcm
满意度:%%80
''' %(name,name,age,height) print(msg)
例子1: 用户登录三次,且每次输错时显示剩余错误次数,(使用字符串格式化)
user_name = 'wangys'
user_passwd = '' count = 0
while count < 3:
name=input("请输入姓名:")
passwd = input("请输入密码:")
count +=1
if name == user_name and passwd==user_passwd:
print("Login Sucess")
break
else:
print("登录失败,您还剩余%s次登录机会" %(3-count))
4.2 format(推荐使用)
name = input("姓名:")
age = int(input("年龄:"))
height = int(input("身高:")) msg = '''
-------- Info of {name} ---------
姓名:{name}
年龄:{age}岁
身高:{height}cm
满意度:%%80
'''.format(name=name,age=age,height=height) print(msg)
五:逻辑运算
and : 且
or : 或
not : 非
优先级: ()> not > and > or
print(3>4 or 4<3 and 1==1)
print(2 >1 and 3 < 4 or 4 > 5 and 2 < 1)
print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8)
print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)
print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)
# int类型>>跟布尔值的转换
# 0 -----------False
# 非0 ----------True # 布尔值--------init
print(bool(True)) # 1
print(bool(False)) # 0
# x or y 若x为真 值为x
print(1 or 2)
print(2 or 1000)
print(0 or 100)