How to find integers within 100 by using while in python
This article mainly introduces how python uses while to find integers within 100. the article is very detailed and has a certain reference value. Interested friends must read it!
The sum of 1, 1 to 100
Define two variables I and sum, the initial value is 1, the value of I increases by 1 at a time, and after taking 100, the program ends, and the value of sum is equal to the value of itself plus I. So I is taken from 2 to 100 and is added to sum every time.
#! / usr/bin/env python#-*- coding:utf-8-*-i=1sum=1while True: the sum of even numbers in breakprint (sum) 2, 1 to 100
Method 1: same as above, except that the initial value of iMagol sum is 0 and the value of I increases by 2 each time, and the program ends after taking 100.
#! / usr/bin/env python#-*- coding:utf-8-*-i=0sum=0while True: breakprint (sum)
Method 2: by taking the remainder function%, let num%2, if equal to 0, be an even number, sum=sum+num
#! / usr/bin/env python#-*-coding:utf-8-*-# Python Learning Exchange Group: 778463939num=0sum=0while True: num+=1 if num%2==0: sum=sum+num if num==100: breakprint ("Task finishedship the sum of even numbers from 1 to 100is:" + str (sum))
Little knowledge: the equal sign is =, which can no longer be written as num%2=0.
3. Odd sum from 1 to 100
Method 1: same as above, except that the initial value of iMagol sum is 1 and the value of I increases by 2 at a time. Here, we should pay special attention to the end of the program after taking the value of I to 99, otherwise the program will end.
#! / usr/bin/env python#-*- coding:utf-8-*-i=int (1) sum=int (1) while True: iTunes 2 sum=sum+i if iTunes 99: breakprint (sum)
Method 2: by taking the remainder function%, let num%2, if equal to 1, be odd, sum=sum+num
#! / usr/bin/env python#-*-coding:utf-8-*-num=0sum=0while True: num+=1 if num%2==1: sum=sum+num if num==100: breakprint ("Task finding the sum of odd numbers from 1 to 100is:" + str (sum)) these are all the contents of the article "how python uses while to find integers within 100". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!