0% found this document useful (0 votes)
44 views

Python RR

The document provides Python code examples to demonstrate various Python programming concepts like input/output, conditional statements, strings, lists, tuples, dictionaries, functions, exceptions, files, NumPy, Pandas, Matplotlib and regular expressions. The code covers basic syntax and usage of these concepts through small programs and functions with appropriate comments.

Uploaded by

Rachna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Python RR

The document provides Python code examples to demonstrate various Python programming concepts like input/output, conditional statements, strings, lists, tuples, dictionaries, functions, exceptions, files, NumPy, Pandas, Matplotlib and regular expressions. The code covers basic syntax and usage of these concepts through small programs and functions with appropriate comments.

Uploaded by

Rachna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

1.

Write a python program to demonstrate the following

(i)Input
(ii) print
(iii) sep attribute &End Attribute
(iv)replacement Operator({})

# input
name=input("Enter name of Student:")
marks=input("Enter Marks of Student:")

# print
print("name:",name,"marks:",marks)

#print with sep attribute


print("name:",name,"marks:",marks,sep="|")

#end attribute
print("name:",end="")
print(name)

#Replacement operator
print("hi!!!,{}.your {} marks.".format(name,marks))
Output:-
2.Demonstrate the following conditional statements in Python

(i) If
(ii) if else
(iii) if- elif- else

(i) if

number=20
if number>0:
 print("Number is Positive")

(ii) if – else

number=-20
if number>0:
 print("Positive Number")
else:
    print("Negative Number")

(iii) if-elif-else

number=0
if number>0:
  print("Positive Number")
elif number==0:
    print("Zero")
else:
    print("Negative Number")
Output:-
3.Demonstrate the following functions/methods which operates on strings in
Python with suitable examples:

(i) len( )

(ii) strip( )

(iii) rstrip( )

(iv) lstrip( )

( v) find( )

(vi) rfind( )

(vii) index( )

(viii) rindex().

(i) len( )

mylist=["black","orange","white", "pink","green","yellow"]
x=len(mylist)
print(x)

(ii) strip( )

name="  welcome to home"


str1=name.strip()
print(name)
print(str1)

(iii) rstrip( )

name="welcome to home   "


str1=name.rstrip()
print(name)
print(str1)
(iv) lstrip( )
name="  welcome to home   "
str1=name.lstrip()
print(name)
print(str1)

( v) find( )

msg="Python is progrmming language"


x=msg.find("is")
print(x)

(vi) rfind( )

msg="Python is progrmming language"


x=msg.rfind("r")
print(x)

(vii) index( )

msg="Python is progrmming language"


x=msg.index("p", 3,15)
print(x)

(viii) rindex()

msg="Python is progrmming language"


x=msg.rindex("p",5,12)
print(x)
Output:-
4. Write a program to create List, Tuple and Dictionary.

(i) List
my_list1=[1,2,"ram","sita", 3.14]
my_list2=["apple","banana","emma"]
#print the list
print(my_list1)
print(my_list2)
#print type of list
print(type(my_list1))
print(type(my_list2))
# List index
print(my_list1[0])
#append
my_list2.append("mango")
print(my_list2)
#Reverse()
my_list1.reverse()
print(my_list1)

(ii) Tuple
my_tuple1=(1,2,"ram","sita", 3.14)
my_tuple2=("apple","banana","emma")
my_tuple4=("apple")
#print the tuple
print(my_tuple1)
print(my_tuple2)
#print type of tuple
print(type(my_tuple1))
print(type(my_tuple2))
# tuple index
print(my_tuple1[2])
#tuple containg duplicate
my_tuple2=("apple","banana","emma","apple")
print(my_tuple2)
#concatenating tuples
print(my_tuple1 + my_tuple2)
#nesting of tuple
my_tuple=(my_tuple1,my_tuple2)
print(my_tuple)
#Repition of tuple
my_tuple4=("apple",)*5
print(my_tuple4)
#code slicing
print(my_tuple1[1:])

(iii) Dictionary
my_dict = {"apple": 3, "banana": 5, "orange": 2}
# Creating a dictionary using dict() function
another_dict = dict(name="Rachna", age=23, city="sirsa")
# Printing the dictionaries
print(my_dict)
print(another_dict)
print(my_dict["apple"])  
print(another_dict["name"])
my_dict["apple"] = 5
# Modifying the value of an existing key
my_dict["Kiwi"] = 9
# Adding a new key-value pair
print(my_dict)
Output:-
5.Write a function to generate square of first n natural Numbers.

def g_square(n):
    squares = []
    for i in range(1, n+1):
        squares.append(i ** 2)
    return squares
squares = g_square(10)
print(squares)
Output:-
6. Demonstrate the following kinds of Parameters used while writing functions in
Python.

(i)Positional Parameters

(ii) Default Parameters

(iii)Keyword Parameter

(iv) Variable length Parameters

(i)Positional Parameters

def power(a,b):
 print("result= ", a ** b)
 
power(5,7)

(ii) Default Parameters

def add(a,b,c=6):
 sum=a+b+c
 print("sum is: ",sum)
 
add(2,4,8)

(iii)Keyword Parameter

def info(name,age):
    print(f"name is {name} and age is {age}")
   
info(name="rachna", age=23)
info(age=23,name="rachna")
(iv) Variable length Parameters

def add(*num):
  z=num[0]+num[1]+num[2]
  print("addition is=:", z)
 
add(5,6,9)
Output:-
7. Demonstrate lambda functions in Python with suitable example programs.

#sort a list of tuple using lambda


subject_marks=[('Datastructure',65),('Web developement',60),('java',55),
('Python',60)]
print("original list of tuple")
print(subject_marks)
subject_marks.sort(key=lambda x :x[1])
print("sorting list of tuple: \n")
print(subject_marks)
Output:-
8. Write a Regular Expression to represent all 10 digit mobile numbers. Rules: 1.
Every number should contains exactly 10 digits. 2. The first digit should be 7 or 8
or 9 Write a Python Program to check whether the given is valid or Not.

import re

def validate_mobile_number(number):
    pattern = r'^[789]\d{9}$'
    if re.match(pattern, number):
        return "Valid"
    else:
        return "Invalid"

number = "705683389213"
result = validate_mobile_number(number)
print(result)
Output:-

9. Write a program to implement multilevel and multiple inheritance.


class Father():
 def Driving(self):
    print("Father enjoy Driving")
class Mother():
    def Cooking(self):
        print("Mother enjoy cooking")
class Child(Father,Mother):
    def Playing(self):
        print("Child love playing")
c=Child()
c.Driving()
c.Cooking()
c.Playing()

class Employees():
 def Name(self):
     print ("Employee Name: Rachna")
class salary(Employees):
 def Salary(self):
    print ("Salary: 10000" )
class Designation(salary):
   def desig(self):
     print ("Designation: Test Engineer")
e = Designation()
e.Name()
e.Salary()
e.desig()
Output:-
10.Write a program to write “to a file and to read from file”

file_path="./my_file.txt"
text="Welcome to my home. \n"
#writing to a file
with open(file_path,"w")as f:
    f.write(text)
   
   
    #read data from that file
with open(file_path, "r") as f:
        print(f.readline())
   
Output:-
11. Demonstration of exception handling
try:
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))

    result = num1 / num2


    print("Result:", result)

except ValueError:
    print("Invalid input. Please enter a valid number.")
   
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
   
except Exception as e:
    print("An error occurred:", str(e))
Output:-
12. Basic operations of NumPy.

import numpy as np

def perform_operations(array1, array2):


    # Addition
    addition_result = np.add(array1, array2)
    print("Addition result:")
    print(addition_result)

    # Subtraction
    subtraction_result = np.subtract(array1, array2)
    print("Subtraction result:")
    print(subtraction_result)

    # Multiplication
    multiplication_result = np.multiply(array1, array2)
    print("Multiplication result:")
    print(multiplication_result)

# arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Perform operations on the arrays


perform_operations(arr1, arr2)
Output:-
13. Basic operations of Pandas
import pandas as pd

# Create a DataFrame
data = {'Name': ['Sita', 'Geeta', 'Ram', 'Sham'],
        'Age': [25, 28, 30, 27],
        'City': ['Sirsa', 'Hissar', 'Fathebad', 'Jind']}
df = pd.DataFrame(data)

# Display the DataFrame


print("Original DataFrame:")
print(df)

# Accessing columns
print("\nAccessing columns:")
print(df['Name'])
print(df.Age)

# Accessing rows
print("\nAccessing rows:")
print(df.loc[1])  # Access row by label
print(df.iloc[2])  # Access row by index

# Filtering data
print("\nFiltering data:")
filtered_df = df[df['Age'] > 26]
print(filtered_df)

# Adding a new column


df['Country'] = ['Rohtak', 'xyz', 'mmm', 'ssss']
print("\nDataFrame with a new column:")
print(df)

# Aggregating data
print("\nAggregating data:")
print(df.groupby('City')['Age'].mean())
# Sorting data
sorted_df = df.sort_values('Age', ascending=False)
print("\nSorted DataFrame:")
print(sorted_df)

# Dropping columns
df.drop('Country', axis=1, inplace=True)
print("\nDataFrame after dropping a column:")
print(df)
Output:-
14. Basic operations of Matplotlib.

import matplotlib.pyplot as plt


import numpy as np

x = np.arange(0, 3 * np.pi, 0.1)


y = np.sin(x)

plt.plot(x, y)
plt.show()
Output:-

You might also like