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

Python Unit I Notes

The document provides a comprehensive overview of Python programming, covering key concepts such as comments, the Python Virtual Machine, data types, operators, and variable scope. It includes both short and long answer questions, detailing features of Python, flavors, and various data types, along with examples and syntax. Additionally, it explains the purpose of membership operators, input functions, and user-defined functions, among other fundamental topics in Python.

Uploaded by

Saraswathi
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)
12 views

Python Unit I Notes

The document provides a comprehensive overview of Python programming, covering key concepts such as comments, the Python Virtual Machine, data types, operators, and variable scope. It includes both short and long answer questions, detailing features of Python, flavors, and various data types, along with examples and syntax. Additionally, it explains the purpose of membership operators, input functions, and user-defined functions, among other fundamental topics in Python.

Uploaded by

Saraswathi
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/ 13

Python Programming

Two Mark questions


1. How to write a comment line in Python? Mention two types.
Ans: Single line comment: In python single line comment is represented using (#) symbol.
Ex:#Single line comment

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 “””

Ex: ’’’Multi line

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.

4. Give 2 step process of Python program execution


Ans: The execution of the Python program involves 2 Steps:
1. Compilation.
2. Interpreter.
5. List any four standard datatypes supported by Python.
Ans: Numeric, Sequence, Set, Mapping, None.
6. How to determine the data type of a variable? Give the syntax and example
Ans: The data type of any object can be determined by using the type() function.
x=5
print(type(x))
class<’int’>
7. What is the purpose of membership operators? Give example
Ans: The Python membership operators test for the membership of an object in a sequence,
such as strings, lists, or tuples. Python offers two membership operators to check or validate
the membership of a value.
The in operator is used to check if a character/substring/element exists in a sequence or not.
Evaluate to True if it finds the specified element in a sequence otherwise False.
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
# using membership 'in' operator
# checking an integer in a list
print(2 in list1)
# checking a character in a string
print('O' in str1)

8. How to input data in Python? Give syntax and example


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)

9. List four type conversion functions.


Ans: There are two types of Type Conversion in Python:
Python Implicit Type Conversion : Python interpreter automatically converts one data type to
another without any user involvement.
Python Explicit Type Conversion : The data type is manually changed by the user as per their
requirement.
Converting integer to float
Python Type conversion using tuple(), set(), list()
Python code to demonstrate Type conversion using dict(), str()
Convert ASCII value to characters
10. List any four categories of Operators in Python.
Ans: Operators in general are used to perform operations on values and variables.
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Identity Operators
 Membership Operators
11. What is indentation? Why it is required?
Ans: Indentation refers to the spaces at the beginning of a code line.
The indentation in Python is very important.
Python uses indentation to indicate a block of code.
The number of spaces is up to you as a programmer, but it has to be at least one.
You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error.

12. Give syntax of if ..elif statement in Python


Ans: Here block of code that will execute if the condition(s) associated with an if statement
evaluate to False. Else block provides a way to handle all other cases that don't meet the
specified conditions.
Syntax:
#if <condition> :
#Block of statements
#End of block of statements
#else:
#Block of statements
#End of block of statements
#Statement outside the if...else statement

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.

14. What are the rules for naming identifiers?


Ans: Identifier name must start with a letter or the underscore character
Identifier name cannot start with a number
Identifier name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Identifier names are case-sensitive (age, Age and AGE are three different variables)
Identifier name cannot be any of the Python keywords.

15. What is an identifier? Give example


Ans: Identifier is a user defined word, which is used to identify program entity or program
elements. Such as variable name, function name, class name, module name, constant name

16. What are python keywords? Give example


Ans: Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers: while, for, int, etc.

17. What are python Variables?


Ans: Variables are containers for storing data values. Python has no command for declaring a
variable. A variable is created the moment you first assign a value to it.
18. What are the rules for naming variables?
Ans: A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
19. Give syntax and example for assigning values to variables
Ans: Ex: x = 5
y = "John"
a=4
A = "Sally"
#A will not overwrite a
myvar = "John"
my_var = "John"
_my_var = "John"
myvar2 = "John"

20. Differentiate scope and life time of a variable.


Ans: A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the
global scope.
21. List any four built in functions in Python.
Ans: print()
input()
int()
append()
22. Give the Syntax of user defined function.
Ans: def functionname(parameter..) :
#block of statement
23. Give the syntax and example for range() function.
Ans: The syntax of range(10)
24. What is the meaning of name == main ?
Ans: Python interpreter reads source file and define few special variables/global variables. If
the python interpreter is running that module (the source file) as the main program, it sets the
special __name__ variable to have a value “__main__”
25. Give example of function returning multiple values.
Ans:
#Returning multiple value
def swapN(a,b):
return b,a
num1,num2 = 25,30
print(“Before swapping a is : “, num1,” b is: “, num2)
num1,num2=swapN(num1,num2)
print(“After swapping a is : “, num1,” b is: “, num2)
26. What is keyword argument? Give example
Ans: The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname=‘Course', lastname='Practice')
#Positional arguments
student(lastname='Practice', firstname=‘Course')

27. What is default argument? Give example


Ans: Python allows assigning a default value to the parameter. A default value is a value that is
predecided and assigned to the parameter when the function call does not have its
corresponding argument.
def fullname(firstname,lastname = ‘None’):
fullname=firstname+lastname
print(“Hello“, firstname)

first= input("Enter the firstname :")


last =input("Enter the lastname : ")
fullname(first, last)
fullname(‘John’)

28. Differentiate *args and **kwargs


Ans: We can define variableArgs function and we have single arguments and inside
function, we print a value and returns. Whenever we call the function, while we call one value in
the 10 and 10 will be placed in a and it will display 10. Suppose we pass 2 arguments i.e(10,20),
then to collect these two arguments we need to define 2 variables, if we not whenever we try to
execute it throws the error.

Long Answer Questions

1. Explain any five features of Python.


Ans: 1. Simple: Python is easy to use and high level language. It is programmer friendly language.
2. Interpreted Language: Python is an interpreted language. i.e, interpreter executes the code
line by line at a time. This makes debugging easy and thus suitable for the beginners.
3. Cross-platform language: Python can run easily on different platforms such as windows,
Linux, Unix, Macintosh etc. Thus, Python is a portable language.
4. Free and open source: Python is freely available. The source code is available. The source
code is also available. Therefore it is open source.
5. Object-oriented language: Python supports object oriented language. Concept of classes
and objects comes into existence.
6. Large Standard Library: Python has a large and broad library.
7. General Purpose Programming language: Python is used for developing any type of
applications, that’s why we can say Python is a General Purpose Programing Language.

2. Explain any five 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.
3. Explain various data types in Python.
Classified into 4 categories:
1. Numeric int is a class
2. Sequences float is a class
3. Sets
4. Mappings set is a class
str is a class
…… same for other datatype

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)

6. Explain any five type conversion functions with example.


Ans: Data conversion functions in Python:
int() : Returns the specified input to integer type. On successfully conversion, it will return integer
value, if value is invalid or on failure it returns runtime error.
>>>num1 = int(3.5)
>>>num2 = int(“10”)
>>>print(“After Converting Float to integer the value is”, num1)
>>>print(“After Converting String to integer the value is”, num2)
OUTPUT:
After Converting Float to integer the value is: 3
After Converting String to integer the value is: 10

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

str(): Returns a string which is human readable form.


>>>int_to_str=str(10)
>>>print(int_to_str)
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

complex():Converts the specified integer value into complex.


>>>com_with_str=complex(“1”)
>>>com_with_num=complex(5,8)
>>> print(com_with_str)
>>>print(com_with_num)
(1+0j)
(5+8j)

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)

7. Explain while and for loops with syntax and example.


Ans:
While Loop:
Lets discuss about while loop execution in python programming. Here usage of while loop is very
simple in python. It is an iterator, to execute a block of statements repeatedly until a given condition
is True, If the condition becomes false, the Statement after the loop in the program is executed.

Python while loop syntax:


while condition:
#Block of code
......
……
#End Block of code
#Statement outside Loop

Simple while loop execution :


i=1 #Step1: initialize of variable
while(i<=5): #Step2: Define the condition
print("i value is :",i)#Step3: Perform logic
i+=1 #Step4: Update the sequence(increment of value)
print("Thank you for using while loop") #Statement outside while loop

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)

range(start, stop, step)


For Instance: if we just want to display from 1 to 10, so it means by default it increment value is 1,
so it will display value from 1 to 10. If we want to specify third argument we can specify, it means
how much we have to increment every step.

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

10. Explain *args and **kwargs with example


Ans:
The special syntax *args in function definitions is used to pass a variable number of arguments
to a function. It is used to pass a non-keyworded, variable-length argument list.
 For example, we want to make a multiply function that takes any number of arguments and is
able to multiply them all together. It can be done using *args.
 Using * the variable that we associate with the * becomes iterable, meaning you can do
things like iterate over it, run some higher-order functions such as map and filter, etc.
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'Python')

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))

fun("Hi", id1='1234', id2='1235', id3='1236')


11. With example explain keyword arguments and default arguments to the function.
Ans:
# Python program to demonstrate default arguments
def fullname(firstname,lastname = ‘None’):
fullname=firstname+lastname
print(“Hello“, firstname)

first= input("Enter the firstname :")


last =input("Enter the lastname : ")
fullname(first, last)
fullname(‘John’)

# Python program to demonstrate default arguments


def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)

# Python program to demonstrate Keyword Arguments


def student(course, duration):
print(firstname, lastname)
# Keyword arguments
student(course =‘BCA, duration =’3yrs’)
#Positional arguments
student(duration =’3yrs’, course =‘BCA)

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:

#Returning multiple value


def swapN(a,b):
return b,a
num1,num2 = 25,30
print(“Before swapping a is : “, num1,” b is: “, num2)
num1,num2=swapN(num1,num2)
print(“After swapping a is : “, num1,” b is: “, num2)

You might also like