sum_between_numbers.py 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. #Program to find sum between 1 and certain number
  2. #Import sys module for verifying user input
  3. import sys
  4. #Ask for user input to enter a number
  5. userInput = input("Enter a number: ")
  6. #If user's input is of float type.....
  7. if isinstance(userInput, float) == True:
  8. #Exit program with the message "Decimals are not allowed. Only whole numbers are."
  9. sys.exit("Decimals are not allowed. Only whole numbers are.")
  10. #If error occurs when converting the input to int type, exit program with the message "Your input is not a number."
  11. try:
  12. userNumber = int(userInput)
  13. except:
  14. sys.exit("Your input is not a number.")
  15. #Create a variable named "userSum", and assign a value of 0
  16. userSum=0
  17. #Create for loop ranging from 1 to userNumber (variable declared above) + 1, and inside the for loop, ...
  18. for i in range(1,userNumber+1):
  19. #Keep on adding loop variable to "userSum"
  20. userSum += i
  21. #Display message showing the sum of numbers between 1 and "userInput"
  22. print("The sum of numbers from 1 to %s, is %d" %(userInput, userSum))