top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

Number Sum

In this blog, I will write about a simple but interesting program I wrote to calculate the sum of all the numbers within a given range.

I named the function `number_sum`. The function takes in a positive integer and calculates the sum of all the numbers within that range.


Here is a quick glance at the function.


def number_sum(num):
    '''
        A program that returns the sum of all the 
        numbers within a given range
    '''
    
    # implement a try except block to catch errors for 
      non integers
      
    try:
       
        if((num >= 1) & (type(num) == int)):
         
          numbers = [number for number in range(1, num + 1)]
          return sum(numbers)
        else:
          return 'Error: number provided should be 1 or greater'
     except:
       print("Only integers are allowed!") 
          

The function first checks if the provided number is an integer and also greater than or equal to 1. If that is the case, it uses list comprehension

to store all the numbers in that range in a list. It then uses the python sum method to calculate the sum of all the numbers in the list.


If the value provided is a boolean, less than 1, or float, it returns an error message saying you should provide a number greater than 1 and an integer type.


If the value provided is not a number, the except block will throw an error message saying only integers are allowed!



The complete code with examples can be found on GitHub here.




0 comments

Recent Posts

See All

COURSES, PROGRAMS & CERTIFICATIONS

 

Advanced Business Analytics Specialization

Applied Data Science with Python (University of Michigan)

Data Analyst Professional Certificate (IBM)

Data Science Professional Certificate (IBM)

Data Science Specialization (John Hopkins University)

Data Science with Python Certification Training 

Data Scientist Career Path

Data Scientist Nano Degree Program

Data Scientist Program

Deep Learning Specialization

Machine Learning Course (Andrew Ng @ Stanford)

Machine Learning, Data Science and Deep Learning

Machine Learning Specialization (University of Washington)

Master Python for Data Science

Mathematics for Machine Learning (Imperial College London)

Programming with Python

Python for Everybody Specialization (University of Michigan)

Python Machine Learning Certification Training

Reinforcement Learning Specialization (University of Alberta)

Join our mailing list

Data Insight participates in affiliate programs and may sometimes get a commission through purchases made through our links without any additional cost to our visitors.

bottom of page