Home > Backend Development > Python Tutorial > How to find the sum of odd numbers from 1 to 100 in Python

How to find the sum of odd numbers from 1 to 100 in Python

PHPz
Release: 2020-09-27 11:56:33
Original
71745 people have browsed it

Python method to find the sum of odd numbers from 1 to 100: It can be implemented with a while loop. The variable n inside the loop continues to decrement until it becomes [-1]. The while condition is no longer satisfied and the loop exits. The code is [for i in range(0,100):if i%2==1:sum = i;].

How to find the sum of odd numbers from 1 to 100 in Python

Related learning recommendations: python tutorial

How to find the sum of odd numbers from 1 to 100 in python:

As long as the conditions are met, the loop will continue and exit the loop when the conditions are not met.

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)
Copy after login

We want to calculate the sum of all odd numbers within 100, which can be achieved with a while loop:

The variable n inside the loop continues to decrement until it becomes -1, and the while condition is no longer met. , the loop exits.

#100以内奇数的和(不包括100)
sum = 0
for i in range(0,100):
    if i%2==1:
        sum += i
print(sum)
Copy after login

The above is the detailed content of How to find the sum of odd numbers from 1 to 100 in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template