Python 1-6-1
Python 1-6-1
EXPERIMENT NO - 01
Date of Performance :
Date of Submission :
THEORY:
Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function
name or any other identifier. They are used to define the syntax and structure of the Python
language. In Python, keywords are case sensitive.
Keywords in Python
False Class finally Is return
None Continue for lambda try
True Def from nonlocal while
and Del global not with
as elif if or yield
assert else import pass
break except in raise
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0
to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all
are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
`
Python Comments
In Python, the hash (#) symbol to start writing a comment. It extends up to the newline character.
Comments are for programmers for better understanding of a program. Python Interpreter ignores
comment.
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example: Another way of doing this is to use triple quotes, either ''' or
""".
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables
as a container that holds data which can be changed later throughout programming. Rules and
Naming Convention for Variables and constants
1. Constant and variable names should have a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
2. snake_case
3. MACRO_CASE
4. camelCase
5. CapWords
Type Conversion:
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Arithmetic operators
Arithmetic operators in Python
Operator Meaning Example
x + y +2
+ Add two operands or unary plus
x - y -2
- Subtract right operand from the left or unary minus
x**y (x to
** Exponent - left operand raised to the power of right the power y)
Logical operators
Comparison Operators
Comparison operators in Python
Operator Meaning Example
> 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
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than
>= or equal to the right x >= y
Membership operators
INPUT/OUTPUT
• Write a python program to input student details and display welcome message to newly
added student record
Diksha
63
Diksha
`
diksha@123
CONCLUSION: Thus, studied basic input/output methods and operators in python and successfully
implemented python programs for the same.
R1 R2 R3 R4 Total Signature
(3Marks) (3Marks) (3 Marks) (1 Mark) (10
Marks)
`
EXPERIMENT NO - 02
Date of Performance :
Date of Submission :
AIM: To study methods of python data types like string, list, dictionary, tuple and set
THEORY:
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.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.
Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks
String Methods
Python has a set of built-in methods that you can use on strings.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
`
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
List Methods
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Tuple
A tuple is a collection which is ordered and unchangeable
Tuple Methods
Method Description
Searches the tuple for a specified value and returns the position of where
index()
it was found
Set
A set is a collection which is unordered and unindexed.
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
Removes the items in this set that are also included in another, specified
difference_update()
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
Removes the items in this set that are not present in other, specified
intersection_update()
set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
`
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.
Method Description
items() Returns a list containing a tuple for each key value pair
Returns the value of the specified key. If the key does not exist: insert the key,
setdefault()
with the specified value
INPUT
`
zkre
`
OUTPUT
`
\
XYZW
‘XYZW’
‘XYZW’
‘XYZW’
`
CONCLUSION: Thus, we have studied different methods of python data types like list, tuple, dictionary, etc.
Also, we have implemented these datatypes in a python program successfully.
R1 R2 R3 R4 Total Signature
EXPERIMENT NO - 03
Date of Performance:
Date of Submission:
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is TRUE
or FALSE otherwise.
1 if statements
2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else ifstatement(s).
`
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following theloop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
`
INPUT/OUTPUT
● Write a python program that finds duplicates from the list [`a`,`b`,‟c`,`a`,`a`,`b`,`d`]
`
● Write a python program that reads alphabet and print desired output.
Alpahbet = [
[1,0,0,0,0,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,0,0,0,0,1]]
CONCLUSION: Thus, we have studied and implemented control structures and decision making
instructions in python.
R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)
`
EXPERIMENT NO - 04
Date of Performance :
Date of Submission :
THEORY:
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
Python gives you many built- in functions like print(), etc. but you can also create your own
functions. These functions are called user- defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
● Function blocks begin with the keyword def followed by the function name and
parentheses ( ( )).
● Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside theseparentheses.
● The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
● The code block within every function starts with a colon (:) and isindented.
● The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as returnNone.
Syntax def functionname( parameters ):
"function_docstring" function_suite return [expression]
EXAMPLE def printme( str ):
"This prints a passed string into this function" print str return
Calling a Function
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme() def
printme( str ):
`
"This prints a passed string into this function" print str return; # Now you can call printme
function printme("I'm first call to user defined function!") printme("Again second call to
the same function") Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the calling
function.
Function Arguments
You can call a function by using the following types of formal arguments −
● Required arguments
● Keyword arguments
● Default arguments
● Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters.
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this –
def functionname([formal_args,] *var_args_tuple ):
"function_docstring" function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all non-keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call.
`
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows –
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
INPUT/OUTPUT
● Write a python program that accepts two strings as input and find the string with
max length
Diksha
Miragal
Miragal
● Write a python program to print dictionary where keys are no’s between 1
and 20(both included) & values are square of keys
`
R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)
EXPERIMENT NO - 05
Date of Performance:
Date of Submission :
THEORY:
File handling
When working with Python, no need to import a library in order to read and write files. It‟s handled
natively in the language.
i.e., read, write, append, etc. A complete list of possible values is given below in the table. This
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).
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.
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 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.
9 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.
10 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.
11 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.
`
12 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.
13 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.
fileObject.close();
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 writefiles.
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.
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
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.
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 offsetargument 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.
Renaming and Deleting Files
The rename() Method
The rename() method takes two arguments, the current filename and the new filename. Syntax
os.rename(current_file_name, new_file_name)
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)
Directories in Python
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 changedirectories.
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")
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 currentdirectory.
Syntax
os.chdir("newdir")
The getcwd() Method
The getcwd() method displays the current working directory. Syntax
os.getcwd()
argument in the method. Before removing a directory, all the contents in it should be removed.
os.rmdir('dirname')
Syntax
Exampl
e
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 manipulatefiles. ● OS Object Methods:
This provides methods to process files as well asdirectories.
`
INPUT/OUTPUT
● Python program to append data to existing file and then display the entire file
`
CONCLUSION: Thus we have explored files and directories in python and have executed the programs
successfully
R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)
`
EXPERIMENT NO - 06
Date of Performance :
Date of Submission :
Python modules and Python packages, two mechanisms that facilitate modular programming.
Modular programming refers to the process of breaking a large, unwieldy programming task into
separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled
together like building blocks to create a larger application.
Python Modules
A module‟s contents are accessed the same way in all three cases: with the import statement.
Create a Module
To create a module just save the code you want in a file with the file extension .py: Example
Save this code in a file named mymodule.py 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("Jonathan")
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like. Example
Import and use the platform module: import platform
x = platform.system() print(x)
`
Example
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
INPUT
OUTPUT
CONCLUSION: Thus, we have learnt to send mails in python and hence program has been
executed successfully.
R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)