如果循环次数已经确定, for循环
"""
eg05 - 循环结构 --> for-in循环
Author: mimo_yy
Date: 2024/5/15
"""
# 如果循环次数已经确定 for循环
for i in range(100): # 产生0到100范围的整数,从0开始取数,100取不到
print(i, 'hello world!')
print(i, 'bye~')
for i in range(1, 101): # 产生1到101范围的整数,从1开始取数,101取不到
print(i, 'hello world!')
print(i, 'bye~') # i是循环变量,所以最好不要在里面出现
for i in range(1, 101, 2): # 产生1到100范围的奇数,步长为2,从1开始取数,100取不到:1,3,5...
print(i, 'hello world!')
print(i, 'bye~')
for i in range(100, 0, -2): # 产生1到101范围的偶数,从100开始取数,步长-2,0取不到:100,98...
print(i, 'hello world!')
print(i, 'bye~') # i是循环变量,所以最好不要在里面出现
print('wow!') # i取值为100
"""
eg06 - 实现0-100的求和
Author: mimo_yy
Date: 2024/5/15
"""
# 实现0-100的求和
total = 0
for i in range(1, 101):
total = total + i
# total += i
print(total)
# 实现0-100的奇数求和
total = 0
for i in range(1, 101, 2):
total = total + i
# total += i
print(total)
# 实现0-100的偶数求和
total = 0
for i in range(2, 101, 2):
total = total + i
# total += i
print(total)
# 实现0-100的偶数求和
total = 0
for i in range(1, 101):
if i % 2 == 0: # 判断是偶数 i%2 != 0 判断是奇数
total = total + i
# total += i
else:
pass # 空语句
print(total)
total = sum(range(1, 101))
"""
eg07 - 求1-100之间3或5的倍数的和
Author: mimo_yy
Date: 2024/5/15
"""
total = 0
for i in range(1, 101):
if i % 3 == 0 or i % 5 == 0:
total += i
else:
pass
print(total)
"""
eg08 - 输出1-N以及他们对应的平方/立方/N的N次方
1 1 1 1
2 4 8 4
3 9 27 27
4 16 64 256
Author: mimo_yy
Date: 2024/5/15
"""
#
ping = 0
li = 0
N = 0
for n in range(1, 5):
ping = n ** 2
li = n ** 3
N = n ** n
print(n, end=' ')
print(ping, end=' ')
print(li, end=' ')
print(N)
#
print('N'.ljust(10), end='') # .ljust左对齐文本,包含‘N’在内的总字符长度为10
print('N^2'.ljust(10), end='')
print('N^3'.ljust(10))
for i in range(1,11):
print(f'{i:<10d}{i**2:<10d}{i**3:<10d}')
# .rjust左右对齐文本,包含‘N’在内的总字符长度为10
# .center中心对齐
"""
eg09 - 输入一个非负整数N,计算N!
N! = N * (N-1)*(N-2)*...* 2 * 1
Author: mimo_yy
Date: 2024/5/15
"""
#
n = int(input('n= '))
total = 1
for i in range(n, 0, -1):
total *= i
print(f'{n}! = {total}')
#
n = int(input('n= '))
total = 1
for i in range(2, n + 1):
total *= i
print(f'{n}! = {total}')
"""
eg10 - 输入两个正整数,找出他们的最大公约数
bug --> 第一次出现程序bug是因为一只蛾子飞到晶体管,导致出现问题;所以之后用bug表示问题/故障/缺陷
debug -->解决bug(调试)
Author: mimo_yy
Date: 2024/5/15
"""
#
x = int(input('x= '))
y = int(input('y= '))
for i in range(x, 0, -1): # 从x到1,从大到小
if x % i == 0 and y % i == 0: # x能被i整除,y也能被i整除
print(i)
break
#欧几里得算法(辗转相除法),执行效率非常高
x = int(input('x= '))
y = int(input('y= '))
while y % x != 0:
x, y = y % x, x
# x-->y
# y%x -->x
# temp = y
# y = x
# x = temp % x
print(x)