Explore the list of my Python programs below:
Remainder
-
A python program to reaminds you something
import time
from plyer import notification
while True:
notification.notify(
title='too much work done',
message='Go and touch some grass Buddy',
)
time.sleep(60*60)
Python Operators & Conditionals
-
Ternary operation
food=input("food:")
print("sweet") if food=="cake" or food=="jalebi" else print("not sweet")
#cleaver ternary operator 1
age = int(input("age :"))
vote = ("yes", "no") [age <= 18]
print(vote)
#cleaver ternary operator 2
'''
sal = float (input("salary : "))
tax = sal*(0.1, 0.2) [sal <= 50000]
print(tax)'''
-
Logical Operator
# logical operators
a = True
b = False
print("AND OPERATION....")
print(a and a)
print(a and b)
print(b and a)
print(b and b)
print("OR OPERATION.....")
print(a or a)
print(a or b)
print(b or a)
print(b or b)
-
Comparison
# Comparison operators
a = 6
print(a > 4)
print(a < 4)
print(a >= 4)
print(a >= 4)
print(a == 4)
print(a != 4)
-
Assignment Operators
# assignment operator shorthand operator
a = 2
a *= 10 #a= a+10
print(a)
a += 10
print(a)
a -= 10
print(a)
a %= 10
print(a)
a /= 10
print(a)
a //= 10
print(a)
-
Arithamatic Operations
# arithamatic operators
num1=int(input("enter 1st number :"))
num2=int(input("enter 2nd number :"))
print(" sum of ",num1,"and",num2,"=",num1+num2)
print(" subtraction of ",num1,"and",num2,"=",num1-num2)
print(" multiplication of ",num1,"and",num2,"=",num1*num2)
print(" divison of ",num1,"and",num2,"=",num1/num2)
print(" modulo of ",num1,"and",num2,"=",num1%num2)
print(" average of ",num1,"and",num2,"=",(num1+num2)/2)
print(" power ",(num1)*num2,"=",num1**num2)
# print(" square of ",num1,"=",num1**2
-
If,if-else, If-else ladder
A = int(input ("A :"))
G = input ("M/F : ")
if((A == 1 or A == 2) and G == "M"):
print("fee is 100")
elif(A == 3 or A == 4 or G == "F"):
print("fee is 200")
elif(A == 5 and G == "M"):
print("fee is 300")
else:
print("no fee")
'''
marks = int(input("enter marks:"))
if (marks>=90):
grade="A"
elif (marks<90 and marks>=80):
grade="B"
elif (marks<80 and marks>=70):
grade="C"
else:
grade="D"
print("grade is:",grade)'''
Loops
-
For loop
for i in range(1,11): # range goes from (n, n-1)
print("5 X",i,"=",5*(i))
-
While loop
i = int(input("ENTER VALUE OF I ="))
n = int (input("upto ="))
while i<=n:
print(i)
i+=11
-
Sum of N number
# sum of first n numbers using while
'''
1+ 2 +3 +4+5 = 15
sum = n+ n+1 +n+2...
'''
input_num = int(input('Enter a number: '))
total = 0
# # using while loop
# i = 1
# while i <= input_num:
# total += i
# i += 1
# using for loop
for i in range (1,input_num+1):
total += i
print(total)
-
Factorial
num =int(input('Enter a number: '))
fact=0
# using for loop
# for i in range(1,num+1):
# if fact == 0:
# fact = i
# else:
# fact *= i
# using while loop
i=1
while i<= num:
if fact == 0:
fact = i
else:
fact *= i
i += 1 # increment i by 1
# factorial upto 5 is 120
print(f'factorial upto {num} is {fact}')
-
Star Pattern
try:
rows = int(input("Enter number of rows: "))
count = 0
for i in range(1, rows + 1):
print("*" * i)
count += i
print(f"Total asterisks: {count}")
except Exception as e:
print("Error:", e)
-
Star pyramid pattern
rows = int(input('Enter the no. of rows= '))
for i in range(1, rows + 1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
-
Find the Largest number
# Program to FIND LARGEST BETWEEN N NUMBERS without using a list
count = int(input('Enter the total number of values you want to compare: '))
# 4
# Take the first input as the initial largest number
largest = int(input('Enter number 1: '))
# Start comparing from the second input
for i in range(1, count):
num = int(input(f'Enter number {i+1}: '))
if num > largest:
largest = num
print("The largest number is:", largest)
-
Palindrome
# Variables to store the number, remainder, and result
n = r = num = res = 0num = int(input("Enter the number: "))
n = num
res = 0 # Initialize the resul
# Reverse the number
while n > 0:
r = n % 10 # Get the last digit of the number
res = res * 10 + r # Append the digit to the reversed number
n = n // 10 # Remove the last digit from the number
print(f"Reverse of {num} is {res}")
# Check if the original number is a palindrome
if num == res:
print(f"{num} is a palindrome number")
else:
print(f"{num} is not a palindrome number")
Function
-
Factorial using function
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return f"The factorial of {n} is 1"
else:
fact = 1
for i in range(2, n + 1):
fact *= i
return f"The factorial of {n} is {fact}"
# Test cases
print(factorial(-5)) # Negative input
print(factorial(0)) # Special case
print(factorial(1)) # Special case
print(factorial(5)) # Normal case
-
USD to INR converter
def to_inr(usd_value):
inr_value = usd_value*83
print(f'{usd_value} USD = {inr_value} INR')
def to_usd(usd_value):
inr_value = usd_value*83
print(f'{inr_value} INR = {usd_value} USD ')
convertor = str(input('press (I)ndian value or (U)SD value: ')).lower()
value = int(input('Enter the value: '))
if convertor == "i":
to_inr(value)
else:
to_usd(value)
-
Swap two variables
# function that swaps the position of 2 variable
def swap(a,b):
temp = a
a = b
b = temp
print(f"The value of a is {a} and b is {b}") # Print the swapped values of a and b.
swap(4,6)
-
Function with arguments
def sum(a,b,c): # fn definition(actual parameter)
sum=(a + b+ c)
return sum
s1 = sum(3,2,1) #function call(argument)
print(s1)
s2 = sum(8,5,9)
print(s2)
# a function to check value is even or odd
value=int(input('enter the no.: '))
def checker(num):
if ((num%2)==0):
print('EVEN')
else:
print('ODD')
checker(value)
-
Fibonacci sequence using recursion
'''
0 1 1 2 3 5 8
fib(0) = 0
fib(1) = 1
fib(2) = fib(0) + fib(1)
fib(3)=fib(1) + fib(2)
fib(4)=fib(2)+ fib(3)
fib(n) = fib(n-2) + fib(n-1)
'''
def fib(n):
# Base case of recursion
if(n == 0 or n == 1):
return n
return fib(n-2) + fib(n-1)
for i in range(0, 9):
print(fib(i), end="\t")
# The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.
-
Recursive sum of numbers
def cal_sum(n):
if n==0:
return 0
return cal_sum(n-1) + n
print(cal_sum(5))
# printing a list using the Recursion
num =[1,2,3,65,5,8,2,2,5,5,2]
def print_num(num,idx=0):
if idx==len(num):
return
print(num[idx],end=' ')
return print_num(num, idx+1)
print_num(num)
-
Modules
import mymodule
import math
print(math.sqrt(16))
mymodule.hello()
#create a file module with name mymodule to use this function
def hello():
print("hello world \nfrom my module")
-
Global and local variables
def avg(a,b):
avg = (a+b)/2 # this avg is a local variable
global z # this declares that we want to change the global variable a
z = 5
return avg
z = 10 # this is a global variable
print(avg(10,20))
print(z) # this will print the global variable z
-
Function with docstrings
def sqrt(x):
'''This function calculates the root of number x.'''
if x < 0:
print("enter a postive no.")
else:
root = x * x
return root
print (sqrt.__doc__)
print (sqrt(4))
String
-
String Functions
# str.len() function
'''len() function is an inbuilt function in python programming language that returns the length of the string.
syntax: len(string)'''
name = input("name:")
print("length of string is :", len(name))
# str.count() function
'''count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string.
syntax: str.count(substring, start, end)'''
str = "this is $ symbol $99.9 and it is used for $ money"
print("the repetation of ", str.count("$"))
# str.find() function
'''find() function is an inbuilt function in python programming language that returns the index of first occurrence of the substring in the given string.
syntax: str.find(substring, start, end)'''
str = "this is $ symbol"
# 8 7 6 5 4 3 2 1
# -8 -7 -6 -5 -4 -3 -2 -1 negative indexing is used
print(str.find("$"))
# str.capitalize function
'''capitalize() function is an inbuilt function in python programming language that returns the first letter of the string in capital letter.
syntax: str.capitalize()'''
str = "i am Studying Python from College"
str = str.capitalize()
print(str)
# str.endswith() function
'''endswith() function is an inbuilt function in python programming language that returns the boolean value True if the string ends with the specified suffix, otherwise False.
syntax: str.endswith(suffix, start, end)'''
str = "i am Studying Python from College"
print(str.endswith("College"))
# str.replace() function
'''replace() function is an inbuilt function in python programming language that returns the string by replacing the old substring with the new substring.
syntax: str.replace(old, new, count)'''
str = "i am Studying Python from College"
str = str.replace("Python", "Java")
print(str)
-
String Slicing
name = "rex456789"
print(name[0:9]) # print from 0 to n-1 , 0 to 8
print(name[0:9:2]) # print from 0 to 8 : skipping 1 character
print(name[:4]) # Replace the first empty number with 0 # name[0:4]
print(name[1:]) # Replace the second empty number with length - 1 # name[1:]
-
String Indexing
# Take input from the user
input = "hello"
print(input[-5])
print(input[-4])
print(input[3])
print(input[2])
print(input[-1])
-
F String
a = "John"
a1 = 10000
b = "Rex"
print(f"Hello, {a}, you are awesome. Take {a1}$ and call {b}.")
Lists
List Operations
# List operations in Python
# list is a collection of items in a particular order.
l1 = [52,14,78,36,58,98,65]
l2 = [85,"helllo",96,"rex"]
print(l1[0:3], l2[3]) # Slicing the first three elements
-
List Methods
# list methods
my_list = [1, 2, 3]
my_list.insert(1, 99) # [1, 99, 2, 3, 4]
my_list.remove(2) # [1, 99, 3, 4]
my_list.pop() # Removes last element -> [1, 99, 3]
my_list.reverse() # [3, 99, 1]
my_list.sort()# [1, 3, 99]
my_list.append(4) #[1, 3, 99, 4]
-
List Comprehension
# create a list of square roots
table = []
for i in range(1, 11):
table.append(i**2)
print(table)
sqrt = [x**2 for x in range(1,11)]
print(sqrt)
-
Tuple Methods
tu = (3,2,5,1,9,2,5)
a, b, s, d, f, r, e = tu
print(a, b, s, d, f)
# tuple methods
print(tu.count(2))
print(tu.index(2))
Sets
-
Set Example
s = {2,5,5,8,4,5}
print (s,type(s))
# set methods
s.add(3) # add an element
s.remove(5) # remove an element
s.discard(5) # discard an element, no error if not found
print(s)
-
Set Operations
# UNION set
a ={1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
c = a.union(b)
print("AUB =",c) # Output: {1, 2, 3, 4,
d = a.intersection(b)
print("Ä∩B =",d) # Output: {4, 5}
-
Input Multiple Sets and Perform Union and Intersection
# Program to take n sets of integers from the user and print their union and intersection.
# Take the number of sets from the user
n = int(input("Enter number of sets: "))
sets = [] # List to store all sets
# Loop to take input for each set
for i in range(n):
# Take comma-separated input, split it, and convert to set
s = set(input(f"Set {i+1} (comma-separated): ").split(','))
sets.append(s) # Add the set to the list
# Print the union of all sets
print("Union:", set.union(*sets))
# Print the intersection of all sets (if any sets exist)
print("Intersection:", set.intersection(*sets) if sets else "None")
Dictionaries
-
Dictionary Example
std = {"kevin":10,
"jhon":43,
"mike":23}
# this KEVIN,JHON are keys of dictionary
'''
print(std["kevin"]) # Accessing value using key
std["mike"] = 2
print(std["mike"])
'''
# dictionary methods
print(std.keys())
print(std.values())
std.pop("mike") # remove key-value pair
# dictionary comprehension
sq = {x: x**2 for x in range(10)}
print(sq)
table_of_20 = {i:i*20 for i in range (1,11)}
print(table_of_20)
-
Input in Dictionary
# WAP to input in subject_marks
# enter marks of student in subject_marks
def student_data():
try:
subject_marks = {}
count = int(input('Enter the number of subject: '))
for i in range(count):
subject = input(f'\nSub{i+1} name : ')
marks = int(input(f'Sub{i+1} marks :'))
subject_marks[subject] = marks
return subject_marks
except Exception as e:
return f'Enter correct value , error occured {e}'
print(student_data())
OOPS
-
Python Class Example
# class is a template for creating objects
# object is an instance of a class
class employee:
company = "Google"
def get_salary(self): # self is way to reference to object which is created
return 34000
# class 1
e = employee() # an object is created
print(e.get_salary()) # calling the method of the class
# class 2
e2 = employee()
print(e2.get_salary()) # accessing the class variable
print(e.company) # accessing the class variable
-
Python Class with Constructors
class Employee:
def __init__(self, name, salary, bond):
self.salary = salary # Create an instance attribute of name salary and assign it with salary
self.name = name
self.bond = bond
def get_info(self):
print(f"\nThe name of the employee is {self.name}.\nSalary is {self.salary}.\nThe bond is for {self.bond} years")
e1 = Employee("REX", 3400000, 4)
e1.get_info()
e2 = Employee("jhon", 2500, 2)
e2.get_info()
-
Python Instance and Class Variables
class emp:
company = "samsung" # this is a class variable
def __init__(self, salary, name, age, company):
self.salary = salary
self.name = name
self.age = age
self.company = company
def get_info(self):
print(f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}, Company: {self.company}")
e1 = emp(1000, "sam", 24, "asus") # this is an instance variable
print(e1.company)
print(emp.company) # Accessing class variable through class name
-
Python Inheritance Example
class animal:
loacation = "India"
def __init__(self, name):
self.name = name
def seapk(self):
print("generic animal sound")
# This is how inheritance works in python
class dog(animal): # this class contain all the properties of animal class
def seapk(self):
print("woof!")
-
Python Operator Overloading
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def sum(self, p):
return point((self.x + p.x), (self.y + p.y))
def print_point(self):
print(f"X is {self.x} and Y is {self.y}")
def __add__(self, p):
return ((self.x + p.x), (self.y + p.y))
p1 = point(1, 2)
p2 = point(3, 4)
# p = p1.sum(p2) #X is 4 and Y is 6
# Operator Overloading
p = p1 + p2 # we overloaded + operator by writing __add__ method
print(p) # This will print a tuple (4, 6)
Python Advance concepts
-
Filters using lambda and filter()
# - filter() applies a function that returns True or False to each item and keeps only the items where the result is True.
# def divisible_by_9(x):
# if (x%9) == 0:
# return True
# else:
# return False
a = []
n = int(input("How many no.: "))
for i in range(n):
while True:
try:
num = int(input(f"Number {i+1} = "))
a.append(num)
break
except ValueError:
print("Please enter a valid integer.")
print(a)
divisible_by_9 = lambda x: x % 9 == 0
new = list(filter(divisible_by_9, a))
print(new)
-
Decorators
#decorators are functions that modify the behavior of another function
# without changing its code. They are often used to add functionality to existing functions in a clean and readable way.
def decorator(func):
def wrapper():
print("I am about to execute a function.........")
func()
print("I have executed a function.........")
return wrapper
@decorator
def say_hello():
print("This is hello function")
say_hello()
'''
f will look somethimng like this:
def f():
print("I am about to execute a function.........")
print("This is hello function")
print("I have executed a function.........")
'''
# f = decorator(say_hello)
# f()
-
Decorator with Arguments (repeat)
def repeat(n):
def decorator(func):
def wrapper(a):
for i in range(n):
func(a)
return wrapper
return decorator
@repeat(5)
def say_hello(a):
print(f"hello! {a}")
say_hello("REX")
'''
it replaces say_hello fn with this:
def decorator(func):
def wrapper(a):
for i in range(5):
say_hello(a)
return decorator
'''
-
Getter and Setter with @property
class employee:
def __init__(self,name, salary):
self.name = name
self.salary = salary
@property
def first_name(self):
l = self.name.split(" ")
return l[0]
@first_name.setter
def first_name(self, first):
l = self.name.split(" ")
new_name = f"{first} {l[1]}"
self.name = new_name
e = employee("Rex doe",100000)
print(e.first_name)
e.first_name = "John"
print(e.name)
-
Instance, Static and Class Methods
class employee:
company = "HP"
def __init__(self,name,salary):
self.name = name
self.salary = salary
# This is an instance method(default)
def info(self):
print(f"THe name of {self.name} and the salary is {self.salary}")
# this is a static method
@staticmethod
def sum(a,b):
return a+b
# this is a class method
@classmethod
def print_company(cls):
print(cls.company)
@classmethod
def change_company(cls,new_company):
cls.company = new_company
e1 = employee("micheal",7389)
e2 = employee("Judas",6545)
# e1.info()
# print(e1.sum(3,3))
# class method try either this
# e1.print_company()
# e1.change_company("SAMSUNG")
# e1.print_company()
# or
print(employee.company)
e1.change_company("ACER")
print(employee.company)
-
Dunder Methods
# dunder stands for double underscore
class employee:
def __init__(self,name,salary):
self.name= name
self.salary = salary
def __str__(self):
return f"\nThe name of employee is {self.name}.\nand Salary is {self.salary}"
def __repr__(self):
return f"\nname = {self.name}.\n Salary = {self.salary}"
def __len__(self):
return len(self.name)
e1 = employee("Rex",68477)
# print(e1.name, e1.salary)
# taking inpu by the usere for the list of employees
list_of_employees = []
no_of_employee = int(input("no. of employees: "))
for i in range(no_of_employee):
print(f"\n for employee {i+1}:")
name = input("Enter employee's name: ")
salary = int(input("Enter employee's salary: "))
e = employee(name, salary)
list_of_employees.append(e)
for e in list_of_employees:
print("The length of name is =",len(e))
print(str(e))
print(repr(e))
-
Error Handling with try-except-finally
# try and except are use to handle error
# when there is error in 'try' stmt it transfers control to 'except'
# while True:
# try:
# a = int(input("Enter first number: "))
# b = int(input("Enter second number: "))
# print(a + b)
# except ValueError:
# print("Please don'perform bad typecast")
# except ZeroDivisionError:
# print("don't divide by 0")
# except Exception as e:
# print("unknown error occured",e)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if b == 0:
raise ValueError("Please don't divide by 0")
print(f"the division is by {a/b}")
-
Try-Else Example
try:
a = 345/10
except Exception as e:
print(e)
# Gets executed when there is no error in the try block
else:
print ("Hey I am good")
-
Try-Finally Example
a = int(input("enter no. 1: "))
b = int(input("enter no. 2: "))
def div(a, b):
try:
c = a / b
print(c)
return c
except Exception as e:
print("An error occurred:", e)
return None
finally:
print("program is executed")
div(a,b)
-
Walrus Operator Example
# def function():
# print("something.......")
# print("something.......")
# return 7
# # a = function()
# if (a:=function())>10:
# print(a)
# else:
# print("a is not greater than 10")
while (data:= input("\nEnter some data: ")):
print(f"You entered: {data}")
# The loop will continue until the user enters an empty string
if data == "exit":
print("Exiting the loop.")
break
-
Variable Arguments (*args) Example
'''
normal fn
def sum(a,b):
return a+b
print(sum(1,2))
'''
# args will be a tuple of all the values passed to sum
def sum(*args):
total = 0
for item in args:
# total = total+item
total += item
return total
print(sum(1,2,3,4))
-
Keyword Arguments (**kwargs) Example
def order_summary(*items, **details):
# def function(*args,**kwargs)
print("Items ordered:", items)
for key, value in details.items():
print(f"{key}: {value}")
order_summary("Burger", "Fries", table=5, takeout=True)
-
Args and kwargs Combined Example
def marks(*args, **kwargs):
print("Positional arguments (args):", args)
print("Keyword arguments (kwargs):", kwargs)
marks(125, 97, 56, 87, jack=65, joe=36, riya=87)
-
Using map() Function
# - map() applies a function to every item in a list and returns a new iterable with the results. Think of it as transforming or converting each element.
# it takes input from user for the list
list_of_no = []
total_no = int(input("Total numbers to be entered: "))
for i in range(total_no):
no_entered = int(input(f"Enter number {i+1}: "))
list_of_no.append(no_entered)
print("You entered:", list_of_no)
square = lambda x: x * x
new = list(map(square,list_of_no))
print(new)
-
Using reduce() Function
# This adds up all the numbers in the list. You’ll find reduce() in the functools module, and it’s great for tasks like summing, multiplying, or combining values into one.
from functools import reduce
numbers = [1,2,3,4,5,6]
# [3,3,4,5,6]
# [6,4,5,6]
# [10,5,6]
# [15,6]
# [21] as output
print("Original list",numbers)
sum = lambda a,b : a+b
print("Reduced list: ",reduce(sum, numbers))
File handiling
-
Reading a file
f = open("rex.txt", "r")
# r refers to just read
# rt means reading file in text mode
content = f.read()
f.close()
print(content)
-
-
Writing in a File
# write to a file called rex.txt
# it should contain info about rex
f = open("rex.txt","w")
str ='''Hi I am Rex a python programmer , Nice to meet ya !
I am learning how to read and write files in python.'''
f.write(str)
f.close()
Append in files
# append is used add the data in existing file at end , without oveerwriting it
f = open("rex.txt","a") # 'a' mode is for appending
str ='''\
This is added through append.I work in AI and ML'''
f.write(str) # write the string to the file
f.close() # close the file
-
Reading line by line
with open("rex.txt", "r") as f:
for line in f:
print(line)
# data =f.readlines() # Read all lines into a list
# print(data) # Print the list of lines
-
With Statement
# # this is how acctuually open a file in python
# f = open("rex.txt","r")
# content = f.read()
# print(content)
# f.close()
with open("rex.txt","r") as f: #context manager
content = f.read()
print(content)
# The 'with' statement automatically closes the file after the block is executed.
-
Using Os module
import os
# print(f"\nfiles under directory are = {os.listdir("dir")}") # List files in the current directory
# print(f"\nlocation of directory is {os.getcwd()}") # Get the current working directory
# print(f"\ndoes rex.txt exits :{os.path.exists("rex.txt")}") # Check if a file exists
os.remove('practice.txt') # Remove a file,'rex.txt',
-
Shutil function
import shutil
# this created a file
with open("s1.txt","w") as f:
f.write("this is sample file 2 ")
shutil.copy("s1.txt","sample.txt")
# shutil (source,destination)
shutil.move("sample.txt","dir/sample.txt")
# import os
# os.remove("11_files/dir/sub_dir2/sample.txt")
-
Creating s Sample file
f = open("sample.txt","w")
f.write("This is a sample file.\nThis file is created for demonstration purposes.\n")
f.close()