DOC-20241219-WA0001.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

INDUSTRIAL TRAINING IN

PYTHON
PROGRAMMING
Submitted by- TUSHAR KUMAR Submitted to- DR. NEETU
College ID- 22IT53 SHARMA
(Mentor)
University Roll No- 22EEAIT054
Batch- I2 (III Semester)
Department of Computer Science and
Information Technology
OVERVIEW
• YOUNITY had organized an Industrial Training for the students of
Computer Science and engineering department branch Information
Technology to develop a sense of programming in python language.
• The training continued for 16 days consisting of a 1.5 hours session
everyday. The teachers were highly supportive and guided the students
throughout the training period.
• After the completion of training, a quiz was conducted to test the
knowledge of the students. The quiz was based on the topics covered
during the training.
CONTENTS
• Fundamentals of • Method and Inheritance
Language Constructors
• Basics of Python I • Polymorphism & Data
Abstraction
• Basics of Python II • Encapsulation
• Conditional Execution • Python Set Operations I
• Functions of programming • Python Set Operations II
• Iteration • File Operations
• Class & Object
DAY 1
Fundamentals of Programming
Language
Programming languages vary in the level of abstraction they
provide from the hardware. They can be classified into the
following categories:
• Low-level language
• Middle-level language
• High-level language
DAY 2
Introduction to Python
• Python is a versatile and popular high-level programming language known for
its simplicity, readability, and wide range of applications. It was created by
Guido van Rossum and first released in 1991. Python is an open-source
language, which means it's free to use and has a large and active community
of developers and users.
• It is a general purpose language, means can be used for a wide variety of task
from Web Development to Data analysis etc.
• Interpreted language:- : Python is an interpreted language, which means we
don't need to compile our code before running it.
• High-Level Language: Python's high-level nature abstracts many low-level
details, making it more user-friendly and productive for developers.
DAY 3
CONDITIONAL EXECUTION
1. if- Statement:- is used to execute a block of code only if a specified condition is True.
Example- if condition
#code to execute when the statement is true;
2. elif Statement:- allows us to execute one block of code when the condition is true and another block
whenever the condition is false.
Example- if condition
#code to execute when the statement is true;
else condition;
#code to execute when the statement is false;
3. if-elif-else Statement:- is used to check multiple conditions.
Example-if condition1:
# Code to execute when condition1 is True
elif condition2:
# Code to execute when condition2 is True
else:
# Code to execute when no conditions are True
DAY 4
Functions of Programming.
A function is a block of code that performs a specific task.
Suppose, we need to create a program to create a circle
and color it. We can create two functions to solve this
problem:
create a circle function
create a color function
Dividing a complex problem into smaller chunks makes our
program easy to understand and reuse.
• Types of function
• There are two types of function in Python programming:
• Standard library functions - These are built-in functions
in Python that are available to use.
SYNTAX FOR WRITING A FUNCTION IN
PYTHON

def function_name(parameters): # What the function


does goes here return result
DAY: 5 
Loops In Python
Python programming language provides the following types of
loops to handle looping requirements. Python provides three
ways for executing the loops. While all the ways provide similar
basic functionality, they differ in their syntax and condition-
checking time.
 While Loop in Python
In python, a while loop is used to execute a block of statements
repeatedly until a given condition is satisfied. And when the
condition becomes false, the line immediately after the loop in the
program is executed.
For Loop in Python
For loop are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is “for in” loop which is similar to for each loop in other languages.

Nested Loops
Python programming language allows to use one loop inside another loop.
Following section shows few examples to illustrate the concept.

Now let us look at syntax and examples of


loops in python
SYNTAX OF WHILE LOOP:-
Syntax:
while expression: statement(s)
SYNTAX OF FOR LOOP:-
Syntax:
for iterator_var in sequence:
statements(s)
SYNTAX OF NESTED LOOP:-
Syntax
for iterator_var in sequence:
for iterator_var in sequence: statements(s)
statements(s)
Loop Control Statements
Loop control statements change execution from their normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.
Continue Statement
the continue statement in Python returns the control to the beginning of the loop.

Output:-
# Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks':
Current Letter : g Current
if letter == 'e' or letter == 's': Letter : k Current Letter : f
continue Current Letter : o Current
print('Current Letter :', letter) Letter : r Current Letter : g
Current Letter : k
Break Statement
The break statement in Python brings control out of the loop. Output:-
Current letter: e
for letter in 'geeksforgeeks':
# break the loop as soon it sees
'e'
# or 's'
if letter == 'e' or letter == 's':
break

print('Current Letter :', letter)


Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for empty
control statements, functions and classes.

# An empty loop
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
OUTPUT
LAST LETTER : S
DAY:-6
ITERATIONN IN PYTHON
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that we can traverse through all
the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which
consist of the methods __iter__() and __next__().

ITERATOR VS ITERABLE:-

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which
we can get an iterator from.
All these objects have a iter() method which is used to get an iterator.
Example:-Get :- OUTPUT
Return an iterator from a tuple, and print each value: Apple
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple) Banana
 Cherry
print(next(myit))
print(next(myit))
print(next(myit))

Strings are also iterable objects, containing a sequence of characters:


mystr = "banana" OUTPUT
myit = iter(mystr)
 a
print(next(myit))
b
print(next(myit))
print(next(myit)) n
print(next(myit)) a
print(next(myit)) n
print(next(myit)) a
CREATING AN ITERATOR
To create an object/class as an iterator you have to implement the methods __iter__() and
__next__() to your object.
As you have learned in the python classes/object chapter, all classes have a function called
__init__(), which allows you to do some initializing when the object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.), but must always return
the iterator object itself.
The __next__() method also allows you to do operations, and must return the next item in the
sequence.

FOR EXAMPLE:-
STOPITERATION:-
To prevent the iteration from going on forever, we can use the StopIteration statement.
In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a
specified number of times:
EXAMPLE:-
Stop after 20 iterations:
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)
DAY:-7
CLASSES AND OBJECT IN PYTHON:
CLASSES:-A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class creates a new
type of object, allowing new instances of that type to be made. Each class instance can have
attributes attached to it for maintaining its state. Class instances can also have methods (defined by
their class) for modifying their state.

SYNTAX FOR CLASS:-


class ClassName:
# Statement
OBJECTS:-
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class
with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven
years old. We can have many dogs to create many different instances, but without the class as a
guide, you would be lost, not knowing what information is required.

An object consists of:


•State: It is represented by the attributes of an object. It also reflects the properties of an object.
•Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
•Identity: It gives a unique name to an object and enables one object to interact with other objects.

SYNTAX FOR OBJECT:-


obj = ClassName()
print(obj.atrr)
DAY 8:-
METHOD AND INHERITANCE CONSTRUCTORS:-
One of the core concepts in object oriented programming (OOP) languages is
inheritance. It is a mechanism that allows us to create a hierarchy of classes that share a
set of properties and methods by deriving a class from another class. Inheritance is the
capability of one class to derive or inherit the properties from another class.
Benefits of inheritance are:

•It represents real-world relationships well.


•It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
•It is transitive in nature, which means that if class B inherits from another class A, then
all the subclasses of B would automatically inherit from class A.
•Inheritance offers a simple, understandable model structure.
•Less development and maintenance expenses result from an inheritance.
Syntax of inheritance:-
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
DAY :-9
POLYMORPHISM AND DATA ABSTRACTION
What is Polymorphism: The word polymorphism means having many forms. In programming,
polymorphism means the same function name (but different signatures) being used for different
types. The key difference is the data types and number of arguments used in function.

Polymorphism
Po l ym o r p h i sm i s t h e a b i l i t y o f a
message to be displayed in more than
one form.
PYTHON supports operator overloading
and function overloading.
Polymorphism is extensively used in
implementing inheritance.
Data abstraction means information hiding. Usually what is hidden is the representation of a data
structure. Example: I implement sets, but I don't tell you whether a set is represented as a list, a
balanced binary tree, or an unbalanced binary tree. Done right, I can change representation without
breaking your code.

SAMPLE PROGRAM:-

Imagine a fraction class:


class fraction: int denominator int numerator
Now two objects of that:
fraction(obj1): denominator=-1 numerator=-1 fraction(obj2): denominator=1 numerator=1
Both objects have the value 1: (1/1) == (-1)/(-1). We wouldn't expect they behave any different to the
outside. That's abstraction. We abstract the data our object holds into a logical view, even tho behind
the scenes, there are other things. Theoretically, we have got a equivalence relation, with different
equivalence groups:
[1]=(1, 1), (-1, -1), (5, 5), ... [2]=(2, 4), (-2, -4), ... ...
And there is a abstraction function that abstracts the internal details to the outside:
f((1, 1)) = [1] f((-1, -1)) = [1]
DAY 11
Encapsulation
Encapsulation is defined as wrapping up of
data and information under a single unit in
Object-Oriented Programming.
Encapsulation also leads to data
abstraction or hiding.
DAY 12:-
PYTHON SET OPERATIONS
THERE ARE MAINLY 4 DIFFERENT SET OPERATIONS IN PYTHON:-
1. UNION
2. INTERSECTION
3. DIFFERENCE
4. SYMMETRIC DIFFERENCE
HAVE A LOOK AT SAMPLE EXAMPLE:-
Input : A = {0, 2, 4, 6, 8} B = {1, 2, 3, 4, 5}
Output :
Union : [0, 1, 2, 3, 4, 5, 6, 8]
Intersection : [2, 4]
Difference : [8, 0, 6]
Symmetric difference : [0, 1, 3, 5, 6, 8]
DAY 13:-
FILE HANDLING IN PYTHON(PART-1):-
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many
other file handling options, to operate on files. The concept of file handling has stretched over various other
languages, but the implementation is either complicated or lengthy, but like other concepts of Python, this
concept here is also easy and short.

ADVANTAGES
•Versatility: File handling in Python allows us to perform a wide range of operations, such as creating,
reading, writing, appending, renaming, and deleting files.
•Flexibility: File handling in Python is highly flexible, as it allows us to work with different file types (e.g. text
files, binary files, CSV files, etc.), and to perform different operations on files (e.g. read, write, append, etc.).
•User–friendly: Python provides a user-friendly interface for file handling, making it easy to create, read, and
manipulate files.
•Cross-platform: Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux),
allowing for seamless integration and compatibility.
DISADVANTAGES
•Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the
file system (e.g. file permissions, file locks, etc.).
•Security risks: File handling in Python can also pose security risks,
especially if the program accepts user input that can be used to access or
modify sensitive files on the system.
•Complexity: File handling in Python can be complex, especially when
working with more advanced file formats or operations. Careful attention
must be paid to the code to ensure that files are handled properly and
securely.
•Performance: File handling operations in Python can be slower than
other programming languages, especially when dealing with large files or
performing complex operations.
DAY 14:-
ACCESS MODES IN FILE HANDLING:-
In Python, there are six methods or access modes, which are:
1.Read Only ('r’): This mode opens the text files for reading only. The start of the file is where the
handle is located. It raises the I/O error if the file does not exist. This is the default mode for opening
files as well.
2.Read and Write ('r+’): This method opens the file for both reading and writing. The start of the file
is where the handle is located. If the file does not exist, an I/O error gets raised.
3.Write Only ('w’): This mode opens the file for writing only. The data in existing files are modified
and overwritten. The start of the file is where the handle is located. If the file does not already exist
in the folder, a new one gets created.
4.Write and Read ('w+’): This mode opens the file for both reading and writing. The text is
overwritten and deleted from an existing file. The start of the file is where the handle is located.
5.Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet exist, a
new one gets created. The handle is set at the end of the file. The newly written data will be added
at the end, following the previously written data.
6.Append and Read (‘a+’): Using this method, we can read and write in the file. If the file doesn't
already exist, one gets created. The handle is set at the end of the file. The newly written text will be
DAY 15:-
OPERATIONS IN FILE HANDLING
1.CREATING A FILE:

"x" – Create: this command will create a new file if and only if there is no file already in existence with that
name or else it will return an error.

#creating a text file with the command functio


n "x"
f = open("myfile.txt", "x")
2.WRITE IN A FILE:-
This function inserts the string into the text file on a single line.
Based on the file we have created above, the below line of code will insert the string into
the created text file, which is "myfile.txt.”
3. READ FROM A FILE:-
This function returns the bytes read as a string. If no n is
specified, it then reads the entire file. We usally use read()
method for this operation.

f = open("myfiles.txt", "r") print(f.readline()) print(f.readline()

4. Closing a file:-
It is good practice to always close the file when you are done
with it.
f = open("myfiles.txt", "r") print(f.readline()) f.close()
THANK
YOU

You might also like