Python 89 Codes
Python 89 Codes
Python 89 Codes
print('Hello, world!')
******************************
# This program adds two numbers
num1 = 1.5
num2 = 6.3
a=5
b=6
c=7
a=1
b=5
c=6
x=y
y = temp
print(random.randint(0,9))
***********************************************
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles'
%(kilometers,miles))
***********************************************
*******
# Python Program to convert temperature in celsius tofahrenheit
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degreeFahrenheit' %(celsius,fahrenheit))
***********************************************
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
# change the values of num1, num2 and num3# for a different result
num1 = 10
num2 = 14
num3 = 12
else:
largest = num3
num = 29
num = 407
if (num % i) == 0:
lower = 900
upper = 1000
Factorial = 1 :
num = 12
# initialize sum
sum = 0
num = 1634
# initialize sumsum = 0
lower = 100
upper = 2000
# initialize sumsum = 0
num = 16
if num < 0:
print("Enter a positive number")else:
sum = 0
# use while loop to iterate until zero
# Uncomment code below to take input from the user # terms = int(input("How many
terms? "))
c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))
******************************************
# define a function
def compute_hcf(x, y):
num1 = 54
num2 = 24
return lcm
num1 = 54
num2 = 24
print_factors(num)
print("Select operation.")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four optionsif choice in ('1', '2', '3',
'4'):
num1 = float(input("Enter first number: ")) num2 = float(input("Enter
second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
else:
print("Invalid Input")
# importing modules
import itertools, random
yy = 2014 # year mm = 11 #
month
nterms = 10
if num < 0:
print("Enter a positive number")else:
print("The sum is",recur_sum(num))
***********************************************
def recur_factorial(n):if n == 1:
return nelse:
return n*recur_factorial(n-1)
num = 7
# decimal numberdec = 34
convertToBinary(dec)print()
*************************************
# 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],
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:print(r)
*******************************
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for r in result:
print(r)
***************************************
# Program to multiply two matrices using nested loops
# 3x3 matrix X =
[[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrixY =
[[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]]
for r in result:print(r)
**************************************
# Program to check if a string is palindrome or notmy_str = 'aIbohPhoBiA'
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# set union
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# string of vowelsvowels =
'aeiou'
# make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0)
print(count)
*****************************
# Python rogram to find the SHA-1 message digest of afile
def hash_file(filename):
""""This function returns the SHA-1 hashof the file passed into
it"""
message = hash_file("track1.mp3")print(message)
ascii_value += 1
print("\n")
*********************************************
Example 4: Inverted half pyramid using *
*****
****
***
**
*
Source Code
rows = int(input("Enter number of rows: "))
print("\n")
****************************************
while k!=(2*i-1):
print("* ", end="")k += 1
k=0
print()
***********************************
Example 7: Full Pyramid of Numbers
1
232
34543
4567654
567898765
Source Code
rows = int(input("Enter number of rows: "))
while k!=((2*i)-1):
if count<=rows-1: print(i+k, end="
")count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")k += 1
*********
print(dict_1 | dict_2)
**************************************dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print({**dict_1, **dict_2})
***********************************dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
dict_3 = dict_2.copy()
dict_3.update(dict_1)
print(dict_3)
************************************my_list = [21, 44, 35, 11]
print(flat_list)
***********************************************
To understand this example, you should have the knowledge of the following Python
programming topics:
Using list comprehension access the sublist from my_list,then access each element of the
sublist.
Each element num is stored in flat_list.
Learn more about list comprehension at Python List
Comprehension.
Example 2: Using Nested for Loops (non pythonic way)my_list = [[1], [2, 3], [4, 5, 6, 7]]
flat_list = []
for sublist in my_list:for num in
sublist:
flat_list.append(num)
print(flat_list)
Output
[1, 2, 3, 4, 5, 6, 7]
Create an empty list flat_list.
flat_list = list(itertools.chain(*my_list))print(flat_list)
**************************************Example 4: Using sum()
my_list = [[1], [2, 3], [4, 5, 6, 7]]
print(my_list[:])
******************************** Get all the Items After a Specific
Positionmy_list = [1, 2, 3, 4, 5]
print(my_list[2:])
**********************************Get all the Items Before a Specific
Positionmy_list = [1, 2, 3, 4, 5]
print(my_list[:2])
*********************************
Get all the Items from One Position to Another Positionmy_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
************************************
Get the Items at Specified Intervals
my_list = [1, 2, 3, 4, 5]
print(my_list[::2])
************************************
print(sorted_dt)
*********************************Example 2: Sort only the values
dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)
************************************Example 1: Using Boolean
operation
my_list = []if not
my_list:
print("the list is empty")
***************************************Example 2: Using len()
try:
num = int(input())
print(string+num)
except (TypeError, ValueError) as e:print(e)
********************************************
Example 1: Using + operatorlist_1 = [1, 'a']
list_2 = [3, 4, 5]
list_2.extend(list_1)print(list_2)
*****************************Using in keyword
my_dict = {1: 'a', 2: 'b', 3: 'c'}
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
**************************************Example 2: Using numpy
import numpy as np
my_list = [1,2,3,4,5,6,7,8,9]
print(np.array_split(my_list, 5))
******************************Example 1: Parse string into
integer balance_str = "1500"
balance_int = int(balance_str)
11:31AM"
print(type(datetime_object))
print(datetime_object)
**************************************Example 2: Using dateutil module
from dateutil import parser
# prints "love"
print(my_string[2:6])
# new line
print()
honda 1948
mercedes 1926
ford 1903 Source
Code
print(content_list)
******************************************Example 1: Using random module
import random
print(isfloat('s12'))
print(isfloat('1.123'))
************************************Using count() method
freq = ['a', 1, 'a', 4, 3, 2, 'a'].count('a')print(freq)
*********************************Open file in append mode and
write to it The content of the file my_file.txt is
honda 1948
mercedes 1926
ford 1903
The source code to write to a file in append mode is:
print(my_dict)
*********************************Example 2: Using pop()
my_dict = {31: 'a', 21: 'b', 14: 'c'}print(my_dict.pop(31))
print(my_dict)
*********************************Example 1: Using triple quotes
my_string = '''The only way to
learn to program isby writing
code.'''
print(my_string)
***********************************
Example 2: Using parentheses and a single/double quotesmy_string = ("The only way to \n"
"learn to program is \n""by writing
code.")
print(my_string)
*********************************
Example 1: Using splitext() method from os moduleimport os
file_details = os.path.splitext('/path/file.ext')print(file_details)
print(file_details[1])
**************************************Example 2: Using pathlib module
import pathlib print(pathlib.Path('/path/file.ext').suffix)
**************************************
start = time.time()
end = time.time()print(end -
start)
***********************************Example 2: Using timeit module
from timeit import default_timer as timerstart = timer()
print(23*2.3)
v = Vehicle()
print(v. class . name )
**************************************
v = Vehicle()
print(type(v). name )
**************************************Example 1: Using zip and dict methods
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
class Polygon:
def sides_no(self):pass
class Triangle(Polygon):def
area(self):
pass
obj_polygon = Polygon()obj_triangle =
Triangle()
print(my_string.strip())
print(output)
**********************************
Example 1: Using os module
import os
***********************************
Example 2: Using Path module
from pathlib import Path
print(Path('/root/file.ext').stem)
***********************************
class Day(Enum):MONDAY
=1
TUESDAY = 2
WEDNESDAY = 3
names = name()
print(names)
honda 1948
mercedes 1926
ford 1903 Source
Code
def file_len(fname):
print(file_len("my_file.txt"))
*************************************** Example 2: Using list comprehension
num_of_lines = sum(1 for l in open('my_file.txt'))
print(num_of_lines)
***********************************Use of del
del deletes items at a specified position.my_list = [1, 2, 3, 4]
del my_list[1]
print(my_list)
********************************Use of remove
remove() deletes the specified item.
my_list.remove(2)
print(my_list)
***********************************Use of pop
pop() removes the item at a specified position and returnsit.
my_list = [1, 2, 3, 4]
print(my_list.pop(1))
print(my_list)
*************************************
Example 1: Using globimport glob,
os
os.chdir("my_dir")
file = pathlib.Path('abc.py')
print("Last modification time: %s" %
time.ctime(os.path.getmtime(file)))
print("Last metadata change time or path creation time:
%s" % time.ctime(os.path.getctime(file)))
***********************************************
*****
time: %s" %
datetime.datetime.fromtimestamp(fname.stat().st_mtime)
)
print("Last metadata change time or path creation time:
%s" %
datetime.datetime.fromtimestamp(fname.stat().st_ctime))
***********************************************Example 1: Using pathlib module
import pathlib
print("\n")
file_stat = os.stat('my_file.txt')
print(file_stat.st_size)
***************************************Example 2: Using pathlib module
from pathlib import Path
file = Path('my_file.txt')
print(file.stat().st_size)
******************************
Example 1: Reverse a Number using a while loopnum = 1234
reversed_num = 0
***********************************
Example 1: Calculate power of a number using a whileloop
base = 3
exponent = 4
result = 1
else:
print(str1 + " and " + str2 + " are not anagram.")
********************************************Example 1: Using list slicing
my_string = "talent battle is Lit"
print(my_string[0].upper() + my_string[1:])
***********************************************
**
Example 2: Using inbuilt method capitalize()
my_string = "talent battle is Lit"
cap_string = my_string.capitalize()print(cap_string)
**************************************
in string]
# swap
words[i], words[j] = words[j], words[i]
get_permutation(words, i + 1)
print(get_permutation('yup'))
****************************************Example 2: Using itertools
from itertools import permutations
print("stop")
countdown(5)
******************************************
for i in my_string: if i ==
my_char:
count += 1
print(count)
print(my_string.count(my_char))
**********************************Example 1: Using set()
list_1 = [1, 2, 1, 4, 6]
print(list(set(list_1)))
in two
lists
list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]
print(list(set(list_1) ^ set(list_2)))
*****************************************Using decode()
print(b'Easy \xE2\x9C\x85'.decode("utf-8"))
***************************************