Python loop statement (while) (for) classic simple exercises

  1. Find the sum of all even numbers within 100
sum = 0#定义求和的数从0开始
for i in range(0,101,2):'''利用for循环语句定义i在0到100之间,由左
闭右开的原则,i可以取到0,但是取不到101,故i在0到100之间。再定义每两
个数之间间隔为2,即0,2,4,6······100,从而取到偶数'''
	sum += i#定义每个取到的数进行相加
print(sum)

operation result:
Insert image description here

  1. Find the sum of all odd numbers within 100
sum = 0
for x in range(1,101,2):'''与上题相符,从0开始该为从1开始,间隔还
是2,故取到奇数'''
	sum += x
print(sum)

operation result:
Insert image description here

3. Write an isosceles triangle
Example: *
       ******
     *********
   ************

n = int(input("请输入行数: "))
for i in range(1, n + 1):
    for k in range(0, abs(i - n)):
        print(" ", end="")
    for j in range(1, i + 1):#定义行数,行数为1到i
        if j <= i and i + j <= 2 * n:
            print("* ", end="")
    print()

operation result:
Insert image description here

Guess you like

Origin blog.csdn.net/Nirvana92/article/details/124154485