程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python loop structure uses the while loop to sum the squares of 1~n

編輯:Python

Functional requirements

Write a console application , Use while The cycle structure is solved in turn 1~5 And output the result .

Implementation steps

i = 0
while i < 5:
    i += 1
    print("%d The square value of is %d" % (i, i * i))
    # print("%d The square value of is %d" % (i, i ** 2))

Running results

Functional requirements

Write a console application , Use while Cyclic structure calculation 1~10 Sum of squares of , The o 12 + 22 + 32 + ... + 102 And display the output .

Program analysis

1. Defining variables sum Used to save the value of the sum of squares , The initial value is 0.

2. Define loop variables n, The value used to represent the current number squared .

3. utilize while Loop to find 1~10 Add the sum of the squares of to the variable sum in .

4. while The condition of the cycle is n Less than 10.

Implementation steps

sum, n = 0, 0
while n < 10:
    n += 1
    sum += n ** 2
print("1 ~ 10 The sum of squares is :%d" % sum)

Running results

Functional requirements

Write a console application , Use while Cyclic structure calculation 1~n Sum of squares of , The o 12 + 22 + 32 + ... + n2, Until the cumulative sum is greater than or equal to 10000 until , And will n The sum of squares of the value of shows the output .

Program analysis

1. Defining variables sum Used to save the value of the sum of squares , The initial value is 0.

2. Define loop variables n, The value used to represent the current number squared .

3. utilize while Loop to find 1~10 Add the sum of the squares of to the variable sum in .

4. while The condition of the cycle is that the sum of squares is less than or equal to 1000, namely sum <= 1000.

Implementation steps

sum, n = 0, 0
while sum < 10000:
    n += 1
    sum += n ** 2
print("1 ~ %d The sum of squares is :%d" % (n, sum))

Running results

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved