Python code to print sum of first 100 Natural Numbers
Python code implementation without user-defined functions & classes
Code:
sum = 0
for i in range(1, 101):
sum = sum + i
print(sum)
Output:
5050
Python Code Editor Online - Click to Expand
Python code implementation using the function
In this code, we will print the sum of the first 100 Natural Numbers using the function.
Code:
def sum_100_natural_numbers():
sum = 0
for i in range(1, 101):
sum = sum + i
return sum
print(sum_100_natural_numbers())
Output:
5050
Python Code Editor Online - Click to Expand
Python code implementation using Classes
In this code, we will implement a class that contains function print the sum of the first 100 Natural Numbers. We will create an object and will call the function using object.function(), that will print the desired result.
Code:
class Natural_number_class(object):
def sum_100_natural_numbers(self):
sum = 0
for i in range(1, 101):
sum = sum + i
return sum
#Create an Object
object_sum = Natural_number_class()
print(object_sum.sum_100_natural_numbers())
Output:
5050
Python Code Editor Online - Click to Expand
Enjoy Python Code By Pythonbaba 🙂