while 循环
# 简单理解为循环版的if语句
i = 0
while i < 10:
print(i)
i += 1
1~100的立方和
i = 1
s = 0
while i <= 100:
s += i ** 3
# print(s)
i = i + 1
print(s)
斐波那契数列的第n项
n = int(input())
a = 1
b = 1
i = 3
while i <= n:
a, b = b, a + b
i = i + 1
print(b)
for 循环
(1):遍历字符串中的每个字符
for i in "Python":
print(i, end=' ')
print()
s = 'AcWing'
for i in s:
print(i, end=' ')
(2)和range函数搭配
# range(x): 返回0 ~ x-1 的数列
for i in range(10):
print(i, end=' ')
print()
# range(x,y): 返回 x x+1 x+2 ... y-2 y-1 的数列
for i in range(-2, 10):
print(i, end=' ')
print()
# range(x,y,z)
# z > 0: 返回 x ~ y-1 的公差为z的等差数列
for i in range(-2, 10, 2):
print(i, end=' ')
print()
# z < 0: 返回 y+1 ~ x 的公差为z的等差数列
for i in range(9, -2, -1):
print(i, end=' ')
1~100 的立方和
s = 0
for i in range(1, 101):
s = s + i ** 3
print(s)
斐波那契第n项
a, b = 1, 1
n = int(input())
for i in range(1, n):
a, b = b, a + b
print(a)
break 和 continue
判断质数
n = int(input())
falg = True
if n == 1: falg = False
for i in range(2, n):
if n % i == 0:
falg = False
break
if falg:
print("Yes")
else:
print("No")
求 1 ~ 100 中所有偶数的和
S = 0
for i in range(1, 101):
if i % 2 !=0: continue
S += i
print(S)