# Write a program to find the sum of natural numbers - Python

Categories:
Viewed: 2 - Published at: a few seconds ago

### write a program to find the sum of natural numbers

``````num = int(input("Enter a number: "))

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
``````

### write a program to find LCM

``````def lcm(x, y):
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
``````

### write a program to find HCF

``````def hcf(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2))
``````

### write a program to convert decimal to binary, octal and hexadecimal

``````dec = int(input("Enter a decimal number: "))

print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
``````

### python program to find ascii value of a character

``````c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))
``````

### write a program to make a simple calculator

``````# define functions
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':

elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
``````

### write a program to sort words in alphabetic order

``````my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
``````

### write a program to print the elements of an array present on even position

``````arr = [1, 2, 3, 4, 5];

print("Elements of given array present on even position: ");

for i in range(1, len(arr), 2):
print(arr[i]);
``````