1
Hello World
print("Hello World")
2
User Input
username = input("Enter username:")
3
Print Input Value
user_input = raw_input("Enter value:")
print("value is: " + user_input)
4
square root
# Python Program to calculate the square root
# Note: change this value for a different result
num = 8
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
5
adds two numbers
# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
6
area of triangle
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
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)
7
quadratic equation
# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
8
swap two variables
# Python program to swap two variables
x = 5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# 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))
9
generate a random number
# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(0,9))
10
calculate miles
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
11
convert temperature
# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
12
Positive or Negative
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
13
odd or even
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
14
leap year or not
# Python program to check if year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
15
largest number
# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
16
prime or not
# Program to check if a number is prime or not
num = 29
# To take input from the user
#num = int(input("Enter a number: "))
# define a flag variable
flag = False
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
17
prime numbers
# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
18
factorial of a number
# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
19
Multiplication table
# Multiplication table (from 1 to 10) in Python
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
20
Fibonacci sequence up
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
21
Armstrong number
# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
22
Armstrong interval
# Program to check Armstrong numbers in a certain interval
lower = 100
upper = 2000
for num in range(lower, upper + 1):
# order of number
order = len(str(num))
# initialize sum
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
23
natural numbers
# Sum of natural numbers up to num
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
24
anonymous function
# Display the powers of 2 using anonymous function
terms = 10
# Uncomment code below to take input from the user
# terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
print("The total terms are:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
25
powers of 2
# Display the powers of 2 using anonymous function
terms = 10
# Uncomment code below to take input from the user
# terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
print("The total terms are:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
26
anonymous function to filter
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
27
convert decimal
# Python program to convert decimal into other number systems
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
28
ASCII value
# Program to find the ASCII value of the given character
c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))
29
find H.C.F
# Python program to find H.C.F of two numbers
# define a function
def compute_hcf(x, y):
# choose the smaller number
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 = 54
num2 = 24
print("The H.C.F. is", compute_hcf(num1, num2))
30
find the L.C.M.
# Python Program to find the L.C.M. of two input number
def compute_lcm(x, y):
# choose the greater number
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 = 54
num2 = 24
print("The L.C.M. is", compute_lcm(num1, num2))
31
factors of a number
# Python Program to find the factors of a number
# This function computes the factor of the argument passed
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = 320
print_factors(num)
32
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:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
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))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
33
shuffle a card
# Python program to shuffle a deck of card
# importing modules
import itertools, random
# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
# shuffle the cards
random.shuffle(deck)
# draw five cards
print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])
34
calendar
# Program to display calendar of the given month and year
# importing calendar module
import calendar
yy = 2014 # year
mm = 11 # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
35
sum of natural
# Python program to find the sum of natural using recursive function
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
# change this value for a different result
num = 16
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
36
factorial using recursion
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
37
print binary
# Function to print binary number using recursion
def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2,end = '')
# decimal number
dec = 34
convertToBinary(dec)
print()
38
add two matrices
# Program to add two matrices using nested loop
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
39
transpose a matrix
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
40
multiply two matrices
# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
41
palindrome or not
# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
42
punctuation
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)
43
sort alphabetically
# Program to sort alphabetically the words form a string provided by the user
my_str = "Hello this Is an Example With cased letters"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)
44
mathematics operations
# Program to perform different set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
45
count the number of each vowels
# Program to count the number of each vowels
# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
46
mail merger
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt", 'r', encoding='utf-8') as names_file:
# open body.txt for reading
with open("body.txt", 'r', encoding='utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello " + name.strip() + "\n" + body
# write the mails to individual files
with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file:
mail_file.write(mail)
47
jpeg image file
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
48
find the SHA-1 message digest of a file
# Python program to find the SHA-1 message digest of a file
# importing the hashlib module
import hashlib
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
# make a hash object
h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest
return h.hexdigest()
message = hash_file("track1.mp3")
print(message)
49
nested dictionary
#nested dictionary
from pathlib import Path
Path("/root/dirA/dirB").mkdir(parents=True, exist_ok=True)
50
Access Index of a List
#Python Program to Access Index of a List Using for Loop
my_list = [21, 44, 35, 11]
for index, val in enumerate(my_list):
print(index, val)
51
Flatten a Nested List
Python Program to Flatten a Nested List
my_list = [[1], [2, 3], [4, 5, 6, 7]]
flat_list = [num for sublist in my_list for num in sublist]
print(flat_list)
52
Slice Lists
Python Program to Slice Lists
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])
53
Iterate Over Dictionaries
Python Program to Iterate Over Dictionaries Using for Loop
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.items():
print(key, value)
54
Sort a Dictionary
Python Program to Sort a Dictionary by Value
dt = {5:4, 1:6, 6:3}
sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}
print(sorted_dt)
55
List is Empty
Python Program to Check If a List is Empty
my_list = []
if not my_list:
print("the list is empty")
56
Catch Multiple Exception
Python Program to Catch Multiple Exceptions in One Line
string = input()
try:
num = int(input())
print(string+num)
except (TypeError, ValueError) as e:
print(e)
57
Copy a File
Python Program to Copy a File
from shutil import copyfile
copyfile("/root/a.txt", "/root/b.txt")
58
Concatenate Two Lists
Python Program to Concatenate Two Lists
list_1 = [1, 'a']
list_2 = [3, 4, 5]
list_joined = list_1 + list_2
print(list_joined)
59
Key is Already Present in a Dictionary
Python Program to Check if a Key is Already Present in a Dictionary
my_dict = {1: 'a', 2: 'b', 3: 'c'}
if 2 in my_dict:
print("present")
60
Split a List Into Evenly Sized Chunks
Python Program to Split a List Into Evenly Sized Chunks
def split(list_a, chunk_size):
for i in range(0, len(list_a), chunk_size):
yield list_a[i:i + chunk_size]
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
61
Parse a String to a Float or Int
Python Program to Parse a String to a Float or Int
balance_str = "1500"
balance_int = int(balance_str)
# print the type
print(type(balance_int))
# print the value
print(balance_int)