Python Program for Even/Odd and Sum of N Natural Numbers
Check if a Number is Even or Odd in Python
Given an integer input, the objective is to determine whether a number is even or odd using Python programming.
An even number is completely divisible by 2, whereas an odd number leaves a remainder of 1 when divided by 2.
Example:
Input: Num = -5
Output: The number is Negative
Methods to Check Even or Odd
- Method 1: Using Brute Force
- Method 2: Using Nested if-else Statements
- Method 3: Using the Ternary Operator
Sum of First N Natural Numbers (Python)
Natural numbers are a sequence of positive numbers starting from 1. The sum of the first N natural numbers can be calculated using different methods.
Method 1: Using for Loop (Python)
n = int(input("Kindly Insert an Integer Variable: ")) sum = 0 for i in range(1, n + 1): sum += i print("Sum of Natural Numbers =", sum)
Output:
Kindly Insert an Integer Variable: 3 Sum of Natural Numbers = 6
Method 2: Using Formula (Python)
n = int(input("Kindly Insert an Integer Variable: ")) sum = n * (n + 1) // 2 print("Sum of Natural Numbers =", sum)
Output:
Kindly Insert an Integer Variable: 3 Sum of Natural Numbers = 6
Method 3: Using Recursion (Python)
def getSum(n): if n == 0: return 0 return n + getSum(n - 1) n = int(input("Kindly Insert an Integer Variable: ")) print("Sum of Natural Numbers =", getSum(n))
Output:
Kindly Insert an Integer Variable: 3 Sum of Natural Numbers = 6