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

PPS Micro

The document discusses various programming concepts in Python, including functions, string methods, object-oriented programming, and file handling. It provides examples of how to define functions, use lambda expressions, and implement classes with attributes and methods. Additionally, it explains the differences between local and global variables, as well as the significance of the init() method in class definitions.

Uploaded by

vedvalunj07
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 views3 pages

PPS Micro

The document discusses various programming concepts in Python, including functions, string methods, object-oriented programming, and file handling. It provides examples of how to define functions, use lambda expressions, and implement classes with attributes and methods. Additionally, it explains the differences between local and global variables, as well as the significance of the init() method in class definitions.

Uploaded by

vedvalunj07
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
You are on page 1/ 3

Q.1) Define a function with suitable string.

method of Employee class is called The file path is also called as


example? Explain need for a function Example uing object of Company Employee pathname.
Ans ~ A function is a block of s="Welcome:to:Python" class For example c:\MyPythonPrograms
organized and reusable program code print(s.split(":")) - Also, In Constructor of Company displayStrings.py is a pathname. In
that perform single, specific, and well O/P Employee. Employee constructor is this path name C:\ is a root folder in
defined task. Python enables its ['Welcome', 'to', 'Python'] called to set name and salary which the sub- folder
programmer to break up a program attributes. MyPythonProgram has a file called
into functions, each of which can be zfill : It return the string with zeros left Q.14) Write a python program that displayStrings.py
written more or less independent of padded to the total width of string. uses class to store exam number and The character used in the pathname
each other. Therefore, the code of Example marks of four subjects. Use list to is called delimiter.
one function is completely insulated s="Python" store the marks of four subjects. Concept of Relative and Absolute
from the codes of the other function. print(s.zfill(15)) Path:
 A function f that uses another O/P class Student: The absolute path is a complete path
function g is known as the calling 000000000Python def _init_(self, exam_number, from the root directory.
function and g is known as the called marks): For example the path
function. Rindex ~ This is function of string self.exam_number = C:\MyPythonPrograms\Strings\
Syntax : datatype to find right must exam_number displayStrings.py is an absolute path
def <space> <function_name> occurrence of sub string. self.marks = marks using which the file can be located.
(<parameters>): Example The relative path is a path towards
return <variables to be returned> S="This is good college" def display_info(self): the file from the current working
Example : print (S.rindex("is") print(f"Exam Number: directory. For example –
def add(a,b) : O/p – 5 {self.exam_number}") \Strings\displayStrings.py can be a
c = a+b Q.8) Write a python program to print("Marks in four subjects: ", relative path if you are currently in the
return c display tables from 1 to 10 using end="") working directory C:\MyPython
c = add(10,20) formatting character. print(", ".join(map(str, Programs
print(―The Addition of two number is : def display_tables(): self.marks))) Q.21) Write a python program that
,c) for i in range(1, 11): number and marks in four subjects counts the number of tabs and new
o/p print(f"Multiplication Table for student1 = Student(12345, [85, 90, 78, line characters in a file.
The Addition of two number is : 30 {i}") 92])
Q.2) Explain Lambda function with for j in range(1, 11): student1.display_info() With open(―one.txt‖,‖r‖) as f1:
example. print(f"{i} x {j:2} = {i * j:2}") O/P Contents = f1.readline()
 Python Lambda Functions are print("-" * 20) Exam Number: 12345 Print(―new line count =‗‘,
anonymous function means that the display_tables() Marks in four subjects: 85, 90, 78, 92 len(contents)‖)
function is without a name. As we O/P Q.15) Explain following Terms: Total_tab = 0
already know that the def keyword is a.Data Abstraction & Encapsulation For line in contents :
used to define a normal function in Q.9) Explain following string methods b.Polymorphism Total_tab+ = line count(― ―)
Python. Similarly, the lambda with example c.Inehritance Total_tab+= line.count(―/t‖)
keyword is used to define an i)Enumerate d.Abstract method and class Print(―tab count =― total_tab)
anonymous function in Python. ii)1 strip ~ Encapsulation: # output
 Notice that the anonymous function ~ lstrip()- remove all leading 1) It is the process of binding New line count =3
does not have a return keyword. This whitespace in string. together the methods and data Tab count =4
is because the anonymous function Syntax- string.lstrip(characters) variables as a single entity i.e. Q.22) Write a python program to
will automatically return the result of Example- class. It hides the data within the display current directory, create
the expression in the function once it s=" Hello" class and makes it available only directory and remove created
is executed. print(s.lstrip()) through the methods. directory.
Syntax : output- Hello Or It is the process of wrapping up of
lambda argument(s) : expression data (properties) and behavior Code- import os
Example: Enumerate~ This function is used to (methods) of an Path= os.getcwd()
a=int(input("Enter the first number.")) do iteration on index as well as object into a single unit and the unit Print(―the current working directory is
b=int(input("Enter the secod element of a list or string together. is called a Class. ―, path)
number.")) Example- 2) Encapsulation enables data hiding, Dir_name = ‗temDir‘
x=lambda a,b: a b l=[1,5,3] hiding irrelevant information from Os.mkdir(dir_name)
print("The Multiplication of two print ("Index and element of list") users of a class and Print(―new directory is created ‖)
numbers is:",x(a,b)) for index , element in enumerate(l): exposing only the relevant details Os.rmdir(dir_name)
# Output: print (index, element) required by the user. Print(―new directory is deleted ‖)
Enter the first number.12 S="pou" ~ Polymorphism: O/P
Ans: Enter the secod number.15 The print ("Index and element of string") 1) This is a Greek word. If we break Current working directory is
Multiplication of two numbers is 180 for index , element in enumerate(s): the term Polymorphism, we get /name/chinmay/python_jupyter/pytho
Q.3) Write python program using print (index, element) ―poly‖-many and N_book
function to find greatest of three O/P ―morph‖-forms. So Polymorphism New dictionary is created
numbers by passing numbers as Index and element of list means having many forms. In OOP it New directory is deleted
argument. 01,15,23 refers to the Q.23) Differentiate between text and
def find_greatest(a, b, c): Index and element of string functions having the same names but binary files. Explain any 4 access
if a > b and a > c: 0P,10,2u carrying different functionalities. modes used in python.
return a Q.10) Write python, program to find 2) It allows one interface to be used ___________Text files___________
elif b > c: whether a given character is present for a set of actions. It means same ~ Data is present in the form of
return b in a string or not. In case it is present function name(but characters.
else: print the index at which it is present. different signatures) being used for ~ The plain text is present in the file
return c Do not use built in string method. different types. ~ It can not be corrupted easily.
~ Data Abstraction: ~ It have the extension such as py or
num1 = 10 def find_character(string, char): 1) Data abstraction means .txt
num2 = 25 for index in range(len(string)): representing only essential features ___________Binary files_________
num3 = 15 if string[index] == char: by hiding all the implementation ~ Data is present in the encoded form
return index details. ~ The image, audio or text data can
greatest = find_greatest(num1, num2, return -1 2)The class is an entity used for data be present in the file
num3) input_string = input(" hello world") abstraction purpose. ~ Even if single bit is changed then
print(f"The greatest number among character_to_find = input("0") ~ Inehritance: the file gets corrupted.
{num1}, {num2}, and {num3} is index = find_character(input_string, 1) In OOP inheritance is just like real ~ It can not read using the text editor
{greatest}.") character_to_find) world inheritance. like Notepad
O/P if index != -1: 2)Here child class inherits properties
from a parent or base class. ‗‘Rb+‖ : this mode allows reading and
The greatest number among 10, 25, print(f"The character
3)Methods of parent class can be writing here also reference is palace
and 15 is 25. '{character_to_find}' is present at
directly accessed in child class as start of the file
Q.4) Differentiate between Local & index {index}.") ―Ab+‖ : here appending and reading
else: 4)Also all public variables of parent
Global variable. Write a python both are allowed file references is
print(f"The character class are accessible.
program to demonstrate difference always at the end of the file
'{character_to_find}' is not present in ~ Class methods:
between local and global variable. ―Ab‖ : this mode for appending in text
the string.") 1)Class methods are also known as
___________Local variable_________ file here file reference Is at the end of
O/P static methods.
~ A variable which is declared inside the file . All new content are written at
Enter the string: hello world 2)These are bound to class.
a function is called as local variable. the end of the file
Enter the character to find: o 3)So, they can be called directly by
~ Accessibility of variable is only ―Rb‖ : it is read mode here file is
The character 'o' is present at index 4. using class name. No need to create
within the function in which it is opened for reading ONLY
-If no constructor is specified in object to call these methods.
declared.
Q.16) With the help of an example classthen python creates a default ~ The local variable is created when
explain the significance of the init( ) constructor the function(in which it is defined)
method. Example. starts executing and it is destroyed
~ In python "init (self) this is class sample: when the execution is complete.
compulindy nome of classVartable=0 ~ It is preferred as local variables are
the constructor def_init_(self): more reliable. Because the values
This is a unique function in class Q.11) Write a python program to cannot be changed outside the
-If no constructor is specified in class check whether a given string starts function.
self.lnstance_var=0 with specified character. __________Global variable_________
S= sample() ~ A variable that is declared outside
print ("value of instance variable is" def starts_with_char(string, char): the function is called global variable.
,s Instance _var) print("Value of class if not string or not char: ~ Accessibility of variable is
variable is", Sample.class Vaciable) return False throughout the program. All functions
O/P return string[0] == char in the program can access the global
Value of instance variable is 0 input_string = input("Hello ") variable.
Value of class variable is 0 input_char = input("H") ~ The global remains throughout the
Q.17) Write a python program to if starts_with_char(input_string, entire program execution.
create class car with two attributes input_char): ~ It is generally not preferred as any
name & cost. Create two objects and print(f"The string '{input_string}' function can change the values of
display information. starts with '{input_char}'.") global variable.
else: global_var = "I am a global variable"
class car: print(f"The string '{input_string}' def demonstrate_scope():
def_init_(self,name,cost) does not start with '{input_char}'.") local_var = "I am a local variable"
self.name=name O/P print(local_var)
self.cost=cost The string 'Hello' starts with 'H'. print(global_var)
def display (self): Q.12) Define programming paradigm. global global_var
print(self.name, self.cost) List programming paradigms. Explain global_var = "I have been modified
car_list=[ ] any one. globally"
no=int (input("Enter no of cars")) ~ A programming paradigm is a print(global_var)
for i in range (no): fundamental style of programming demonstrate_scope()
name=input ("Enter name of the that defines how the structure print(global_var)
car") and basic elements of a computer O/P
Cost=input("Enter cost of the car'') program will be built. I am a global variable
temp_car=car (name.cast) List of programming paradigm- I am a local variable
car_list.append (temp_car) 1) Monolithic programming paradigm I am a global variable
print ("List of car detalls is --->") 2) Procedural programming paradigm I have been modified globally
for obg in car_list 3) Structured programmingparadigm Q.5) Explain keyword arguments in
obj.display() 4) Object Oriented Programming python. Write a python program to
Q.18) Write a python program that paradigm demonstrate keyword arguments.
reads data from one file and write into 1. Monolithic programming- ~ Keyword arguments are also called
another file and line by line. -Monolithic means formed of single as named arguments.
block. ~ These are the arguments in which
With open (―one.txt‖ , ―r‖) as f1: -Here complete program is written as the values are associated with the
Contents=f1.readline() a sequence. names. Hence the positions of the
With open(―two.txt‖,‖w‖) as f2: 2. Procedural programming- arguments does not matter.
For line in contents: * Here program is divided in
F2.write(line) procedures or module or functions. def describe_pet(animal_type,
Print(―completed‖) * Function is a small unit of pet_name, age=None):
Output programming logic """Display information about a
Completed 3. Structured programmingParadigm- pet."""
Q.19) What is directory? List any four -This is improved/ advanced version print(f"\nI have a {animal_type}.")
directory methods and explain any of procedural language. It contains print(f"My {animal_type}'s name is
two of them. top downmodular {pet_name}.")
~ Is collection of file or dictionaries it approach, control structure, function if age:
is used to organise the file system in oriented programming. print(f"{pet_name} is {age} years
systematic manner -Here program is written in a old.")
Methods on directory- structured format compulsorily. describe_pet('hamster', 'Harry')
1)view current directory—os.getbud() 4. Object Oriented Programming describe_pet(animal_type='dog',
2)create directory —os.mkdir() (OOP) Paradigm- pet_name='Willie')
3) delete directory—os.rmdir() * Here data is major focus. (Function describe_pet('cat',
4) change access rights of directory acts on data) pet_name='Whiskers')
—os.chmod() * Data and functions are put together describe_pet(animal_type='parrot',
Code- import os to avoid misuse or un-intentional pet_name='Polly', age=3)
Path= os.getcwd() modifications in data. O/P
Print(―the current working directory is Q.13) Justify the statement I have a hamster.
―, path) ―Inheritance helps to make reusable My hamster's name is Harry.
Dir_name = ‗temDir‘ code‖. I have a dog.
Os.mkdir(dir_name) ~ In oop inheritance is just like real My dog's name is Willie.
Print(―new directory is created ‖) world inheritance. I have a cat.
Os.rmdir(dir_name) Here child class inherits properties My cat's name is Whiskers.
Print(―new directory is deleted ‖) from a parent of bace class I have a parrot.
O/P Methods of parent class can be My parrot's name is Polly.
Current working directory is directly acceued in child class Polly is 3 years old.
/name/chinmay/python_ - Also all public variables of parent Q.6) Write python program using
jupyter/python_book class are accessible. function to find whether number is
New dictionary is created It is used to re-use methods of parent odd or even.
New directory is deleted class easily. Constructor of parent num = int(input("Enter a number: "))
Q.20) Why do we need files? Explain class can be called within child class if (num % 2) == 0:
relative and absolute path in files. constructor so that data members of print("{0} is Even".format(num))
~ Definition File is a named location parent class can be set. else:
on the disk to store information. "super()" keyword is used to access print("{0} is Odd".format(num))
~ File is basically used to store the parent class constructor. O/P
information permanently on - In python all classes are child class Enter number 43
secondary memory. of "object" dass. 43 is odd
~ Due to this, even if the computer is - Example Enter number 18
switched off, the data remains In following code Company Employee 18 is even
permanently on secondary memory is a class which inherite Employee Q.7) Explain following string methods
(hard disk). Hence it is called class. with example. i) Rindex ii) Z fill iii)
persistent data structure. -So CompanyEmployee object can Split
~ Every file is located by its path. This now access public data and methods split() : It takes one argument. The
path begins at the root folder. In from Employee class. string is then split around every
windows it can C:\, D:\ or E;\etc. In this example display Employee() occurrence of the argument in the

You might also like