Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Unit - 3

This document covers the mapping type operators in Python, focusing on dictionaries, their creation, manipulation, and built-in methods. It also discusses conditionals, loops, file handling, and command line arguments. Key concepts include dictionary operations, control flow statements, and file I/O methods.

Uploaded by

SATHISHKUMAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit - 3

This document covers the mapping type operators in Python, focusing on dictionaries, their creation, manipulation, and built-in methods. It also discusses conditionals, loops, file handling, and command line arguments. Key concepts include dictionary operations, control flow statements, and file I/O methods.

Uploaded by

SATHISHKUMAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT – 3 MAPPING TYPE OPERATORS

Mapping type: Dictionaries – Mapping type operators – Mapping type  It represents a collection of key-value pairs.
Built-in and Factory Functions - Mapping type built in methods –
Conditionals and loops – if statement – else Statement – elif statement –  Each key is unique within the collection.
conditional expression – while statement – for statement – break statement
– continue statement – pass statement – Iterators and the iter( ) function -
 The primary mapping types in Python are dictionaries (dict).
Files and Input/output – File objects – File built-in functions – File built- in
methods – File built-in attributes – Standard files – command line
arguments. 1. Creating a Dictionary:
 Using curly braces {} to define a dictionary.
MAPPING TYPE Example:
DICTIONARIES my_dict = {'key1': 'value1', 'key2': 'value2'}
 It is the mapping type.
 It is mutable. 2. Accessing Values:
Syntax:  Using square brackets [] to access the value associated with a
variable_name={“Value-1”,”Value_2”,Value_n} key.
Example: Example:
value = my_dict['key1']

3. Adding/Updating Elements:
 Using square brackets [] to add or update key-value pairs.
Example:
Output:
my_dict['new_key'] = 'new_value'

V. Naresh Kumar, M.C.A., M.Phil., Page 1


4. Deleting Elements: 8. Iterating Through a Dictionary:
 Using del statement to remove a key-value pair.  Using a for loop to iterate over keys or key-value pairs.
Example: Example:
del my_dict['key1'] for key in my_dict: print(key, my_dict[key])

5. Checking Membership: 9. Dictionary Comprehension:


 Using the in keyword to check if a key is present in the  Creating dictionaries using a concise syntax.
dictionary. Example:
Example: squared_dict = {x: x**2 for x in range(5)}
if 'key1' in my_dict: print("Key exists")

6. Getting Keys and Values:


 Using the keys() and values () methods to get lists of keys
and values, respectively.
Example:
keys = my_dict.keys() values = my_dict.values()

7. Getting Items:
 Using the items() method to get a list of key-value pairs as
tuples.
Example:
items = my_dict.items()

V. Naresh Kumar, M.C.A., M.Phil., Page 2


MAPPING TYPE BUILT-IN AND FACTORY FUNCTIONS 3. list() Constructor:
1. map() Function: Syntax:
 Applies the specified function to all items in the given list ([iterable])
iterable(s). Example:
Syntax: my_list = list (range(5)) print(my_list)
map(function, iterable, ...) Output:
Example: [0, 1, 2, 3, 4]
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers) 4. set() Constructor:
print(list(squared_numbers)) Syntax:
Output: set([iterable])
[1, 4, 9, 16, 25] Example:
my_set = set([1, 2, 3, 2, 4, 5])
2. dict() Constructor: print(my_set)
Syntax: Output:
dict([iterable], **kwargs) {1, 2, 3, 4, 5}
Example:
key_value_pairs = [('a', 1), ('b', 2), ('c', 3)] my_dict =
dict(key_value_pairs) print(my_dict)
Output:
{'a': 1, 'b': 2, 'c': 3}

V. Naresh Kumar, M.C.A., M.Phil., Page 3


MAPPING TYPE BUILT IN METHODS IN PYTHON 3. get(key[, default])
1. Clear ()  Returns the value for the specified key.
 Removes all items from the dictionary.  If the key is not found, it returns the specified default value.
Example: Example:
my_dict = {'a': 1, 'b': 2, 'c': 3} my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear () value = my_dict.get('b', 0)
print(my_dict) print(value)
Output: Output:
{} 2

2. copy() 4. Item()
 Returns a shallow copy of the dictionary.  Returns a view of the dictionary's key-value pairs as tuples.
Example: Example:
original_dict = {'a': 1, 'b': 2, 'c': 3} my_dict = {'a': 1, 'b': 2, 'c': 3}
copied_dict = original_dict.copy () items = my_dict.items()
print(items)
Output:
dict_items([('a', 1), ('b', 2), ('c', 3)])

V. Naresh Kumar, M.C.A., M.Phil., Page 4


5. keys() 7. popitem()
 Returns a view of the dictionary's keys.  Removes and returns an arbitrary (key, value) pair as a tuple.
Example:  Raises a KeyError if the dictionary is empty.
my_dict = {'a': 1, 'b': 2, 'c': 3} Example:
keys = my_dict.keys() my_dict = {'a': 1, 'b': 2, 'c': 3}
print(keys) item = my_dict.popitem()
Output: print(item)
dict_keys(['a', 'b', 'c']) Output:
('c', 3)
6. values() 8. update([other])
 Returns a view of the dictionary's values.  Updates the dictionary with the key-value pairs from another
Example: dictionary or an iterable of key-value pairs.
my_dict = {'a': 1, 'b': 2, 'c': 3} Example:
values = my_dict.values() my_dict = {'a': 1, 'b': 2}
print(values) other_dict = {'b': 3, 'c': 4}
Output: my_dict.update(other_dict)
dict_values([1, 2, 3]) print(my_dict)
Output:
{'a': 1, 'b': 3, 'c': 4}

V. Naresh Kumar, M.C.A., M.Phil., Page 5


CONDITIONALS AND LOOPS If … Else Statement
If Statement  If the condition is ture it execute the true statement otherwise
 If the condition is ture it execute true statement. it execute the false statement.
 If condition is false, it exit the loop. Syntax:
Syntax: If (condition):
If (condition): (Statement - 1)
(Statement) else:
Flowchart (Statement - x
Flowchart

Program:
print("String Handling Function") Program:
str1=input("Enter the String 1: ") print("String Handling Function")
if str1.islower(): str1=input("Enter the String 1: ")
print(str1,"The string is lower..") if str1.islower ():
print(str1,"The string is lower..")
else:
print("Try again")

V. Naresh Kumar, M.C.A., M.Phil., Page 6


Elif Statement Program:
 If the condition-1 is ture it executes the statement-1. print("String Handling Function")
 if condition-2 true it execute the statement-2 str1=input("Enter the String 1: ")
 otherwise, it execute statement-x str2=input("Enter the String 2: ")
Syntax: if str1.islower():
If (condition-1): print(str1,"The string is lower..")
(Statement-1) elif str2.islower():
elif(condition-2): print(str2,"The string is lower..")
(Statement-2) else:
else: print("Try again")
(Statement-x)
Flowchart

V. Naresh Kumar, M.C.A., M.Phil., Page 7


WHILE LOOP Program:
 It is an entry control loop. name=1
 It execute until the condition is false. n=int(input("Enter the Number:: "))
 It execute only once. while name<=n:

 If condition is false it does not execute once. print("Naresh")

Syntax: name=name+1

While (condition):
//statement-1 Output:

Flowchart

V. Naresh Kumar, M.C.A., M.Phil., Page 8


FOR LOOP Program:
 It also called iterating loop. n=int (input ("Enter the Number: "))
Syntax: for i in range (1, n+1):
For (variable) in range (variable) print (i)
Flowchart Output:

V. Naresh Kumar, M.C.A., M.Phil., Page 9


BREAK STATEMENT Program
 Terminates the current loop.
 Used in both while and for loops.
Flowchart

Output:

V. Naresh Kumar, M.C.A., M.Phil., Page 10


CONTINUE STATEMENT Example:
 Continue statement is used to skip the execution of the
program block and returns the control to the beginning of the
current loop to start the next iteration.
Flowchart:

Output:

V. Naresh Kumar, M.C.A., M.Phil., Page 11


PASS STATEMENT ITERATORS AND THE ITER ( ) FUNCTION
 The pass statement is used as a placeholder.  An iterator is an object that contains a countable number of
Example: values.
 Lists, tuples, dictionaries, and sets are all iterable objects.
 It has two methods,
1. __iter__()
2. __next__()
Program:

Output:

Output:

V. Naresh Kumar, M.C.A., M.Phil., Page 12


FILES AND INPUT/OUTPUT Access-Mode:
Introduction: "w" - File writing only.
 A file is some information or data. "r" - File Reading Only
 Data or information is stored in the system device. "a" - File appending
 The file is divided into two categories, "x" - Creates the specified file
1. Text file "w+" - updating & overwrite if the file exists.
2. Binary file "r+" - updating & does not overwrite.
 The information or data such as, Example:
o Music files f=open("N:/naresh1.txt","r")
o Video files print(f.read())
o Text files f=open("N:/naresh1.txt","a")
 File operation takes place in the following order. print(f.write("Kumar"))
o Open a file print(f.name)
o Read or write (perform operation)
print(f.mode)
o Close the file
FILE BUILT-IN FUNCTION print(f.closed)
OPEN()
f.close()
 File built-in function is Open().
Output:
 Open() function used to open a file.
 Open() function accepts two arguments,
1. file name
2. access mode
Syntax:
File object = open (file-name, access-mode)
File-name:
 It specifies the name of the file to be opened.

V. Naresh Kumar, M.C.A., M.Phil., Page 13


FILE BUILT-IN METHODS Example:
1. close() f=open("N:/naresh1.txt","r")
 The close() method used to close the currently opened file. print(f.read())
Syntax: f=open("N:/naresh1.txt","a")
Fileobject.close() print(f.write("Kumar"))
2. read()
print(f.name)
 The read () method is used to read the content from file.
print(f.mode)
Syntax:
Fileobject.read([size]) print(f.closed)
3. readline()
f.close()
 The readline() method reads the lines of the file.
Output:
Syntax:
Fileobject.readline()
4. write()
 The write () method is used to write the content into file.
Syntax:
Fileobject.write(content)
5. writelines()
 The writelines () method is used to write multiple lines of content
into file.
Syntax:
Fileobject.writelines(list)

V. Naresh Kumar, M.C.A., M.Phil., Page 14


FILE BUILT-IN ATTRIBUTES Output:

 Python Supports following built-in attributes, those are


File name,
1. file mode
2. file closed

1. file.name:

 Returns the name of the file which is already opened.

2. file.mode

 Returns the access mode of opened file.

3. file.closed

 Returns true, if the file closed, otherwise false.

Example:
f=open("N:/naresh1.txt","r")
print(f.read())
f=open("N:/naresh1.txt","a")
print(f.write("Kumar"))
print(f.name)

print(f.mode)

print(f.closed)

f.close()

V. Naresh Kumar, M.C.A., M.Phil., Page 15


STANDARD FILES 6. setup.py files:
1. .py files:
 These files are used to define metadata about a Python
 These are Python source code files. package, including its dependencies, version, and other
 They contain Python code that can be executed by the Python information.
interpreter.  They are commonly used with tools like setuptools for
packaging and distributing Python projects.
2. .pyc files:
7. .gitignore files:
 These are compiled Python files.
 When a .py file is executed, Python compiles it into bytecode  These files are used to specify which files and directories
and saves it as a .pyc file for faster execution in subsequent should be ignored by the version control system Git.
runs.  They are commonly used to exclude files like compiled
bytecode (.pyc) files and other generated files from being
3. init.py files:
tracked by Git.
 These files are used to define a Python package.
8. LICENSE files:
 They can be empty or contain initialization code that is
executed when the package is imported.  These files contain the license under which the Python code
is distributed.
4. README.md files:
 They specify the terms and conditions under which the code
 While not specific to Python, README.md files are can be used, modified, and redistributed.
commonly used in Python projects to provide documentation
and information about the project.

5. requirements.txt files:

 These files list the dependencies required by a Python


project.
 They are commonly used with package management tools
like pip to install the necessary dependencies.

V. Naresh Kumar, M.C.A., M.Phil., Page 16


COMMAND LINE ARGUMENTS 2. Python getopt module

 The line in front of the command prompt C:\> is called as  Similar as the C getopt() function.
command-line.  The getopt module is useful in parsing command line
 The command-line arguments are always stored in string arguments.
variables.
3. Python argparse module
 To store in numeric variable, we can use type conversion
functions.  It is the preferred way to parse command line arguments.
 Command-line arguments are parameters passed to a script or  It provides a lot of option such as
program.
1. Positional arguments
 There are different ways we can use command line
2. Default value for arguments
arguments.
3. Help message
1. Python sys module
4. Specifying data type of argument etc.
2. Python getopt module
Example:
3. Python argparse module
import argparse
4. Fire
parser = argparse.ArgumentParser()
5. Docopt
parser.parse_args()
1. Python sys module
4. Docopt
 It stores command-line arguments into a list.
 Docopt is used to create command line interfaces.
 It accesses using sys.argv.
 It simplifies the process of parsing command-line arguments
 Read command-line arguments as String.
and generating help messages.
Example:
5. Fire
import sys
 Python Fire automatically generates a command line
print(type(sys.argv)) interface.
print(' The command line arguments are: ')  Here, need one line of code.

for i in sys.argv:  It works instantly.


 Don’t need to define any arguments
print(i)

V. Naresh Kumar, M.C.A., M.Phil., Page 17

You might also like