Ques Python
Ques Python
Types of arguments
There may be several types of arguments which can be passed at the time of function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
As far as the required arguments are concerned, these are the arguments which are required to be passed at the
time of function calling with the exact match of their positions in the function call and function definition. Consider
the following example.
Example 1
1. def func(name):
2. message = "Hi "+name
3. return message
4. name = input("Enter the name:")
5. print(func(name))
Output:
Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the
arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling and definition. If the
same match is found, the values of the arguments are copied in the function definition.
Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4.
5. #name and message is copied with the values John and hello respectively
6. func(name = "John",message="hello")
Output:
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not
provided at the time of function call, then that argument can be initialized with the value given in the definition even
if the argument is not specified at the function call.
Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john")
Output:
However, at the function definition, we define the variable-length argument using the *args (star) as *<variable -
name >.
Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
Output:
In the above code, we passed *names as variable-length argument. We called the function and passed values
which are treated as tuple internally. The tuple is an iterable sequence the same as the list. To print the given
values, we iterated *arg names using for loop.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope, whereas the variable defined inside a
function is known to have a local scope.
Output:
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed Output:
Output:
The sum is 60
Value of sum outside the function: 0
3. It simulates the real world entity. So real- It doesn't simulate the real
world problems can be easily solved world. It works on step by step
through oops. instructions divided into small
parts called functions.
Single inheritance
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:
dog barking
Animal Speaking
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
30
200
0.5
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.Everything in Python is an object, and almost everything
has attributes and methods.
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
1. class ClassName:
2. #statement_suite
Consider the following example to create a class Employee which contains two fields as Employee
id, and name.The class also contains a function display() which is used to display the information
of the Employee.
Example
1. class Employee:
2. id = 10;
3. name = "ayush"
4. def display (self):
5. print(self.id,self.name)
Here, the self is used as a reference variable which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function call.
1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above example.
Example
1. class Employee:
2. id = 10;
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. emp = Employee()
7. emp.display()
Output:
ID: 10
Name: ayush
Q What is a file? Explain methods to open, close,read and
write files in Python.
Opening a file
Python provides the open() function which accepts two arguments, file name and access mode in
which the file is accessed. The function returns a file object which can be used to perform various
operations like reading, writing, etc.
The files can be accessed using various modes like read, write, or append. The following are the
details about the access mode to open a file.
Example
Output:
<class '_io.TextIOWrapper'>
file is opened successfully
fileobject.close()
Example
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If
the count is not specified, then it may read the content of the file until the end.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. content = fileptr.read(9);
6.
7. # prints the type of the data stored in the file
8. print(type(content))
9.
10. #prints the content of the file
11. print(content)
12.
13. #closes the opened file
14. fileptr.close()
Output:
<class 'str'>
Hi, I am
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file
exists.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.
Example 1
1. #open the file.txt in append mode. Creates a new file if no such file exists.
2. fileptr = open("file.txt","a");
3.
4. #appending the content to the file
5. fileptr.write("Python is the modern day language. It makes things so simple.")
6.
7.
8. #closing the opened file
9. fileptr.close();
File.txt:
1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.
OPERATOR DESCRIPTION SYNTAX
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
Output:
13
5
36
2.25
2
1
2. Relational Operators: Relational operators compares the values. It either True or False according
to the condition.
OPERATOR DESCRIPTION SYNTAX
> Greater than: True if left operand is greater than the right x>y
< Less than: True if left operand is less than the right x<y
Greater than or equal to: True if left operand is greater than or equal
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output:
False
True
False
True
False
True
3. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOToperations.
And Logical AND: True if both the operands are true x and y
print(a and b)
print(a or b)
print(not a)
Output:
False
True
False
4. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
| Bitwise OR x|y
~ Bitwise NOT ~x
print(~a)
print(a ^ b)
print(a >> 2)
A function can be defined as the organized block of reusable code, which can be called whenever required.
The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively
and avoids the repetition of the code. As the program grows, function makes the program more organized.
o User-define functions - The user-defined functions are those define by the user to perform the specific
task.
o Built-in functions - The built-in functions are those functions that are pre-defined in Python.
o Using functions, we can avoid rewriting the same logic/code again and again in a program.
o We can call Python functions multiple times in a program and anywhere in a program.
o We can track a large Python program easily when it is divided into multiple functions.
o Reusability is the main achievement of Python functions.
It can accept any number of arguments and has only one expression. It is useful when the function objects are
required.
Example 1
1. x = lambda a:a+10
2. print(x)
3. print("sum = ",x(20))
Output:
In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument
and a+10 is an expression. The given expression gets evaluated and returned the result.
1. Parameterized Constructor
2. Non-parameterized Constructor
1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()
Output:
Output:
The regular expressions can be defined as the sequence of characters which are used to search for
a pattern in a string. The module re provides the support to use regex in the python program. The
re module throws an exception if there is some error while using the regular expression.
1. import re
Regex Functions
The following regex functions are used in the python.
SN Function Description
1 match This method matches the regex pattern in the string with the
optional flag. It returns true if a match is found in the string
otherwise it returns false.
4 split Returns a list in which the string has been split in each
match.
Example
Split at each white-space character:
import re
Example
Replace every white-space character with the number 9:
import re
The9rain9in9Spain
You can control the number of replacements by specifying the count parameter:
Example
Replace the first 2 occurrences:
import re
The9rain9in Spain
Q Explain findall in Regular expression.
Example
Print a list of all matches:
import re
['ai', 'ai']
The list contains the matches in the order they are found.
Example
Return an empty list if no match was found:
import re
[]
No match
Output :
Output :
enter the no.5
The number is 5
Q Appraise the use of try block and except block in Python with
syntax.
If the python program contains suspicious code that may throw the exception, we must place that code in the
try block. The try block must be followed with the except statement which contains a block of code that will
be executed if there is some exception in the try block.
We can also use the else statement with the try-except statement in which, we can place the code which will
be executed in the scenario if no exception occurs in the try block.
Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except Exception:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")
Output:
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
Sys.maxsize
It returns the largest integer a variable can take.
import sys
sys.maxsize
OUTPUT:
2147483647
Sys.path
This is an environment variable that is a search path for all Python modules
import sys
sys.path
OUTPUT:
['C:/Users/Rajni/AppData/Local/Programs/Python/Python38-32', 'C:\\Users\\Rajni\\AppData\\Local\\
Programs\\Python\\Python38-32\\lib\\site-packages']
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("John")
OUTPUT:
Hello john
When you have imported the math module, you can start using methods and constants of the module.
The math.sqrt() method for example, returns the square root of a number :
import math
x = math.sqrt(64)
print(x)
Output: 4
The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method
rounds a number downwards to its nearest integer, and returns the result:
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is
shown by the ().
3 The List has the variable length. The tuple has the fixed length.
4 The list provides more functionality than The tuple provides less functionality
tuple. than the list.
5 The list Is used in the scenario in which we The tuple is used in the cases where
need to store the simple collections with no we need to store the read-only
constraints where the value of the items can collections i.e., the value of the
be changed. items can not be changed. It can be
used as the key inside the
dictionary.
In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'
while loops
for loops
Example
i = 1
while i< 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while condition is true:
Example
i = 1
while i< 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and continue with the next:
Example
i = 0
while i< 6:
i += 1
if i == 3:
continue
print(i)
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).
This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
The for loop does not require an indexing variable to set beforehand .
Q Define variable and what are the rules for creating variables in
Python.
A variable in python gives data to the computer for processing. It is a reserved memory location to
store values.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Installation on
Difficult to install on Windows Easy to install on Windows
Windows
Scope of Variables are accessible even outside The scope of variables is limited
Variable the loop within the loops
Python programs are saved with C++ programs are saved with the
Extension
the .py extension .cpp extension
Python keywords are special reserved words that have specific meanings and purposes and can’t be used for
anything but those specific purposes.