and:布尔"与" - 如果 x 为 False,x and y 返回
False,否则它返回 y 的计算值。
or:布尔"或" - 如果 x 是 True,它返回 True,
否则它返回 y 的计算值。
not:布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。
例子:
stu = True
if not stu:
print(“你不是学生”)
else:
print(“是学生,可以进校园”)
or前面值不成立取后面值
a and b and c and d
如果 a 为 False 则后面所有的 and 均不再执行,直接返回 a 的值。
a or b or c or d
如果 a 为 True 则后面所有的 or 均不在执行。直接返回 a 的值。
a = 5
b = a>3 or 4
print(b)
True
and两边必须都同时成立,一个不成立都false,前面不成立后面就不用看了
a = 6
b = a > 7 and 5
print(b)
False
b =10
a=7 if b>10 else 8
print(a)
即:
b = 10
if b>10:
a=7
else:
a=8
print(a)
8
i=1
while i<5:
print(i,"<5")
i+=1
else:
print(i,“好像不成立了”)
i=1
while i<5:
print(i,"<5")
if i == 3:
break
i+=1
else:
print(i,“好像不成立了”)
break执行了后面的else就不执行了,break结束了这个循环
判断质数
num = int(input(“请输入一个数:”))
j = 2
while j
break
j += 1
if j == num:
print(num,“是质数”)
else:
print(num, “不是质数”)
代码改进:
num = int(input(“请输入一个数:”))
j = 2
while j
print(num,“不是质数”)
break
j += 1
else:
print(num,“是质数”)
num = int(input(“请输入一个数:”))
for i in range(2,num):
if num%i == 0:
print(“不是质数”)
break
else:
print(“质数”)
2到100之间的质数:for和while求法
b = []
for i in range(2,100):
for j in range(2, i):
if i % j == 0:
break
else:
b.append(i)
print(b)
a = []
i = 2
while i <100:
j=2
while j
break
j+=1
else:
a.append(i)
i+=1
print(a)
for i in range(5):
for j in range(i+1):
print("*",end="")
print()
x = 1
while x<=5:
y = 1
while y<=x:
print("",end="")
y+=1
print()
x+=1
九九乘法表while写法:
i = 1
while i <= 9:
j = 1
while j <=i:
print(j,"",i,"=",ij,end=" “)
j+=1
i+=1
print()
九九乘法表for写法:
for i in range(1,10):
for j in range(1,i+1):
print(j,”",i,"=",ij,end=" “)
print()
九九乘法表for、while写法:
for i in range(1,10):
j=1
while j <= i:
print(j,”",i,"=",ij,end=" “)
j+=1
print()
九九乘法表while、for写法:
i = 1
while i <= 9:
for j in range(1,i+1):
print(j,”",i,"=",ij,end=" “)
i+=1
print()
打印倒三角形的while、for写法:
i = 1
while i<=5:
j = 1
while j
j+=1
j=1
while j<=6-i:
print(”
j+=1
print()
i+=1
for i in range(5):
for j in range(i):
print(" “,end = “”)
for j in range(5-i):
print(”*", end="")
print()
打印矩形:while和for
for i in range(5):
for j in range(5):
if i == 0 or j == 0 or i == 4 or j == 4:
print("*",end="")
else:
print(" “,end=”")
print()
i = 1
while i <= 5:
j = 1
while j<=5:
if i == 1 or j == 1 or i == 5 or j == 5:
print("*",end="")
else:
print(" “,end=”")
j+=1
print()
i+=1