Program to Print Hello world in Python

# 1. A program to print Hello, world!  
print('Hello, World!')
Hello, World!

A Program to Find the Square Root of a Number

# 2. A Program to Find the Square Root of a Number

num = float(input('Enter a number: '))
sqrt = num**0.5
print('The square root of %0.2f is %0.2f'%(num,sqrt))
Enter a number: 100
The square root of 100.00 is 10.00

Program to Sum Two Numbers

# Program to add two numbers using + operator  
num1 = eval(input("enter number 1 "))
num2 = eval(input("enter number 2 "))
# Sum the two numbers
result = num1 + num2
# Display the result
print('The sum of {0} and {1} = {2}'.format(num1, num2, result))
enter number 1 12
enter number 2 21
The sum of 12 and 21 = 33

Program to Swap Two Variables

x = input('Enter x value: ')
y = input('Enter y value: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Enter x value: 12
Enter y value: 21
The value of x after swapping: 21
The value of y after swapping: 12

— Without using third variable

x =int(input('Enter x value: '))
y =int(input('Enter y value: '))

# use of basic arithmetic [+ & -] operator
x = x+y;
y = x-y;
x = x-y;
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Enter x value: 12
Enter y value: 21
The value of x after swapping: 21
The value of y after swapping: 12

— Swap Values using Arithmetic [*, /] Operators

x =int(input('Enter x value: '))
y =int(input('Enter y value: '))
# use of basic arithmetic operators
x = x*y;
y = x/y;
x = x/y;
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Enter x value: 12
Enter y value: 21
The value of x after swapping: 21.0
The value of y after swapping: 12.0

— Swap Values using Simple Constructor — tuple Pack / Unpack

x =input('Enter x value: ')
y =input('Enter y value: ')
# apply simple constructor below
x,y=y,x
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Enter x value: 12
Enter y value: 21
The value of x after swapping: 21
The value of y after swapping: 12

— Swap Values using Bitwise XOR operator

x =int(input('Enter x value: '))
y =int(input('Enter y value: '))
x =x^y
y =x^y
x =x^y
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Enter x value: 12
Enter y value: 21
The value of x after swapping: 21
The value of y after swapping: 12

Program to Convert Celsius to Fahrenheit

celsius =float(input("Enter a value in Celsius: "))
# calculate fahrenheit
fahrenheit =(celsius * 1.8) + 32
print('%0.1f° Celsius = %0.1f° Fahrenheit.'%(celsius,fahrenheit))
Enter a value in Celsius: 32
32.0° Celsius = 89.6° Fahrenheit.

Find ASCII Value of Character

cha=str(input('Enter any character: '))
print('ASCII value of {0} = {1}'.format(cha,ord(cha)))
Enter any character: A
ASCII value of A = 65

Program to Calculate the Area of a Triangle

Base =float(input('Enter the base value: '));
Height =float(input('Enter the height value: '));
Area = (Base * Height) / 2;
print('The area of the triangle is {} '.format(Area))
Enter the base value: 5
Enter the height value: 3
The area of the triangle is 7.5

— Calculate the area of triangle using sides of triangle

a =float(input('Enter first side: '))
b =float(input('Enter second side: '))
c =float(input('Enter third side: '))
s = (a + b + c) / 2
# Calculate the area
Area =(s*(s-a)*(s-b)*(s-c))**0.5
print('The area of the triangle is %0.2f' %Area)
Enter first side: 2
Enter second side: 3
Enter third side: 4
The area of the triangle is 2.90

Program to Convert Kilometers to Miles

km =float(input("Enter km value: "))
# conversion rate
rate =0.621371
miles =km*rate
print('%0.2f km is equal to %0.2f miles'%(km,miles))
Enter km value: 10
10.00 km is equal to 6.21 miles

Program to Convert Decimal to Binary and Hexadecimal

num_dec =int(input('Enter a number: '))
print('Binary equivalent of {0} = {1}'.format(num_dec,bin(num_dec)))
print('Hexadecimal equivalent of {0} = {1}'.format(num_dec,hex(num_dec)))
Enter a number: 10
Binary equivalent of 10 = 0b1010
Hexadecimal equivalent of 10 = 0xa

Program to Solve Quadratic Equation

import cmath
a = float(input('Enter a value: '))
b = float(input('Enter b value: '))
c = float(input('Enter c value: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
root1 = (-b-cmath.sqrt(d))/(2*a)
root2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution is: {0} + {1}'.format(root1,root2))
Enter a value: 2
Enter b value: 2
Enter c value: 2
The solution is: (-0.5-0.8660254037844386j) + (-0.5+0.8660254037844386j)

Program to Check if a Number is Odd or Even

num = int(input('Enter any number: '))
if (num % 2) == 0:
print('{0} is an Even Number'.format(num))
else:
print('{0} is an Odd Number'.format(num))
Enter any number: 1
1 is an Odd Number

Program to Check if a Number is Positive, Negative or Zero

num =float(input('Enter any number: '))
if num > 0:
print('This is a Positive number')
elif num == 0:
print('This is Zero')
else:
print('This is a Negative number')
Enter any number: -1
This is a Negative number

Program to Find the Largest Among Three Numbers

num1 =int(input('Enter first number: '))
num2 =int(input('Enter second number: '))
num3 =int(input('Enter third number: '))
if (num1 >= num2) and (num1 >= num3):
bigNum = num1
elif (num2 >= num1) and (num2 >= num3):
bigNum = num2
else:
bigNum = num3
print('The largest number = {0}'.format(bigNum))
Enter first number: 3
Enter second number: 5
Enter third number: 1
The largest number = 5

Program to Check Leap Year

year =int(input('Enter a year: '))
if (year % 400) == 0:
print('{0} is a leap year'.format(year))

elif year % 4==0 and year % 100 != 0 :
print('{0} is a leap year'.format(year))

else:
print('{0} is not a leap year'.format(year))
Enter a year: 2010
2010 is not a leap year

Program to Display the multiplication Table

num=int(input('Enter a number: '))
# Iterate 10 times from i (ie 1 to 10)
for i in range(1, 11):
print('{0} x {1} = {2}'.format(num,i,num*i))

Enter a number: 10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Program to Check Prime Number

num =int(input('Enter a number: '))
# prime numbers must be greater than 1
if num>1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print('{0} is not a prime number'.format(num))
break
else:
print('{0} is a prime number'.format(num))
Enter a number: 11
11 is a prime number

Program to Find the Factorial of a Number

num =int(input('Enter a number: '))
factorial=1
# check for negative, positive or zero
if num<0:
print('Error! Negative nunber is not accepted')
elif num==0:
print('Factorial of 0 = 1')
else:
for i in range(1,num + 1):
factorial = factorial*i
print('Factorial of {0} = {1}'.format(num,factorial))
Enter a number: 3
Factorial of 3 = 6

Program to Print the Fibonacci sequence

nt_num = int(input('Enter nth term:  '))
# first two terms
n1, n2 = 0, 1
count = 0
if nt_num <= 0:
print('Enter only positive number')
elif nt_num == 1:
print('Fibonacci sequence of {0} = {1}'.format(nt_num,n1))
else:
print('Fibonacci sequence:')
while count < nt_num:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Enter nth term:  10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Program to Find the Sum of Natural Numbers

num=int(input('Enter nth number: '))
if num < 0:
print('Enter only positive number')
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print('Sum = {0}'.format(sum))
Enter nth number: 10
Sum = 55

— Sum of Natural Numbers Using n(n+1)/2

num =int(input('Enter nth number: '))
if num >= 0:
sum = num*(num+1)/2
print('Sum = {0}'.format(sum))
else:
print('Enter only positive number')
Enter nth number: 10
Sum = 55.0

Program to Find List of Numbers Divisible by 4

— using filter method

nums = eval(input("Enter list of numbers in [] brackets "))
# using filter method

result = list(filter(lambda x: (x % 4 == 0), nums))
print(result)
Enter list of numbers in [] brackets [1,2,3,4,5,6,7,8]
[4, 8]

— using for loop and if condition

# using for loop and if condition
nums = eval(input("Enter list of numbers in [] brackets "))

for i in nums:
if i % 4 == 0:
print(i, end= " " )
Enter list of numbers in [] brackets [1,2,3,4,5,6,7,8]
4 8

using list comprehension


nums = eval(input("Enter list of numbers in [] brackets "))

L1 = list(i for i in nums if i % 4 == 0 )
print(L1)
Enter list of numbers in [] brackets [1,2,3,4,5,6,7,8]
[4, 8]

Program to Make a Simple Calculator

# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers
def subtract(x, y):
return x - y

# This function multiplies two numbers
def multiply(x, y):
return x * y

# This function divides two numbers
def divide(x, y):
return x / y

print("Select operation :: ")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
choice = input("Enter choice(1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

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))
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation.lower() == "no":
break
else:
print("Invalid Input")
Select operation  ::   
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter first number: 1
Enter second number: 2
1.0 + 2.0 = 3.0
Let's do next calculation? (yes/no): no

Program to Check Whether a String is Palindrome or No

str1 =input('Enter a string: ')
str2 = str1[::-1]
if str1 == str2:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')
Enter a string: abc
The string is not a palindrome.

— using for Loop

# using for Loop 
str1 =input('Enter a string: ')
l1 = len(str1)
for i in range(len(str1)//2):
if str1[i] != str1[l1 - i - 1]:
print('The string is not a palindrome.')
break
else:
print('The string is a palindrome.')
Enter a string: aba
The string is a palindrome.

— using reversed function

str =input('Enter a string: ')  
str =str.casefold()
rev_str =reversed(str)
if list(str) == list(rev_str):
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')

Program to Check Armstrong Number

num = int(input("Enter a number   "))
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print('{0} is an Armstrong number'.format(num))
else:
print('{0} is not an Armstrong number'.format(num))

Enter a number   371
371 is an Armstrong number

Print all Prime Numbers in a Range

min =int(input('Enter minimum range: '))
max =int(input('Enter maximum range: '))

if min > max :
min , max = max, min

for num in range(min, max + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num, end= " ")
Enter minimum range: 1
Enter maximum range: 20
2 3 5 7 11 13 17 19

Program to Find Armstrong Number in a Range

num_start =int(input('Enter start number: '))
num_end =int(input('Enter end number: '))
for num in range(num_start, num_end + 1):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)

--

--

Key computer Education

keykoders.wordpress.com Opens up the Mind Programming for Beginner | Coding Tutorial | Free Programs | Free Projects