Python Unit I Notes
Python Unit I Notes
Multiple comments: In python multiple line comment is represented using either (#) symbol at
beginning of each line or can be represented using triple single or double quotes ‘’’ or “””
Comments’’’
2. What is Python Virtual Machine?
Ans: The Python Virtual Machine, often referred to as the Python interpreter, is responsible
for executing Python code.
A function add that returns the sum of two numbers. It then calls this function with 3 and 5 as
arguments, storing the result in a variable result, and prints it.
3. List any four flavors of Python.
Ans: CPython: It is used in the C language programming.
Jython: It is for a Java Application. It can run on JVM.
Ironpython: It is for C# .Net Platform
PyPy: PyPy often runs faster than CPython because PyPy is a just-in-time compiler while
CPython is an interpreter.
13. What is the purpose of else suit in Python loops? Give example
Ans: If specified loop condition is true block of statement will execute, once the
condition is false, then control moves to else, else statement will be executed.
Numeric Datatypes:
Is used to reserve numbers in memory. Numbers such as integers, floating point numbers or real
number. To reserve these values we use Numeric Datatype. It is sub classified as:
1. int int is a class or a datatype. It reserves a memory for integer value of unlimited length in
Python 3.x version onwards. If we work lower version of python software i.e, Python 2.x, int
datatype is limited length, which will work similar to C programming language int, long datatype
where used.
2. long long integer is used to reserve memory for unlimited length of integer value. This
datatype exists only in Python 2.x version. In Python 3.x version long datatype doesn’t exists.
3. float float is used to reserve memory for decimal values/ floating point values, it is equivalent
to double in C language.
4. complex complex datatype is used to reserve memory for complex/real imaginary numbers.
Sequences: The data stored is organized in sequential form. Every sequential is called as collection,
which contains 0 or more values. As we know every datatype in python is one class. Here, data are
reserved in the memory in sequential order.
1. String (str class): str is used to represent as string. Any value declared using single/double/triple
quote, it will create an instance of string class. Thus string represents sequence of characters.
Python 2.6 – Supports Sequence of characters
Python 2.x – Supports only ASCII Code Characters (256 characters)
Python 3.6 – Supports UNICODE Characters (65536 Characters)
2. List: List is a collection of objects. We can store different types of objects. List is mutable data
type.
3. Tuple: Tuple is a collection of objects. We can store different types of objects. Tuple is an
immutable datatype.
Sets: It is an unordered collection of objects. There are two types of sets: Sets and Frozen sets. Set is
available as standard datatype in Python 2.6 version.
Mapping: Mapping datatype called Dictionary. Dictionary uses hash map or hash table, where data
is organized as a key and value pair.
4. Explain the Arithmetic operators, logical operators and relational operators with an
example.
Ans: Operators:
It represents computations like addition and multiplication. The values the operator is applied to are
called operands.
Arithmetic Operators
Addition Addition the two numeric values, and can >>> num1 = 5
(+) also be used to concatenate two strings on >>> num2 = 6
either side of the operator. >>>num1+num2 o/p: 11
>>> str1 = "Hello"
>>> str2 = "India"
>>> str1 + str2 o/p: 'HelloIndia'
Subtraction Subtracts the operand on the right from >>> num1 = 5
(-) the operand on the left. >>> num2 = 6
>>>num1- num2
Multiplication Multiplies the two values on both side of >>> num1 = 5
(*) the operator. Repeats the item on left of >>> num2 = 6
the operator if first operand is a string >>>num1* num2
and second operand is an integer value. 30
>>> str1 = 'India'
>>> str1 * 2
'IndiaIndia'
Division Divides the operand on the left by the >>> num1 = 8
(/) operand on the right and returns the >>> num2 = 4
quotient >>>num2/num1
0.5
Modulus Modulus the operand on the left by the >>> num1 = 13
(%) operand on the right and returns the >>> num2 = 5
remainder >>>num1%num2 o/p: 3
Floor Division Floor Divides the operand on the left by >>> num1 = 13
(//) the operand on the right and returns the >>> num2 = 4
quotient by removing the decimal part >>> num1 // num2 o/p: 3
(Integer division). >>> num2 // num1 o/p: 0
Exponential Performs exponential (power) calculation >>> num1 = 3
(**) on operands. That is, raise the operand on >>> num2 = 4
the left to the power of the operand on the >>> num1 ** num2
right 81
Relational Operator:
Logical AND If both the operands are True, then >>> True and True
condition becomes True True
>>> True and False
False
>>> False and False
False
>>> num1,num2 = 10,-20
>>> bool(num1 and num2)
True
>>> bool(num1 and num3)
False
Logical OR If any of the two operands are True, >>> True or True
then condition becomes True True
>>> True or False
True
>>> bool(num1 or num3)
True
>>> False or False
False
Logical NOT Used to reverse the logical state of >>> bool(num1) True
its operand >>> bool(not num1) False
Relational Operator:
Equal to: If the values of two operands >>>num1 == num2
are equal, then the condition False
is true, otherwise it is False. >>>str1 == str2
False
Not equal to : If the values of two operands >>> num1 != num2
are not equal, then the True
condition is true, otherwise it >>> str1 != str2
is False. True
Greater than: If the value of the left-side >>>num1 > num2
operand is greater than the True
value of the right-side >>> str1 > str2
operand, then condition is True
True, otherwise it is False.
Less than: If the value of the left-side >>>num1 < num2
operand is less than the value False
of the right-side operand, >>>str2 < str1
then condition is True, True
otherwise it is False.
Greater than or equal to: If the value of the left-side >>> num1 >= num2
operand is greater than or True
equal to the value of the >>> num2 >= num3
right-side operand, then False
condition is True, otherwise it
is False.
Less than or equal to: If the value of the left-side >>> num1 <= num2
operand is less than or equal False
to the value of the right-side >>> str1 <= str2
operand, then condition is False
True, otherwise it is False.
5. How to read different types of input from the keyboard. Give examples
Ans:
input () function first takes the input from the user and converts it into a string. The type of the
returned object always will be <class ‘str’>. It does not evaluate the expression it just returns
the complete statement as String.
# Python program showing
# a use of input()
val = input("Enter your value: ")
print(val)
float() :Returns the float value from the specified input. On successfully conversion, it will return
integer value or on failure it returns runtime error.
>>>num1 = float(3)
>>>num2 = float(“10”)
>>>print(“After Converting integer to float the value is”, num1)
>>>print(“After Converting String to float the value is”, num2)
OUTPUT:
After Converting integer to Float the value is: 3.0
After Converting string to Float the value is: 10
chr(): Converts the specified integer value into character whose ASCII code is same as the integer
using chr() function.
>>>ascii_to_char=chr(100)
>>>print(asci_to_char)
d
ord(): Returns an integer representing Unicode code point for the given Unicode character.
>>>unicode_int=ord(‘4’)
>>>unicode_char= ord(“#”)
>>>print(unicode_int)
>>>print(unicode_char)
For Loop:
It is an iterator, just used to execute block of instructions (or single instruction) as long as specified
condition is true.
Syntax:
for var in variable:
#Block of Statement
But here along with for loop usage we should learn about range() function also.
Here, we use the range() function, this is python library function. For loop always takes the
help of range() to iterate. For Instance:
What is the variable we have to iterate, or repeat with the loop that we have to specify here.
i.e, x in the range() function.
for x in range(10):
print(“x value is : “, x)
8. Give the syntax of range function. Explain use range function in for loop with examples.
Ans:
range() function: range(stop)
Here, Only one argument if we specify, that is a stop condition and if we don’t specify starting point
by default start will consider 0
Ex: range(10) => iterates from 0 to 9
range(start, stop)
For Instance I just want to display value from 5to 10 we have specify lower bound and upper bound.
If we specify lower bound as 5 and upper bound if we want to display value till 10 so we have to
specify upper bound as 11. So, then it will start printing from 5 and it will stop printing 10.
for x in range(5,11):
print(“x value is : “, x)
for x in range(1,11,1):
print(“x value is : “, x)
9. With syntax and example explain how to define and call a function in Python
Ans: Creating User Defined Function:
A function definition begins with def (short for define)
The syntax for creating a user defined function is as follows:
def <function_name>:
…………… #set of instructions to be executed.
…………..
return<value>
The items enclosed in "[ ]" are called parameters and they are optional. Hence, a
function may or may not have parameters. Also, a function may or may not return a
value.
Function header always ends with a colon (:).
Function name should be unique. Rules for naming identifiers also applies for
function naming.
The statements outside the function indentation are not considered as part of the
function.
#User defined function
def sumSquares(n): #n is the parameter
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)
num = int(input("Enter the value for n: "))
sumSquares(num) #function call
The special syntax **kwargs in function definitions is used to pass a variable length argument
list. We use the name kwargs with the double star **.
A keyword argument is where you provide a name to the variable as you pass it into the
function.
It collects all the additional keyword arguments passed to the function and stores them in a
dictionary.
def fun(arg1, **kwargs):
for k, val in kwargs.items():
print("%s == %s" % (k, val))
12. With example explain how command line arguments are passed to python program.
Ans:
import sys
def command():
print("You can use for loop to traverse through sys.argv")
for arg in sys.argv:
print(arg)
command()
13. How to return multiple values from a function definition? Explain with an example
Ans: