0% found this document useful (0 votes)
17 views20 pages

Python Basic Programs and Functions

The document contains various Python programs demonstrating basic functionalities such as a simple calculator, factorial calculation, and operations on lists, files, and strings. It also includes examples of reading and writing to CSV, binary, and text files, as well as handling exceptions. Additionally, it covers concepts like prime number checking, LCM calculation, and frequency counting in strings.

Uploaded by

omkarpal2276
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views20 pages

Python Basic Programs and Functions

The document contains various Python programs demonstrating basic functionalities such as a simple calculator, factorial calculation, and operations on lists, files, and strings. It also includes examples of reading and writing to CSV, binary, and text files, as well as handling exceptions. Additionally, it covers concepts like prime number checking, LCM calculation, and frequency counting in strings.

Uploaded by

omkarpal2276
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SIMPLE CALCULATOR

print('----CALCULATOR-----')

def add(a,b):

return a + b

def sub(a,b):

return a - b

def mul(a,b):

return a * b

def div(a,b):

return a/b

x=int(input('Enter the Ist Number'))

y=int(input('Enter the 2nd Number'))

z=int(input('Hey! What do you want? \n Please Enter- \n 1 for Add \n 2 for Subtract \n 3 for Multiply \n 4 for Divide
\n '))

if z == 1:

print(add(x,y))

elif z == 2:

print(sub(x,y))

elif z == 3:

print(mul(x,y))

elif z == 4:

print(div(x,y))

else:

print('INVALID INPUT! PLEASE ENTER NUMBER BETWEEN 1 to 4')

Output:-
FACTORIAL OF A NUMBER
def factorial(n):

x=1

for i in range(n, 1, -1):

x=x*i

return x

a = int(input('Enter the number whose factorial you want: '))

if a<0:

print('FACTORIAL OF NEGETIVE NUMBER DOES NOT EXIST')

else:

print(factorial(a),'is the factorial of', a)

Output:-
SQUARE AND CUBE OF A NUMBER
def sq(x):

return x*x

def cu(x):

return x*x*x

n=int(input('Enter the Number:'))

z=int(input('What do you want? \nPress 1 for Square \nPress 2 for cube \n '))

if z == 1:

print(sq(n),'is the square of',n)

elif z ==2:

print(cu(n),'is the cube of', n)

else:

print('INVALID INPUT!')

Output:-
READING AND WRITING INTO A
CSV FILE
import csv

# -------- Writing into CSV file --------

f = open("[Link]", "w")

writer = [Link](f)

[Link](["Roll No", "Name", "Marks"])

[Link]([1, "Rahul", 85])

[Link]([2, "Anita", 90])

[Link]([3, "Aman", 78])

[Link]()

print("Data written successfully")

# -------- Reading from CSV file --------

f = open("[Link]", "r", newline="")

reader = [Link](f)

print("\nReading data from CSV file:\n")

for row in reader:

print(row)

[Link]()

Output:-
READING AND WRITING INTO A
BINARY FILE
import pickle

# -------- Writing into Binary file --------

f = open("[Link]", "wb")

data = [[1, "Rahul", 85],

[2, "Anita", 90],

[3, "Aman", 78]]

[Link](data, f)

[Link]()

print("Data written into binary file successfully")

# -------- Reading from Binary file --------

f = open("[Link]", "rb")

data = [Link](f)

print("\nReading data from binary file:\n")

for record in data:

print(record)

[Link]()

Output:-
READING AND WRITING INTO A
TEXT FILE
# -------- Writing into Text file --------

f = open("[Link]", "w")

[Link]("Roll No Name Marks\n")

[Link]("1 Rahul 85\n")

[Link]("2 Anita 90\n")

[Link]("3 Aman 78\n")

[Link]()

print("Data written into text file successfully")

# -------- Reading from Text file --------

f = open("[Link]", "r")

print("\nReading data from text file:\n")

data = [Link]()

print(data)

[Link]()

Output:-
TABLE OF ANY NUMBER
n = int(input("Enter a number: "))

print("Table of", n)

for i in range(1, 11):

print(n, "x", i, "=", n * i)

Output:-
LOOP FORMATION
#----Star Pattern – Right Angle Triangle----

n = int(input("Enter number of rows: "))

for i in range(1, n + 1):

print("*" * i)

# ----Inverted triangle-----

n = int(input("Enter number of rows: "))

for i in range(n, 0, -1):

print("*" * i)

Output:-
NUMBER IS POSITIVE, NEGETIVE,
ZERO

num = float(input("Enter a number: "))

if num > 0:

print("Positive")

elif num < 0:

print("Negative")

else:

print("Zero")

Output:-
MERGING TWO LISTS
a = input("Enter first list: ").split()

b = input("Enter second list: ").split()

merged = a + b

print("Merged list:", merged)

Output:-
COUNTING VOWELS AND
CONSONENTS
text = input("Enter a string: ").lower()

vowels = 0

for v in text:

if i in 'aeiou':

vowels += 1

print("Vowels:", vowels)

print("Consonants:", len(text) - vowels)

Output:-
NUMBER IS EVEN/ODD
num = int(input("Enter a number: "))

if num % 2 == 0:

print("Even number")

else:

print("Odd number")

Output:-
CHECKING NUMBER IS PRIME OR
NOT PRIME
num = int(input("Enter a number: "))

if num > 1:

for i in range(2, num):

if num % i == 0:

print("Not Prime")

break

else:

print("Prime Number")

else:

print("Not Prime")

Output:-
RANGE BASED PROGRAMS
# Program based on range() in Python

# 1 Print numbers from 1 to 10

print("Numbers from 1 to 10:")

for i in range(1, 11):

print(i, end=" ")

print("\n")

# 2 Print even numbers from 2 to 20

print("Even numbers from 2 to 20:")

for i in range(2, 21, 2):

print(i, end=" ")

print("\n")

# 3 Print numbers in reverse from 10 to 1

print("Numbers from 10 to 1 in reverse:")

for i in range(10, 0, -1):

print(i, end=" ")

print("\n")

Output:-
LCM OF TWO NUMBERS
a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

def gcd(x, y):

while y:

x, y = y, x % y

return x

lcm = a * b // gcd(a, b)

print("LCM =", lcm)

Output:-
FREQUENCY OF ANY NUMBER

text = input("Enter a string: ")

freq = {}

for ch in text:

freq[ch] = [Link](ch, 0) + 1

print(freq)

Output:-
TO FIND THE LARGEST AND
SMALLEST NUMBER

a=list (input("Enter a List:"))

print(a)

print("Maximum value of list" ,max(a))

print("Minimum value of list" ,min(a))

Output:-
SUM OF ELEMENTS IN A LIST

lst = input("Enter elements of list separated by space: ").split()

lst = [int(i) for i in lst]

total = sum(lst)

print("Sum of list elements:", total)

Output:-
SEARCHING AN ELEMENT FROM A
DICTIONARY
student = {

"Rahul": 85,

"Aman": 90,

"Neha": 88,

"Anshu":94,

"Suryansh":95,

"Akshansh":95}

name = input("Enter name to search: ")

if name in student:

print("Marks:", student[name])

else:

print("Student not found")

Output:-
PROGRAM BASED ON EXCEPTION
HANDLING
try:

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

c=a/b

print("Result:", c)

except ZeroDivisionError:

print("Division by zero is not allowed")

except ValueError:

print("Please enter valid numbers")

Output:-

You might also like