Basic_Python_programs.ipynb - Colab
Basic_Python_programs.ipynb - Colab
ipynb - Colab
Hello_World!
def square(n):
return n*n
def cube(n):
return n**3
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 1/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
a = int(input("A: "))
b = int(input("B: "))
c = int(input("C: "))
A: 3
B: 6
C: 9
9 is a largest number.
def add(num):
result = 0
for i in num:
result += i
return result
def sub(num):
return num[0] - num[1]
def mul(num):
result = 1
for i in num:
result*= i
return result
def div(num):
return num[0] // num[1]
def fdiv(num):
return num[0]/num[1]
def mod(num):
return num[0]%num[1]
if operation == '+' or operation == '-' or operation == '*' or operation =='/' or operation =='//' or operat
operands = list(map(int, input("Enter the numbers seperated by space:").split(" ")))
if operation =='+':
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 2/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
print("Addition:", add(operands))
elif operation == '-':
print('Subtraction:', sub(operands))
elif operation =='*':
print('Multiplication:', mul(operands))
elif operation =='//':
print('Division:', div(operands))
elif operation =='/':
print("Floor division:", fdiv(operands))
else:
print('Modulus:', mod(operands))
else:
print("Enter invalid operation...")
a = 10
b = 20
print(f"Before swapping a has {a} and b has {b}")
a, b = b, a
print(f"After swapping a has {a} and b has {b}")
x = 100
y = 150
print(f"Before swapping x has {x} and y has {y}")
x = x+y
y = x-y
x = x-y
print(f"After swapping x has {x} and y has {y}")
p = 5
q = 15
print(f"Before swapping p has {p} and q has {q}")
p = p ^ q
q = p^q
p = p^ q
print(f"After swapping p has {p} and q has {q}")
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 3/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
return area
if selection == 1:
height = int(input("Enter Height of the triangle:"))
base = int(input("Enter Base of the triangle:"))
print(f"Area of right angled triangle is: {right_angled(base, height)}")
else:
side = int(input("Enter side of the Equilateral triangle: "))
print("Area of Equilateral triangle is {}".format(equilateral(side)))
try:
base = int(input("Enter base of the triangle:"))
height = int(input("Enter height of the triangle:"))
area = 0.5 * base * height
except:
area = ((3**0.5)/4) * base *base
finally:
print(f"Area of triangle is {area}")
a = int(input())
b = int(input())
c = int(input())
if a == 0:
print("Invalid Quadrilateral equation.")
else:
discriminant = b * b - 4 * a * c
square_dis = discriminant **0.5
denominator = 2*a
if discriminant > 0:
# If b*b > 4*a*c, then roots are real and different; roots of x2 - 7x - 12 are 3 and 4
print("Real and different roots")
print("Roots: ", -b-square_dis/denominator, " and ", -b+square_dis/denominator )
elif discriminant == 0:
# b*b == 4*a*c, then roots are real and both roots are same; roots of x2 - 2x + 1 are 1 and 1
print("Real and same roots")
print("Roots are: ", -b/denominator)
else:
# If b*b < 4*a*c, then roots are complex; x2 + x + 1 roots are -0.5 + i1.73205 and -0.5 - i1.73205
print("Complex roots")
print("Roots are: ", -b/denominator,"+i and ", -b/denominator,"-i")
1
1
1
Complex roots
Roots are: -0.5 +i and -0.5 -i11
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 4/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
#1 kilometer = 0.6215 miles
kilometers = float(input("Enter kilometer to convert into miles: "))
miles = kilometers / 1.609
print(f"{kilometers} kilometers are equal to {miles} miles")
#(C*1.8) + 32 = F
# C = (F-32)/1.8
Enter Fahrenhei: 98
Celsius : 36.67
def isEven(n):
return n%2 == 0
# return 1 if n%2 == 0 else 0
# return True if n%2 == 0 else False
if isEven(num):
print("Even number!")
else:
print("Odd number!")
Enter a number:2
Even number!
def leap(year):
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 5/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
return year%4==0
print("Leap Year" if leap(year) else "Non leap year")
Number upto: 15
Sum: 120
def sum(n):
if n == 1:
return 1
else:
return n + sum(n-1)
print("sum of {} natural numbers are: {}".format(number, sum(number)))
Enter number:15
sum of 15 natural numbers are: 120
Enter number: 5
factorial of 5 is 120
def factorial(n):
# return 1 if n ==0 else n*factorial(n-1)
if n == 1:
return 1
else:
return n * factorial(n-1)
if __name__ == "__main__":
number = int(input())
print(factorial(number))
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 6/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
5
120
number = int(input("number:"))
for i in range(1,number+1):
if number%i== 0:
print(i, end= ' ')
number:18
1 2 3 6 9 18
if isPrime(number):
print("{} is a prime number".format(number))
else:
print("{} is not a prime number".format(number))
Any number:21
21 is not a prime number
def isPrime(n):
for j in range(2, (n//2)+1):
if i%j == 0:
return False
return True
Enter start:2
Enter stop:100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 7/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
m = 1
if upto ==0:
print(n)
elif upto == 1:
print(n,m)
else:
print(n, m, end=' ')
for i in range(2, upto+1):
o = m
m = m + n
n = o
print(m, end = ' ')
number = int(input())
copy = number
armstrong = 0
count = len(str(number))
if armstrong == copy:
print(f"{copy} is an Armstrong number.")
else:
print("not an armstrong number")
153
153 is an Armstrong number.
def isArmstrong(n):
str_n = str(n)
count = len(str_n)
armstrong = 0
for j in str_n:
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 8/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
armstrong += int(j)**count
if armstrong == n:
return n
for i in range(start, stop+1):
if isArmstrong(i):
print(i, end = " ")
Enter number5
2 power 0 is 1
2 power 1 is 2
2 power 2 is 4
2 power 3 is 8
2 power 4 is 16
2 power 5 is 32
Enter number: 5
enter a number upto we have to check: 80
The list of numbers which are divisible by 5 are [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65,
97
hcf1 = int(input('HCf_1:'))
hcf2 = int(input('HCF_2:'))
print(gcd(hcf1, hcf2))
HCf_1:24
HCF_2:54
6
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 9/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
n = 24
m = 4
small = n if n<m else m
big = n if n>m else m
while small:
big , small = small, big%small
print(big)
def gcd(nums):
nums = sorted(nums)
for j in range(nums[0],1,-1):
boolean = False
for i in nums:
if i%j ==0:
boolean = True
else:
boolean = False
if boolean== True:
return j
print(gcd(nums))
10,5,65,40,20
5
##Euclidean algorithm
n = 27
m = 24
def Euclidean(m, n):
while n:
m,n = n, m%n
return m
print(Euclidean(m,n))
keyboard_arrow_down LCM
m = int(input('Primary:'))
n = int(input("Second:"))
large = ref = m if m>n else n
small = n if m>n else m
count = 2
while large % small != 0:
large = ref
large *= count
count +=1
print("LCM", large)
Primary:4
Second:6
LCM 12
m = m1 = int(input('Primary:'))
n = n1 = int(input("Second:"))
while n:
m, n = n, m%n
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 10/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
lcm = (m1*n1)//m
print("LCM:", lcm)
Primary:4
Second:6
LCM: 12
num = 12345
rev_num = 0
while num > 0:
rem = num % 10
rev_num = rem + (rev_num * 10)
num //=10
print(rev_num)
54321
num = 12345
print(int(str(num)[::-1]))
54321
num = 123
count = 0
while num:
num//=10
count +=1
print(count)
num=1234
print(len(str(num)))
num = 4
pwr = 2
def power(num, pwr):
return num ** pwr
print(power(num,pwr))
16
print(int(pow(4,3)))
64
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 11/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
binary = ''
while decimal>0:
binary = str(decimal%2) + binary
decimal //=2
print(f'binary is {binary} without functions')
Decimal: 15
With functions: 1111
binary is 1111 without functions
decimal = int(input("Decimal:"))
octal = ''
while decimal>0:
octal = str(decimal%8) + octal
decimal //= 8
print('Octal without functions:', octal)
Decimal:12
with functions 14
Octal without functions: 14
Decimal: 15
with functions: f
Hexadecimal without function: f
binary = input("Binary:")
print("Decimal:", int(binary,2))
decimal = 0
for i in binary:
decimal = decimal * 2 + int(i)
print('Decimal without function:', decimal)
Binary:1011
Decimal: 11
Decimal without function: 11
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 12/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
octal = input("Octal:")
print('Decimal:', int(octal, 8))
decimal = 0
for i in octal:
decimal = decimal*8 + int(i)
print("Decimal without function:", decimal)
Octal:17
Decimal: 15
Decimal without function: 15
hexa = input("Hexadecimal:")
print("decimal:", int(hexa, 16))
decimal = 0
hex_map = {'0':0, '1':1, '2':2, '3':3, '4':4,'5':5,'6':6, '7':7, '8':8, '9':9, 'a':10, 'b':11, 'c':12, 'd':1
for i in hexa:
decimal = 16*decimal + hex_map[i]
print("deciamal without function:",decimal)
Hexadecimal:51
decimal: 81
deciamal without function: 81
n = 5
for i in range(n):
for j in range(n):
print("* ", end="")
print()
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
n = 5
for i in range(n):
for j in range(i+1):
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 13/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
print("* ", end="")
print()
*
* *
* * *
* * * *
* * * * *
n = 5
for i in range(n):
for j in range(n-i):
print("* ", end="")
print()
* * * * *
* * * *
* * *
* *
*
n = 5
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for k in range(i+1):
print("* ", end="")
print()
*
* *
* * *
* * * *
* * * * *
for i in range(5):
print(" " * (4-i+1), "* " * (i+1))
*
* *
* * *
* * * *
* * * * *
n = 5
for i in range(n):
for j in range(i):
print(" ", end= "")
for k in range(n-i):
print('* ',end="")
print()
* * * * *
* * * *
* * *
* *
*
n = 5
for i in range(n):
for j in range(n-i-1):
print(" ", end = "")
for k in range(i+1):
print("* ", end="")
print()
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 14/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
*
* *
* * *
* * * *
* * * * *
n = 5
for i in range(n):
for j in range(i):
print(" ", end="")
for k in range(n-i):
print("* ", end = "")
print()
* * * * *
* * * *
* * *
* *
*
n = 5
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for k in range(i+1):
print("* ", end = "")
print()
for i in range(n):
for j in range(i+1):
print(' ', end = '')
for k in range(n-i-1):
print("* ", end = '')
print()
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
n = 5
for i in range(n-1):
for j in range(i):
print(" ", end = '')
for k in range(n-i):
print("* ", end = '')
print()
for i in range(n):
for j in range(n-i-1):
print(" ", end = "")
for k in range(i+1):
print('* ', end = '')
print()
* * * * *
* * * *
* * *
* *
*
* *
* * *
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 15/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
* * * *
* * * * *
n = 5
for i in range(n-1):
for j in range(i):
print(' ', end = "")
for k in range(n-i):
if k ==0 or k == n-i-1:
print('* ', end = '')
else:
print(" ",end = '')
print()
for i in range(n):
for j in range(n-i-1):
print(' ', end = '')
for k in range(i+1):
if k == 0 or k == i:
print("* ", end='')
else:
print(' ', end='')
print()
* *
* *
* *
* *
*
* *
* *
* *
* *
n = 5
for i in range(n):
for j in range(n):
if i == 0 or j ==0 or i == n-1 or j == n-1:
print('* ',end = '')
else:
print(' ', end = '')
print()
* * * * *
* *
* *
* *
* * * * *
n = 5
for i in range(n+1):
for j in range(i):
if j == 0 or i ==n or i == j+1:
print('* ', end = '')
else:
print(' ',end = '')
print()
*
* *
* *
* *
* * * * *
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 16/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
n = 5
for i in range(n):
for j in range(i):
print(' ',end ='')
for k in range(n-i):
if i == 0 or k == 0 or k ==n-i-1:
print('* ',end='')
else:
print(' ',end = '')
print()
* * * * *
* *
* *
* *
*
n = 5
for i in range(n):
for j in range(n-i):
if i == 0 or j == 0 or j == n-i-1:
print('* ', end='')
else:
print(' ', end = '')
print()
* * * * *
* *
* *
* *
*
n = 5
for i in range(n):
for j in range(n-i-1):
print(' ',end='')
for k in range(i+1):
if k == 0 or k ==i or i ==n-1:
print('* ', end = '')
else:
print(' ',end='')
print()
*
* *
* *
* *
* * * * *
n = 5
for i in range(n):
for j in range(i):
print(' ',end='')
for k in range(n-i):
if i == 0 or k == 0 or k == n-i-1:
print('* ', end='')
else:
print(' ',end='')
print()
* * * * *
* *
* *
* *
*
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 17/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
n = 5
for i in range(n-1):
for j in range(n-i-1):
print(" ",end='')
for k in range(i+1):
if k == 0 or k == i:
print("* ",end='')
else:
print(' ',end='')
print()
for i in range(n):
for j in range(i):
print(' ',end='')
for k in range(n-i):
if k == 0 or k ==n-i-1:
print('* ',end='')
else:
print(' ',end='')
print()
*
* *
* *
* *
* *
* *
* *
* *
*
list1 = [21,3,9,54,3,24]
list2=[]
if len(list1) == 0:
print('List1 is empty')
else:
print(f'List1 has {len(list1)} elements')
if not list2:
print('List is Empty')
my_list = [1,2,3,4,5,6]
print(my_list[len(my_list)-1])
print(my_list[-1])
6
6
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 18/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
num = ['zero','one','two','three']
for i in num:
ind = num.index(i)
print(ind, 'index of', i)
0 index of zero
1 index of one
2 index of two
3 index of three
num = ['zero','one','two','three']
for i,j in enumerate(num):
print(i,'index of', j)
0 index of zero
1 index of one
2 index of two
3 index of three
List = [1,2,3,4,2,4,1,4,5,2,6,72,7,8]
search = 2
print(List.count(search))
search = 1
count = 0
for i in List:
if search == i:
count +=1
print(count)
[1, 2, 3]
[8, 9, 10]
[2, 4, 6, 8, 10]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 19/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
list1 = [1,2,3,4]
list2 = [5,6,7,8]
print(list1+list2)
list1.extend(list2)
print(list1)
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
str1 = "Hello"
str2 = "World"
total = '_'.join((str1,str2))
print(total)
Hello_World
my_list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
size = 2
lists= [my_list[i:i+size] for i in range(0,len(my_list),size)]
print(lists)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14]]
nested_list = [0.1,0.2,[3.1,4.2,[5,6,[70,80,[900,1000]]]]]
def flattened(num):
flattened_list = []
for i in num:
if isinstance(i, list):
flattened_list.extend(flattened(i))
else:
flattened_list.append(i)
return flattened_list
print(flattened(nested_list))
my_list = [1,2,3,4]
my_list2 = my_list[::-1]
for i, j in zip(my_list, my_list2):
print(i,j)
1 4
2 3
3 2
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 20/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
4 1
my_list = [1,1,2,7,3,4,4,5,5,3,3,5,4,1,6]
print(list(set(my_list)))
[1, 2, 3, 4, 5, 6, 7]
my_list = [1,1,2,7,3,4,4,5,5,3,3,5,4,1,6]
new_list = []
for i in my_list:
if i not in new_list:
new_list.append(i)
new_list.sort()
print(new_list)
[1, 2, 3, 4, 5, 6, 7]
my_list = [1,2,3,4,5,6,3,7,8,9]
print('Actual list:', my_list)
del my_list[1] #delete the 1st index item
print('Del index 1:',my_list)
my_list.remove(3) #remove element which we passed as an argument
print(my_list)
popped_item = my_list.pop(5) #pop item in 5th index
print(f'{popped_item} is fetched which locates as 5th index of {my_list}')
major = []
for i in range(m):
minor = []
for j in range(n):
k = matrix1[i][j]+matrix2[i][j]
minor.append(k)
major.append(minor)
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 21/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
print(minor)
for i in range(m):
for j in range(n):
print(major[i][j], end=' ')
print()
# Example matrix
matrix = [ [1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transpose = []
for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
row.append(matrix[j][i])
transpose.append(row)
print("Transposed matrix:")
for row in transpose:
print(row)
Transposed matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 22/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
k = matrix[j][i]
row.append(k)
matrixB.append(row)
for i in range(len(matrix)):
for j in range(len(matrixB[0])):
for k in range(len(matrixB)):
mul[i][j]= matrix[i][k]*matrixB[k][j]
for i in mul:
print(i)
string_in = '3.14'
# string_in = '3.14pi'
try:
float_in = float(string_in)
print(float_in)
except ValueError as e:
print("Exception raised on ", e)
print(long_string)
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 23/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
Enter a character:7
Unicode value of 7 is 55
if string == string[::-1]:
print("string is palindrome")
else:
print("Not pallindrome")
words = input().upper()
A = E = I = O = U = 0
for i in words:
if i =='A':
A += 1
elif i =='E':
E += 1
elif i =='I':
I += 1
elif i =='O':
O += 1
elif i =='U':
U += 1
else:
pass
Sai Praveen
A: 2 E: 2 I: 1 O: 0 U: 0
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 24/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
print('S2:', s2)
print('S3:', s3)
S1: Sai
S2: Sai Praveen
S3: neevarP
alphabets = ['hai','i', 'had', 'many', 'hopes', 'on','ttec', 'company', 'for', 'that', 'i', 'had', 'prepared
sorted_one = sorted(alphabets)
print(sorted_one)
['communication', 'company', 'didn"t', 'due', 'for', 'get', 'had', 'had', 'hai', 'having', 'hopes', 'i',
HaiSaiPraveen
b'Hai Praveen'
Hai Praveen
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 25/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
string1='listen'
string2 = 'silent'
string1 = string1.replace(" ","").lower()
string2 = string2.replace(" ","").lower()
if sorted(string1) == sorted(string2):
print("Strings are Anagrams")
else:
print("Not Anagrams")
Sai praveen
def is_num(input):
return isinstance(input, str)
def is_num1(input):
return input.isdigit()
def is_num2(input):
return input.isnumeric()
def is_num3(input):
try:
float(input)
return True
except:
return False
print(is_num3('5'))
True
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 26/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
import string
string_input = 'Hai! my name is Praveen: Im working in D.X.C. Technologies!'
new = str.maketrans('','',string.punctuation)
string_input = string_input.translate(new)
print(string_input)
import string
string_input = 'Hai! my name is Praveen: Im working in D.X.C. Technologies!'
s = ''
for i in string_input:
if i not in string.punctuation:
s += i
print(s)
a = {1,2,3,4,5,6}
b = {4,5,6,7,8,9}
difference_set = a.difference(b)
difference_set = a - b #returns elements present in A but not in B
print(difference_set)
s
ymmetric_difference_set = a.symmetric_difference(b)
symmetric_difference_set = a ^ b # returns the elements present in either of the sets but not in both
print(symmetric_difference_set)
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 27/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
subset_check = a.issubset(b)
subset_check = a <= b #returns True if all the elements in the first set are present in the second
print(subset_check)
superset_check = b.issuperset(a)
superset_check = a >= b #returns True if all the elements in the second set are present in the first
print(superset_check)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{4, 5, 6}
{1, 2, 3}
{1, 2, 3, 7, 8, 9}
False
False
{'Name': 'Sai Praveen Ande', 'Age': 22, 'Qualification': 'B.Tech', 'Branch': 'ECE', 'Address': {'Door No
list1 = [1,2,3,4,5]
list2 = [1,4,9,16,25]
my_dict = {}
for index,value in enumerate(list1):
my_dict[value] = list2[index]
print(my_dict)
print(my_dict2)
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 28/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
for value in my_dict.values():
print(value, end = ' ')
A for Append
B for BaseClass
C for Cassendra
D for Database
E for Efficient
A B C D E
Append BaseClass Cassendra Database Efficient
print(dict(sorted(my_dict.items(), key = lambda x:x[1], reverse = True))) # sort values in reverse order
ele = 'C'
if my_dict.get(ele) is not None:
print(f'{ele} is present in dictionary with {my_dict.get(ele)}')
else:
print(f'{ele} not in dictionary')
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 29/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
{1: 'sai Praveen', 2: 'vamsi', 3: 'Raja Blessing', 4: 'jagadhish', 6: 'peta subhramanyam', 7: 'Pavan Put
{1: 'sai Praveen', 2: 'vamsi', 3: 'Raja Blessing', 4: 'jagadhish', 6: 'peta subhramanyam', 7: 'Pavan Put
my_list = [1,2,3]
try:
print(my_list[3]/0)
except (IndexError, ZeroDivisionError, ValueError) as e:
print('Exception Raise', str(e))
I am a pyton Programmer!
import sys
sys.stdout.write("Hello ")
sys.stdout.write("Praveen!")
Hello Praveen!
class MyClass:
pass
obj = MyClass()
class_name = type(obj).__name__
class_Name = obj.__class__.__name__
print(class_name)
print(class_Name)
MyClass
MyClass
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 30/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
YELLOW = 3
Color.RED
2
Color.RED
Color.GREEN
Color.YELLOW
True
False
import random as r
8
1
3.204923201970927
E
['N']
import random
lis = [1,2,3,4,5,6,7,8]
print(random.choice(lis))
Spades of 4
Spades of 10
Diamonds of 10
Spades of 7
Clubs of 2
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 31/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
File_path = 'path/source/file.txt'
with open(File_path, 'a') as file:
content = "This is the Text that I should have to append to file.txt file.\n"
file.write(content)
path_file = "path/source/file.txt"
file_path= 'path/source/file.txt'
with open(file_path, 'r') as file:
count = 0
for line in file:
count += 1
print(count)
import os
file_path = 'path/source/file.txt'
file_name = os.path.basename(file_path)
print(file_name)
file.txt
import os
file_name = 'file.exe'
file_exe = os.path.splitext(file_name)[1]
print(file_exe)
.exe
keyboard_arrow_down Find All File with .txt Extension Present inside a Directory
import os
files= 'path/source/'
for file in files:
if os.path.splitext(files)[1] == '.txt':
print(os.path.basename(file))
/content
file_path = 'path/to/source/file.txt'
print('File size:', path.getsize(file_path), 'bytes')
import calendar
yy = int(input('enter year: '))
month = int(input('Enter month 1-12: '))
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 33/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
print()
print(calendar.month(yy, month))
October 2001
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
2001-10-22 02:30:12
file_path = 'path/to/source/file.txt'
creation_time = os.path.getctime(file_path)
creation_date = datetime.datetime.fromtimestamp(creation_time)
print(f'File is created at {creation_time} on {creation_date}')
modify_time = os.path.getmtime(file_path)
modify_date = datetime.datetime.fromtimestamp(modify_time)
print(f'File recently modified at {modify_time} on {modify_date}')
import time
def timer(minutes):
seconds = minutes * 60
while seconds>0:
minute_remaining = seconds // 60
second_remaining = seconds % 60
print(f'{minute_remaining:02d} : {second_remaining:02d}')
time.sleep(1)
seconds -=1
print("Time is UP!")
timer(1)
01 : 00
00 : 59
00 : 58
00 : 57
00 : 56
00 : 55
00 : 54
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 34/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
00 : 53
00 : 52
00 : 51
00 : 50
00 : 49
00 : 48
00 : 47
00 : 46
00 : 45
00 : 44
00 : 43
00 : 42
00 : 41
00 : 40
00 : 39
00 : 38
00 : 37
00 : 36
00 : 35
00 : 34
00 : 33
00 : 32
00 : 31
00 : 30
00 : 29
00 : 28
00 : 27
00 : 26
00 : 25
00 : 24
00 : 23
00 : 22
00 : 21
00 : 20
00 : 19
00 : 18
00 : 17
00 : 16
00 : 15
00 : 14
00 : 13
00 : 12
00 : 11
00 : 10
00 : 09
00 : 08
00 : 07
00 : 06
00 : 05
00 : 04
00 : 03
import time
start = time.time()
end = time.time()
elapsed_time = end -start
print(f'{elapsed_time:.2f}')
3.01
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 35/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
import email
import mailbox
pic = Image.open("picture.jpg")
width, height = pic.size
print('Image resolution: ', width, "*", height)
import hashlib
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 36/37
3/3/25, 5:03 PM Basic_Python_programs.ipynb - Colab
# print the hash values
https://colab.research.google.com/drive/1BE32xmy-SCbPxY7O_xIVaJ6XpTUfZzNq?usp=sharing#printMode=true 37/37