目录
一.交换两种数的四种方法
num1 = int(input("请输入第一个整数:"))
num2 = int(input("请输入第二个整数:"))
print(f"交换前:num1 = {num1},num2 = {num2}")
#临时变量法
#temp = num1
#num1 = num2
#num2 = temp
#数学法
#num1 = num1 + num2
#num2 = num1 - num2
#num1 = num1 - num2
#python特有多值交换方式
num1,num2 = num2,num1
#异或法
#num1 = num1 ^ num2
#num2 = num1 ^ num2
#num1 = num1 ^ num2
print(f"交换后:num1 = {num1},num2 = {num2}")
二.which循环
1.利用which循环打印直角三角形
layer = int(input("请输入打印的层数:"))
index = 0
while index < layer:
j = 0
while j <= index:
print("*",end = "")
j += 1
print()
index += 1
2.利用which循环打印九九乘法表
i = 1
while i <= 9:
j = 1
while j <= i:
print(f"{j} x {i} = {j * i}",end = " ")
j += 1
print()
i += 1
三.for循环
1.直角三角形
layer = int(input("请输入打印层数:"))
for i in range(layer):
for j in range(2 * i + 1):
print("*",end = "")
print()
2.等腰三角形
layer = int(input("请输入打印层数:"))
#打印空格
for i in range(1,layer + 1):
for j in range(layer - i):
print(" ",end = "")
#打印*的个数
for j in range(2 * i - 1):
print("*",end = "")
print()
3.菱形
layer = int(input("请输入奇数行:"))
while layer % 2 == 0:
layer = int(input("请输入奇数行:"))
#上半部分
for i in range(0,layer // 2 + 1):
#打印空格
print(" " * (layer - i),end = "")
#打印*的个数
print("*" * (2 * i + 1))
#下半部分
for i in range(layer // 2,0,-1):
#打印空格
print(" " * (layer - i + 1),end = "")
#打印*的个数
print("*" * (2 * i - 1))
4.空心菱形
layer = int(input("请输入奇数行:"))
while layer % 2 == 0:
layer = int(input("请输入奇数行:"))
#上半部分
for i in range(0,layer // 2 + 2):
#打印空格
print(" " * (layer - i),end = "")
#打印*的个数
for j in range(2 * i + 1):
if j == 0 or j == 2 * i:
print("*",end = "")
else:
print(" ",end = "")
print()
#下半部分
for i in range(layer // 2,-1,-1):
#打印空格
print(" " * (layer - i ),end = "")
#打印*的个数
for j in range(2 * i + 1):
if j == 0 or j == 2 * i:
print("*",end = "")
else:
print(" ",end = "")
print()
5.带有对角线的空心菱形
layer = int(input("请输入奇数行:"))
while layer % 2 == 0:
layer = int(input("请输入奇数行:"))
#上半部分
for i in range(0,layer // 2 + 2):
#打印空格
print(" " * (layer - i),end = "")
#打印*的个数
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or j == i or i == layer // 2 + 1:
print("*",end = "")
else:
print(" ",end = "")
print()
#下半部分
for i in range(layer // 2,-1,-1):
#打印空格
print(" " * (layer - i ),end = "")
#打印*的个数
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or j == i:
print("*",end = "")
else:
print(" ",end = "")
print()
四.判断一个数是不是素数
prime = int(input("请输入一个整数,判断是否为素数:"))
flag = True
for i in range(2,prime):
if prime & i == 0:
flag = False
break
if flag:
print(f"{prime}是一个质数")
else:
print(f"{prime}是一个合数")