0% found this document useful (0 votes)
3 views53 pages

Ii MSC Python Unit I Notes

The document provides a comprehensive overview of programming using Python, covering key topics such as Python's features, data types, flow control, functions, modules, file handling, object-oriented programming, and regular expressions. It includes detailed explanations of Python's syntax, variable assignment, and standard data types, as well as practical applications like web development with Django. The document serves as a foundational guide for beginners and intermediate programmers looking to enhance their Python skills.

Uploaded by

RCW CS 18
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)
3 views53 pages

Ii MSC Python Unit I Notes

The document provides a comprehensive overview of programming using Python, covering key topics such as Python's features, data types, flow control, functions, modules, file handling, object-oriented programming, and regular expressions. It includes detailed explanations of Python's syntax, variable assignment, and standard data types, as well as practical applications like web development with Django. The document serves as a foundational guide for beginners and intermediate programmers looking to enhance their Python skills.

Uploaded by

RCW CS 18
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/ 53

PROGRAMMING USING PYTHON

UNIT - I: OVERVIEW
Introduction to Python: Features of Python - How to Run Python – Identifiers – Reserved
Keywords - Variables - Comments in Python - Indentation in Python - Multi-Line Statements -
Multiple Statement Group (Suite) – Quotes in Python - Input, Output and Import Functions -
Operators. Data Types and Operations: Numbers-Strings-List-Tuple-Set-Dictionary-Data type
conversion.
UNIT - II: FLOW CONTROL & FUNCTIONS
Flow Control: Decision Making-Loops-Nested Loops-Types of Loops. Functions: Function
Definition-Function Calling - Function Arguments - Recursive Functions - Function with
more than one return value.
UNIT - III: MODULES, PACKAGES AND FILE HANDLING
Modules and Packages: Built-in Modules - Creating Modules - import Statement – Locating
Modules - Namespaces and Scope - The dir() function - The reload() function - Packages in Python -
Date and Time Modules. File Handling: Opening a File - Closing a File - Writing to a File – Reading
from a File - File Methods - Renaming a File - Deleting a File – Directories in Python.
UNIT - IV: OBJECT ORIENTED PROGRAMMING
Class Definition - Creating Objects - Built-in Attribute Methods - Built-in Class Attributes -
Destructors in Python Encapsulation - Data Hiding- Inheritance - Method Overriding Polymorphism.
Exception Handling: Built-in Exceptions - Handling Exceptions – Exception with Arguments- Raising
Exception - User-defined Exception - Assertions in Python
UNIT - V: REGULAR EXPRESSIONS & WEB APPLICATIONS
Regular Expressions: The match() function - The search() function - Search and Replace -
Regular Expression Modifiers: Option Flags - Regular Expression Patterns – Character Classes -
Special Character Classes - Repetition Cases - findall() method - compile() method. Web Application
Framework- Django Architecture- Starting development- Case Study: Blogging App.
TEXTS
1. Jeeva Jose and P. SojanLal, “Introduction to Computing and Problem Solving with
Python”, Khanna Book Publising Co. (P) Ltd., 2016.
2. ArshdeepBahga, Vijay Madisetti, “Cloud Computing: A Hands – On Approach”
Universities press (India) Pvt. limited016.
PROGRAMMING USING PYTHON

CONTENTS

UNIT - 1
PAGE
CHAPTER TOPIC’S
NO
1.1 Python 1
1.1.1 Characteristics of Python 1
1.1.2 Applications of Python 2
1.1.3 Features of Python 2
1.2 Python Basic Syntax 4
1.2.1 Python First Program 4
1.3 Python identifier 5

1.4 Reserved words 5


1.5 Variables 6
1.5.1 Assigning Values to Variables 6
1.5.2 Multiple Assignment 7
1.5.3 Standard Data Types 7
Comments in Python
1.6 16

1.7 Indentation in Python 17

1.8 Multiline statement 20

Multiple Statement Group (Suite)


1.9 20
Quotes in Python
1.10 21

1.11 Input, Output and Import Functions 22


1.12 Operators 35
1.12.1 Types of Operator 35
1.12.2 Python Arithmetic Operators 36
1.12.3 Python Comparison Operators 37
1.12.4 Python Assignment Operators 38
1.12.5 Python Bitwise Operators 39
1.12.6 Python Logical Operators 41
1.12.7 Python Membership Operators 42
1.12.8 Python Identity Operators 42
1.12.9 Python Operators Precedence 43
1.13 Data types 45
1.13.1 Python Numbers 45
1.13.2 Python Strings 45
1.13.3 Python Lists 45
1.13.4 Python Tuples 46
1.13.5 Python Dictionary 46
1.14 Data type Conversion 46
DCS33-PROGRAMMING USING PYTHON UNIT I

1.1 Python

 Python is a high-level, interpreted, interactive and object-oriented scripting


language. Python is designed to be highly readable.
 It uses English keywords frequently where as other languages use punctuation, and it
has fewer syntactical constructions than other languages.

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it. This is similar to PERL and PHP.

 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

 Python is Object-Oriented − Python supports Object-Oriented style or technique of


programming that encapsulates code within objects.

 Python is a Beginner's Language − Python is a great language for the beginner-level


programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

1.1.1 Characteristics of Python

Following are important characteristics of Python Programming −

 It supports functional and structured programming methods as well as OOP.

 It can be used as a scripting language or can be compiled to byte-code for building large
applications.

 It provides very high-level dynamic data types and supports dynamic type checking.

 It supports automatic garbage collection.

 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

1 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

1.1.2 Applications of Python

Python is one of the most widely used language over the web.

 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.

 Easy-to-read − Python code is more clearly defined and visible to the eyes.

 Easy-to-maintain − Python's source code is fairly easy-to-maintain.

 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.

 Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.

 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.

 Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.

 Databases − Python provides interfaces to all major commercial databases.

 GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.

 Scalable − Python provides a better structure and support for large programs than shell
scripting.

1.1.3 Features of Python:

Python's features include −

 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
2 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT I

 Easy-to-read − Python code is more clearly defined and visible to the eyes.

 Easy-to-maintain − Python's source code is fairly easy-to-maintain.

 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.

 Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.

 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.

 Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.

 Databases − Python provides interfaces to all major commercial databases.

 GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.

 Scalable − Python provides a better structure and support for large programs than shell
scripting.

Python has a big list of good features, few are listed below −

 It supports functional and structured programming methods as well as OOP.

 It can be used as a scripting language or can be compiled to byte-code for building large
applications.

 It provides very high-level dynamic data types and supports dynamic type checking.

 It supports automatic garbage collection.

 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

3 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

1.2 Python Basic Syntax

 There is no use of curly braces or semicolon in Python programming language. It is


English-like language.
 But Python uses the indentation to define a block of code. Indentation is nothing but
adding whitespace before the statement when it is needed.

For example -

1. def func():
2. statement 1
3. statement 2
4. …………………
5. …………………
6. statement N

In the above example, the statements that are same level to right belong to the function.
Generally, we can use four whitespaces to define indentation.

1.2.1Python First Program

Python provides the facility to execute the code using few lines.

For example - Suppose we want to print the "Hello World" program in Java; it will take three
lines to print it.

public class HelloWorld


{
public static void main(String[] args)
{
// Prints "Hello, World" to the terminal window.
System.out.println("Hello World");
}
}

4 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

1.3 Python identifier

 A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
 Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language.
 Thus, Manpower and manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers −

 Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.

 Starting an identifier with a single leading underscore indicates that the identifier is
private.

 Starting an identifier with two leading underscores indicates a strongly private identifier.

 If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.

1.4 Reserved words

 Reserved words (also called keywords) are defined with predefined meaning and syntax
in the language. These keywords have to be used to develop programming instructions.
Reserved words can’t be used as identifiers for other programming elements like name of
variable, function etc.
 Following is the list of reserved keywords in Python 3

and except lambda with


as finally nonlocal while
assert false None yield
break for not
class from or
continue global pass

5 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

def if raise
del import return
elif in True
else is try

 Python 3 has 33 keywords while Python 2 has 30. The print has been removed from
Python 2 as keyword and included as built-in function.

1.5 Variables

 Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.

 Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.

 Therefore, by assigning different data types to variables, you can store integers,
decimals or characters in these variables.

1.5.1 Assigning Values to Variables

 Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable.

 The equal sign (=) is used to assign values to variables.

 The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.

For example

#!/usr/bin/python

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

6 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

print counter
print miles
print name

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively.

This produces the following result −

100
1000.0
John

1.5.2 Multiple Assignment

 Python allows you to assign a single value to several variables simultaneously.

For example − a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables.

For example − a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

1.5.3 Standard Data Types

 The data stored in memory can be of many types.

 For example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are used to define
the operations possible on them and the storage method for each of them.

7 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Python has five standard data types −

 Numbers

 String

 List

 Tuple

 Dictionary

Python Numbers

 Number data types store numeric values. Number objects are created when you assign a
value to them. For example −

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement.

The syntax of the del statement is − del var1[,var2[,var3[ ....,varN]]]]

You can delete a single object or multiple objects by using the del statement.

For example −del var del var_a, var_b

Python supports four different numerical types −

 int (signed integers)

 long (long integers, they can also be represented in octal and hexadecimal)

 float (floating point real values)

 complex (complex numbers)

Examples

Here are some examples of numbers −

8 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

 Python allows you to use a lowercase l with long, but it is recommended that you use only
an uppercase L to avoid confusion with the number 1. Python displays long integers with
an uppercase L.

 A complex number consists of an ordered pair of real floating-point numbers denoted by


x + yj, where x and y are the real numbers and j is the imaginary unit.

Python Strings

 Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes.

 Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.
9 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT I

 The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example −

#!/usr/bin/python

str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

The following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists

 Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]).

 To some extent, lists are similar to arrays in C. One difference between them is that all
the items belonging to a list can be of different data type.

 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The

10 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.

For example

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

The following result −

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Python Tuples

 A tuple is another sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.

 The main differences between lists and tuples are:

11 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

 Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed,
while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.

 Tuples can be thought of as read-only lists.

For example

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints the complete tuple


print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd print
tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples

This produce the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

12 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

tuple[2] = 1000 # Invalid syntax with tuple


list[2] = 1000 # Valid syntax with list

Python Dictionary

 Python's dictionaries are kind of hash table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs.

 A dictionary key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.

 Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]).

For example

#!/usr/bin/python

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']

13 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

['sales', 6734, 'john']

Dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order"; they are simply unordered.

Data Type Conversion

 It perform conversions between the built-in types. To convert between types, you simply
use the type name as a function.

 There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

S.No. Function & Description

1
int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

2
long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

3
float(x)

Converts x to a floating-point number.

4
complex(real [,imag])

Creates a complex number.

5
str(x)

Converts object x to a string representation.

14 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

6
repr(x)

Converts object x to an expression string.

7
eval(str)

Evaluates a string and returns an object.

8
tuple(s)

Converts s to a tuple.

9
list(s)

Converts s to a list.

10
set(s)

Converts s to a set.

11
dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.

12
frozenset(s)

Converts s to a frozen set.

13
chr(x)

Converts an integer to a character.

15 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

14
unichr(x)

Converts an integer to a Unicode character.

15
ord(x)

Converts a single character to its integer value.

16
hex(x)

Converts an integer to a hexadecimal string.

17
oct(x)

Converts an integer to an octal string.

1.6 Comments in Python

 A hash sign (#) that is not inside a string literal begins a comment.

 All characters after the # and up to the end of the physical line are part of the comment
and the Python interpreter ignores them.

Example

#!/usr/bin/python

# First comment

print "Hello, Python!" # second comment

Output

This produces the following result −

16 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments −

'''
This is a multiline
comment.
'''

1.7 Indentation in Python

 Python provides no braces to indicate blocks of code for class and function definitions or
flow control.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.

For example

if True:

17 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

print "True"
else:
print "False"

However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Thus, in Python all the continuous lines indented with same number of spaces would form a
block. The following example has various statement blocks −

#!/usr/bin/python

import sys

try:

# open file stream

file = open(file_name, "w")

except IOError:

print "There was an error writing to", file_name

sys.exit()

print "Enter '", file_finish,

print "' When finished"

while file_text != file_finish:

18 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

file_text = raw_input("Enter text: ")

if file_text == file_finish:

# close the file

file.close

break

file.write(file_text)

file.write("\n")

file.close()

file_name = raw_input("Enter filename: ")

if len(file_name) == 0:

print "Next time please enter something"

sys.exit()

try:

file = open(file_name, "r")

except IOError:

print "There was an error reading file"

sys.exit()

file_text = file.read()

file.close()

print file_text

19 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

1.8 Multiline statement

Statements in Python typically end with a new line. Python does, however, allow the use
of the line continuation character (\) to denote that the line should continue. For example −

total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

1.9 Multiple Statement Group (Suite)

 A group of individual statements, which make a single code block are called suites in
Python. Compound or complex statements, such as if, while, def, and class require a header
line and a suite.

 Header lines begin the statement (with the keyword) and terminate with a colon (: ) and are
followed by one or more lines which make up the suite.

Example

if expr1==True:

stmt1

stmt2

elif expr2==True:

stmt3

DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


20
DCS33-PROGRAMMING USING PYTHON UNIT I

stmt4

else:

stmt5

stmt6

while expr==True:

stmt1

stmt2

1.10 Quotes in Python

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long
as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following
are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

1.11 Input, Output and Import Functions

 The basic I/O functions available in Python. For more functions, please refer to standard
Python documentation.
21 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT I

Printing to the Screen

 The simplest way to produce output is using the print statement where you can pass zero
or more expressions separated by commas.

 This function converts the expressions you pass into a string and writes the result to
standard output as follows −

#!/usr/bin/python

print "Python is really a great language,", "isn't it?"

This produces the following result on your standard screen −

Reading Keyboard Input

 Python provides two built-in functions to read a line of text from standard input, which
by default comes from the keyboard. These functions are −

 raw_input
 input

The raw_input Function

 The raw_input([prompt]) function reads one line from standard input and returns it as a
string (removing the trailing newline).

#!/usr/bin/python

str = raw_input("Enter your input: ")


print "Received input is : ", str

This prompts you to enter any string and it would display same string on the screen. When I
typed "Hello Python!", its output is like this −

Enter your input: Hello Python

22 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Received input is : Hello Python

The input Function

The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated result to you.

#!/usr/bin/python

str = input("Enter your input: ")


print "Received input is : ", str

This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]


Recieved input is : [10, 20, 30, 40]

Opening and Closing Files

 Reading and writing to the standard input and output. Now, we will see how to use
actual data files.

 Python provides basic functions and methods necessary to manipulate files by default.
You can do most of the file manipulation using a file object.

The open Function

 Before you can read or write a file, you have to open it using Python's built-
in open() function.

 This function creates a file object, which would be utilized to call other support methods
associated with it.

Syntax
file object = open(file_name [, access_mode][, buffering])

Here are parameter details −

23 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

 file_name − The file_name argument is a string value that contains the name of the file
that you want to access.

 access_mode − The access_mode determines the mode in which the file has to beopened,
i.e., read, write, append, etc. A complete list of possible values is given below inthe table.
This is optional parameter and the default file access mode is read (r).

 buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the indicated
buffer size. If negative, the buffer size is the system default(default behavior).

Here is a list of the different modes of opening a file −

S.No. Modes & Description

1 R:Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.

2 Rb: Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.

3 r+: Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.

4
rb+:Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.

5
W:Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.

24 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

6 wb: Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.

7
w+: Opens a file for both writing and reading. Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.

8
wb+:Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and writing.

9 a :Opens a file for appending. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

10 ab :Opens a file for appending in binary format. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.

11
a+ :Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new
file for reading and writing.

12
ab+ : Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.

The file Object Attributes

Once a file is opened and you have one file object, you can get various information
related to that file.

25 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Here is a list of all attributes related to file object −

S.No. Attribute & Description

1 file.closed: Returns true if file is closed, false otherwise.

2 file.mode: Returns access mode with which file was opened.

3 file.name: Returns name of the file.

4 file.softspace: Returns false if space explicitly required with print, true otherwise.

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

This produces the following result −

Name of the file: foo.txt


Closed or not : False
Opening mode : wb
Softspace flag : 0

The close() Method

26 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

 The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.

 Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.

Syntax
fileObject.close()

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file


fo.close()

This produces the following result −

Name of the file: foo.txt

Reading and Writing Files

 The file object provides a set of access methods to make our lives easier. We would see
how to use read() and write() methods to read and write files.

27 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

The write() Method

 The write() method writes any string to an open file. It is important to note that Python
strings can have binary data and not just text.

 The write() method does not add a newline character ('\n') to the end of the string −

Syntax
fileObject.write(string)

Here, passed parameter is the content to be written into the opened file.

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file


fo.close()

The above method would create foo.txt file and would write given content in that file and finally
it would close that file. If you would open this file, it would have following content.

Python is a great language.


Yeah its great!!

The read() Method

 The read() method reads a string from an open file. It is important to note that Python
strings can have binary data. apart from text data.

Syntax
fileObject.read([count])

28 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as much
as possible, maybe until the end of file.

Example

Let's take a file foo.txt, which we created above.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

This produces the following result −

Read String is : Python is

File Positions

 The tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.

 The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.

 If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end
of the file would be taken as the reference position.

Example

Let us take a file foo.txt, which we created above.

29 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str

# Check current position


position = fo.tell()
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()

This produces the following result −

Read String is : Python is


Current file position : 10
Again read String is : Python is

Renaming and Deleting Files

 Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.

 To use this module you need to import it first and then you can call any related functions.

The rename() Method


30 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT I

The rename() method takes two arguments, the current filename and the new filename.

Syntax
os.rename(current_file_name, new_file_name)

Example

Following is the example to rename an existing file test1.txt −

#!/usr/bin/python
import os

# Rename a file from test1.txt to test2.txt


os.rename( "test1.txt", "test2.txt" )

The remove() Method

You can use the remove() method to delete files by supplying the name of the file to be deleted
as the argument.

Syntax
os.remove(file_name)

Example

Following is the example to delete an existing file test2.txt −

#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")

Directories in Python

31 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

 All files are contained within various directories, and Python has no problem handling
these too. The os module has several methods that help you create, remove, and change
directories.

The mkdir() Method

 You can use the mkdir() method of the os module to create directories in the current
directory.

 You need to supply an argument to this method which contains the name of the directory
to be created.

Syntax
os.mkdir("newdir")

Example

Following is the example to create a directory test in the current directory −

#!/usr/bin/python
import os

# Create a directory "test"


os.mkdir("test")

The chdir() Method

 You can use the chdir() method to change the current directory. The chdir() method takes
an argument, which is the name of the directory that you want to make the current
directory.

Syntax
os.chdir("newdir")

Example

Following is the example to go into "/home/newdir" directory −


32 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT I

#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")

The getcwd() Method

The getcwd() method displays the current working directory.

Syntax
os.getcwd()

Example

Following is the example to give current directory −

#!/usr/bin/python
import os

# This would give location of the current directory


os.getcwd()

The rmdir() Method

The rmdir() method deletes the directory, which is passed as an argument in the method.

Before removing a directory, all the contents in it should be removed.

Syntax
os.rmdir('dirname')

Example

Following is the example to remove "/tmp/test" directory. It is required to give fully qualified
name of the directory, otherwise it would search for that directory in the current directory.

33 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

#!/usr/bin/python
import os

# This would remove "/tmp/test" directory.


os.rmdir( "/tmp/test" )

File & Directory Related Methods

 There are three important sources, which provide a wide range of utility methods to handle
and manipulate files & directories on Windows and UNIX operating systems. They are as
follows −

 File Object Methods: The file object provides functions to manipulate files.

 OS Object Methods: This provides methods to process files as well as directories.

1.12 Operators:

Operators are the constructs which can manipulate the value of operands.

Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

1.12.1 Types of Operator

Python language supports the following types of operators.

 Arithmetic Operators

 Comparison (Relational) Operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

34 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

 Membership Operators

 Identity Operators

1.12.2 Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder

35 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

** Exponent Performs exponential (power) calculation on a**b =10 to the power 20


operators

// Floor Division - The division of operands where 9//2 = 4 and 9.0//2.0 = 4.0, -
the result is the quotient in which the digits after 11//3 = -4, -11.0//3 = -4.0
the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative
infinity) −

1.12.3 Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them.
They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.

!= If values of two operands are not equal, then (a != b) is true.


condition becomes true.

<> If values of two operands are not equal, then (a <> b) is true. This is similar to !=
condition becomes true. operator.

36 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

> If the value of left operand is greater than the (a > b) is not true.
value of right operand, then condition becomes
true.

< If the value of left operand is less than the value (a < b) is true.
of right operand, then condition becomes true.

>= If the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, then
condition becomes true.

<= If the value of left operand is less than or equal to (a <= b) is true.
the value of right operand, then condition
becomes true.

1.12.4 Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c

+= Add AND It adds right operand to the left operand and assign the result to left c += a is
equivalent

37 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

operand to c = c +
a

-= Subtract AND It subtracts right operand from the left operand and assign the result c -= a is
to left operand equivalent
to c = c -
a

*= Multiply It multiplies right operand with the left operand and assign the c *= a is
AND result to left operand equivalent
to c = c *
a

/= Divide AND It divides left operand with the right operand and assign the result c /= a is
to left operand equivalent
to c = c /
a

%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent
to c = c %
a

**= Exponent Performs exponential (power) calculation on operators and assign c **= a is
AND value to the left operand equivalent
to c = c
** a

38 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent
to c = c //
a

1.12.5 Python Bitwise Operators

 Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and
b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101
respectively.

 Following table lists out the bitwise operators supported by Python language with an
example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100

b = 0000 1101

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example

& Binary AND Operator copies a bit to the


result if it exists in both (a & b) (means 0000 1100)
operands

39 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

| Binary OR It copies a bit if it exists in


(a | b) = 61 (means 0011 1101)
either operand.

^ Binary XOR It copies the bit if it is set in


(a ^ b) = 49 (means 0011 0001)
one operand but not both.

~ Binary Ones (~a ) = -61 (means 1100 0011 in 2's


It is unary and has the effect
Complement complement form due to a signed
of 'flipping' bits.
binary number.

<< Binary Left Shift The left operands value is


moved left by the number of
a << 2 = 240 (means 1111 0000)
bits specified by the right
operand.

>> Binary Right Shift The left operands value is


moved right by the number of
a >> 2 = 15 (means 0000 1111)
bits specified by the right
operand.

1.12.6 Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then

Operator Description Example

40 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.

or Logical OR If any of the two operands are non-zero then condition becomes (a or b)
true. is true.

not Logical NOT Used to reverse the logical state of its operand. Not(a
and b) is
false.

1.12.7 Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −

[ Show Example ]

Operator Description Example

in Evaluates to true if it finds a variable


x in y, here in results in a 1 if x is a member of
in the specified sequence and false
sequence y.
otherwise.

not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if x is not a
variable in the specified sequence member of sequence y.
and false otherwise.

41 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

1.12.8 Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −

Operator Description Example

is Evaluates to true if the variables on either


x is y, here is results in 1 if id(x) equals
side of the operator point to the same
id(y).
object and false otherwise.

is not Evaluates to false if the variables on


x is not y, here is not results in 1 if id(x) is
either side of the operator point to the
not equal to id(y).
same object and true otherwise.

1.12.9 Python Operators Precedence

The following table lists all operators from highest precedence to lowest.

S.No. Operator & Description

1
**

Exponentiation (raise to the power)

2
~+-

Complement, unary plus and minus (method names for the


last two are +@ and -@)

42 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

3
* / % //

Multiply, divide, modulo and floor division

4
+-

Addition and subtraction

5
>> <<

Right and left bitwise shift

6
&

Bitwise 'AND'

7
^|

Bitwise exclusive `OR' and regular `OR'

8
<= < > >=

Comparison operators

9
<> == !=

Equality operators

10
= %= /= //= -= += *= **=

Assignment operators

43 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

11
is is not

Identity operators

12
in not in

Membership operators

13
not or and

Logical operators

1.13 Data types:

 The data stored in memory can be of many types. For example, a person's age is stored as
a numeric value and his or her address is stored as alphanumeric characters.
 Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.

Python has five standard data types −

 Numbers

 String

 List

 Tuple

 Dictionary

1.13.1 Python Numbers

44 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

 Number data types store numeric values. Number objects are created when you assign a
value to them. For example −

var1 = 1

var2 = 10

1.13.2 Python Strings

 Strings in Python are identified as a contiguous set of characters represented in the


quotation marks.
 Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string
and working their way from -1 at the end.

1.13.3 Python Lists

 Lists are the most versatile of Python's compound data types.


 A list contains items separated by commas and enclosed within square brackets ([]).
 To some extent, lists are similar to arrays in C. One difference between them is that all
the items belonging to a list can be of different data type.

1.13.4 Python Tuples

 A tuple is another sequence data type that is similar to the list.


 A tuple consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses.

1.13.5 Python Dictionary

 Python's dictionaries are kind of hash table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs.
 A dictionary key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.

45 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

1.14 Data type Conversion

 There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

Sr.No. Function & Description

1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.

2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.

3 float(x)
Converts x to a floating-point number.

4 complex(real [,imag])
Creates a complex number.

5 str(x)
Converts object x to a string representation.

6 repr(x)
Converts object x to an expression string.

7 eval(str)
Evaluates a string and returns an object.

46 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Sr.No. Function & Description

8 tuple(s)
Converts s to a tuple.

9 list(s)
Converts s to a list.

10 set(s)
Converts s to a set.

11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.

12 frozenset(s)
Converts s to a frozen set.

13 chr(x)
Converts an integer to a character.

14 unichr(x)
Converts an integer to a Unicode character.

15 ord(x)
Converts a single character to its integer value.

47 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

Sr.No. Function & Description

16 hex(x)
Converts an integer to a hexadecimal string.

17 oct(x)
Converts an integer to an octal string.

48 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

UNIT I - OVERVIEW

Syllabus: [Regulation: 2021]


UNIT - I: Introduction to Python: Features of Python - How to Run Python – Identifiers – Reserved
Keywords - Variables - Comments in Python - Indentation in Python - Multi-Line Statements -
Multiple Statement Group (Suite) – Quotes in Python - Input, Output and Import Functions -
Operators. Data Types and Operations: Numbers-Strings-List-Tuple-Set-Dictionary- Data type
conversion.

PART-A QUESTIONS

1. What are the applications of Python?


2. What are the advantages of Python?
3. What do you mean by Python literals?
4. What is identifier?
5. Define keywords.
6. What is variable?
7. What is tuple in Python?
8. What is an operator in Python?
9. What is a dictionary in Python?
10. What is the difference between list and tuple?
11. How can you convert a number to string?
PART-B QUESTIONS
1. Name some of the features of Python.
2. How will you convert a string to a tuple in python?
3. What are Literals in Python and explain about different Literals?
4. What are comments and how can you add comments in Python?
5. How will you remove duplicate elements from a list?
6. How do you get a list of all the keys in a dictionary?

49 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI


DCS33-PROGRAMMING USING PYTHON UNIT I

PART-C QUESTIONS

1. Explain briefly about the applications of Python.


2. What are the rules for choosing names of variables? Explain in detail
3. Write in brief about any 5 keywords in Python.
4. Explain about the need for learning python programming and its importance.
5. Write a python program to describe different ways of deleting an element from the given
List.
6. What are the different operations that can be performed on a list? Explain with Examples
7. Write in brief about List in python.
8. Write in brief about Tuple in python. Write operations with suitable examples.
9. Write in brief about Set in python. Write operations with suitable examples.
10. Explain types of operators.

50 DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI

You might also like