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

Python loop structure uses while loop to realize sum factorization

編輯:Python

Functional requirements

Write a console application , Receive user input from the keyboard 5 The value of the number , And take this 5 Add the values and display them on the console .

Program analysis

1. Define loop variables count, And assign the initial value to the cyclic variable 1, It is used to count the number of data currently read .

2. Define the summation variable sum, Used to save the sum value after each accumulation , Because there is no data to accumulate at first , Therefore, the initial value is 1.

3. Use while loop , Read data from the keyboard in turn , And add the read data to the variable sum in .

4. When the loop variable count Less than or equal to 5 when , stay while The statement of the loop structure continues to execute , Until the cycle condition is not met .

The sample code

sum = 0
count = 1
while (count <= 5):
    num = float(input(" Please enter the first %d Data :" % count))
    sum += num
    count += 1
print(" The sum of five numbers is %.2f" % sum)

Running results

 

Functional requirements

Write a console application , Use while It's a loop 1 To 5 The product of the . The o 1 * 2 * 3 * 4 * 5 Value .

The sample code

sum = 1
count = 1
while count <= 5:
    sum *= count
    count += 1
print("1 * 2 * 3 * 4 * 5 = %d" % sum)

Running results

 


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