You are on page 1of 66

NATIVE LANGUAGE TRANSLATION TOOL SUITE

AN INTERNSHIP REPORT

Submitted

In the partial fulfillment of the requirements for

the award of the degree of

Bachelor of Technology in Electronics and Communication Engineering


By

V.VARUN SAI

[Reg. No. 191FA05062]

Under the guidance of Under the guidance of

DADHWAL, SUNYANA M. Vamsi Krishna

Senior Software Manager Professor

(ACCREDITED BY NAAC WITH ‘A’GRADE)

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

VIGNAN’S FOUNDATION FOR SCIENCE, TECHNOLOGY AND RESEARCH

(Deemed to be University)

VADLAMUDI, GUNTUR – 522 213, INDIA

May-2023

CERTIFICATE
This is to certify that the internship report entitled “NATIVE LANGUAGE TRANSLATION TOOL
SUITE” that is being submitted by V.VARUN SAI bearing Regd. No 191FA05062 in partial fulfillment
for the award of B. Tech degree in Electronics and Communication Engineering to Vignan’s Foundation
for Science
Technology and Research University, is a record of Bonafede work carried out by her at WABTEC
Corporation under the supervision of DADHWAL, SUNYANA and the internal guidance of M.Vamsi
Krishna of ECE Department.

Signature of the faculty guide Signature of Head of the Department

M.Vamsi Krishna Dr. T. Pitchaiah, M.E, Ph.D., MIEEE

Professor Professor
DECLARATION

I hereby declare that the internship work entitled “NATIVE LANGUAGE TRANSLATION TOOL
SUITE” is being submitted to Vignan’s Foundation for Science, Technology and Research (Deemed to be
University) in partial fulfillment for the award of B. Tech degree in Electronics and Communication
Engineering. The work was originally designed and executed by me under the guidance of my supervisor
DADHWAL,SUNYANA with M.Vamsi Krishna as faculty the guide at Department of Electronics and
Communication Engineering, Vignan’s Foundation for Science Technology and Research (Deemed to be
University) and was not a duplication of work done by someone else. I hold the responsibility of the
originality of the work incorporated into this thesis.

Signature of the candidate

V.VARUN SAI-191FA05062

ACKNOWLEDGEMENT

It’s my privilege to thank DADHWAL, SUNYANA who had been a source of inspiration and for
his/her timely guidance in the conduction of my project work. I/We wish to express my deep sense of
gratitude to my internal Guide, M. Vamsi Krishna, Professor, VFSTR (Deemed to be University) for his
able guidance and useful suggestions, which helped me in completing the project work, in time.

I would like to specially thank Dr. T. Pitchaiah, Head of the Department, ECE, and Mr. M. Vamsi
Krishna Internship Coordinator, Department of ECE, VFSTR (Deemed to be University) for their help and
support during the program.

Words are inadequate in offering my sincere thanks to DADHWAL, SUNYANA, and all the team
members for their encouragement, guidance, and cooperation during my stay in the company.

I take immense pleasure in thanking DADHWAL, SUNYANA for having permitted me to carry out
this internship work. Also, I wish to express my gratitude to Dr. M. Y. S. Prasad Vice-Chancellor, VFSTR
(Deemed to be University) for providing me the greatest opportunity to have industrial exposure and to
carry out the Live Projects.
I would like to thank all my faculty and technical staff for their support to finish my work successfully.
I wish to express my heart full thanks to my parents for their support and encouragement throughout my
life.

INTERNSHIP SUMMARY

Location: Bengaluru

Center: WABTEC Corporation.

Duration: 6 months

Date of start: 16th January 2023

Date of submission: 30th June 2023

Training details: Technical training in Python

Project Details: NATIVE LANGUAGE TRANSLATION TOOL SUITE

Reporting Manager: DADHWAL, SUNYANA, WABTEC Corporation Bengaluru.

Name of Faculty guide: M.Vamsi Krishna, Professor, VFSTR University.


PROFILE OF THE COMPANY
WABTEC Corporation
Wabtec Corporation is a leading provider of technology-based equipment and services for the freight
rail and passenger transit industries. The company was formed in 1999 through the merger of
Westinghouse Air Brake Company (WABCO) and MotivePower Industries Inc. Today, Wabtec employs
over 27,000 people globally and operates in more than 50 countries.

Wabtec's products and services are organized into two main business segments: Freight and Transit. The
Freight segment designs and manufactures a range of locomotives, freight cars, and associated
components, as well as provides maintenance, repair, and overhaul services. The Transit segment offers
a comprehensive range of systems and services for passenger transit vehicles, including braking systems,
propulsion and control systems, and passenger information systems.

Wabtec's history dates to 1869 when George Westinghouse invented the air brake system for trains,
which revolutionized the railroad industry. Today, Wabtec continues to be a leader in innovation and
technology, with a focus on developing solutions that improve safety, efficiency, and reliability for its
customers. The company's customer base is diverse and includes major freight railroads, transit agencies,
and industrial companies. Wabtec's products and services are used in a range of applications, including
freight transportation, commuter and light rail systems, mining, and industrial manufacturing.

In recent years, Wabtec has made significant investments in research and development, including the
development of new technologies such as digital train control systems and predictive maintenance
software. The company has also expanded its global footprint through acquisitions and partnerships with
leading industry players.

Overall, Wabtec Corporation is committed to driving the future of transportation by providing innovative
solutions and world-class services that meet the evolving needs of its customers and the industry.
WABTEC INDIA INDUSTRIAL PRIVATE LIMITED
ITC Green Centre, 6th Floor, Southwest Tower, No. 18
Banaswadi Main Road, Maruthiseva Nagar Bangalore
Karnataka, India – 560005

OFFER FOR INTERNSHIP

Veeravalli Varun Sai Vignan University

Dear Varun Sai,

Congratulations!

You have been selected as an Intern - Electronics & Communications Engineering with the
WABTEC INDIA INDUSTRIAL PRIVATE LIMITED, a Wabtec Company. Your assignment will
begin from January 16, 2023, and end on June 30, 2023.

Subject to the compliance with terms enclosed herewith as Annexure 1, during the above period you
will be paid a stipend amount of Rs. 30000/- (INR) per month. This offer is subject to your joining us
on the mentioned date and time. Annexures 2 and 3 will provide you with helpful information. You
hereby consent that your engagement will be terminated with immediate effect if the Compliance terms
and conditions stated in Annexure 1 are not complied.

Please note that this offer letter constitutes neither an offer of employment nor a commitment to offer
employment with the Company to you in the future.

This offer is valid until 7 days from the date of this letter. Look forward to your acceptance.

Yours Sincerely,

Sumeeta Desai
Director - Talent Acquisition Asia Pac
TABLE OF CONTENTS
CONTENTS Pg. no
CHAPTER 1-HCL ETHICS 1
1.1 Code of Business Ethics and Conduct (COBEC 2
1.2 Information Security 2
1.3 Export Compliance 2
1.4 Dimensions of Data Privacy 3
CHAPTER 2-INTRODUCTION TO PYTHON 4
2.1 History 5
2.2 Design philosophy and Features 6
2.3 Installation of Python 7
2.3.1 Introduction 7
2.3.2 Python 3 Installation on Windows 8
2.4 Syntax and Semantics 14
2.4.1 Indentation 14
2.4.2 Expressions 15
2.4.3 Methods 17
2.4.4 Typing 17
17
2.5 Python Operators
2.5.1 Arithmetic Operators 17
2.5.2 Logical Operators 18
2.5.3 Comparison operator 18
2.5.4 Identity operator 19
2. 5.5 Membership 19
2.5.6 Assignment operator 19
2.5.7 Bitwise Operators 20
2.6 Python Collections 20
2.6.1 Python Lists 20
2.6.2 Tuples in Python 22
2.6.3 Sets in Python 22

2. 6.4 Python Dictionary 23

CHAPTER-7 CONDITIONAL STATEMENTS 25


2.7.1 Python if else 25

2.7.2 if statement 25
2.7.3 if- else 26

2.7.4 Nested-if 27

2.7.5 if-elseif-else ladder 28

2.8-Python Loops 29

2.8.1 Python While Loop 29

2.8.2 While-else loop 30


31
2.8.3 Python For Loops
2.8.4 Loop Control Statements 31
2.9 Functions in Python 31

2.9.1 Keyword Arguments 32


2.9.2 Default Arguments 33

2.9.3 Variable-length Arguments 33

2. 9.4 The Anonymous Functions 33


2.10 Modules 34

2.10.1 The import Statement 34

2.10.2 Executing Modules as Scripts 34

2.10.3 Namespaces and Scoping 35

2.10.4 The globals() and locals() Functions 36

2.11 Python Packages 36


2.12 Regular Expressions 37

2.12.1Metacharacters 39

2.12.2 Set 40

2.12.4 Functions in RegEx 41

2.12.5 Match Object 42

2.13 Object Oriented Programming 42


2.13.1 Classes 43

2.13.2 Init Constructor 44

2.13.3 Inheritance 45

2.13.4 Encapsulation 47
2.13.5 Method Overriding 47
2.13.6 Abstraction 47

CHAPTER 3 : Native Language Translation Tool Suite 49

3.1 Introduction 51

3.2 Definition 52

3.3 Purpose 52

3.4 Scope 52

3.5 Intended Audience 52


3.6 Design and Implementation Constraints 52

CHAPTER 4- SYSTEM & SOFTWARE SPECIFICATIONS 53


4.1 Operating Environment 54

4.2 Software 54
4.3 Hardware 54

4.4 Software Requirements 54

CHAPTER 5 -PACKAGES REQUIRED 55


5.1 Openpyxl
5.2 Tkinter 56

CHAPTER 6-SYSTEM ARCHITECTURE 59


6.1 Architecture

CHAPTER 7- SIMULATION RESULTS AND DISCUSSION 64


7.1 Output Files 68

7.2 Executable Application 68

7.3 Tool 69

CHAPTER 8: Risks and Maintainability


CHAPTER 9: CONCLUSION 67

REFERENCES 67

TABLE OF FIGURES

FIGURES Pg.no
Fig 2.3.1: Python Installation 7

Fig 2.3.2: Python Releases for Windows 8


Fig 2.3.3: Python 3.7.3 9

Fig 2.3.4: Python Setup 10

Fig 2.3.5: Python Command Prompt 11

Fig 2.3.6: Python Terminal 12

Fig 2.3.7: Windows Run app 12

Fig 2.3.8: Edit System Variable 13

Fig 2.6.1: Nested Dictionary 23

Fig 2.7.1: if else 26

Fig 2.7.2: if elif 27

Fig 7.3: Nested if 28

Fig 2.7.4: if-elseif-else ladder 29

Fig 2.8.1: While Loop 30

Fig 2.13.1: Oops 43

Fig 2.13.2: Types of inheritance 45

Fig 2.7.2: Encapsulation 47

Fig 6.1: svm-1 60

Fig 6.2: svm-2 61


Fig 6.3: svm-3 61

Fig 6.4: svm-4 62


Fig 6.5: svm-5 62

Fig 6.6: svm-6 62

Fig 6.7: svm-7 62

Fig 6.8: svm-8 63

Fig 6.9: svm-9 63

Fig 7.1: Architecture 65


Fig 8.1: Scripts Directory 68

Fig 8.2: Train Directory 68

Fig 8.3:Image Captured durning Training 69

Fig 8.4: Python Shell after Training 69

Fig 8.5.1: Recognized faces 70

Fig 8.5.2: Script Directory with updated Excel Sheet 70

Fig 8.6 Updated Excel Sheet 71


CHAPTER-1 WABTEC ETHICS

Wabtec Corporation is dedicated to upholding ethical behavior and business practices, as


outlined in its Code of Business Ethics and Conduct (COBEC). The company is committed
to compliance with applicable laws and regulation, and expects its employees to act with
integrity and transparency in all business interactions. Wabtec's mission and vision
statements reflect its commitment to ethical behavior and social responsibility.
1.1 Code of Business Ethics and Conduct (COBEC):
The Code of Business Ethics and Conduct mainly deals with
- It is a company policy.
- Anti-corruption and bribery
- Conflicts of interest
- Fair competition
- Respectful workplace
- Environmental responsibility

1.2 Information Security:


The Wabtec Corporation Code of Business Ethics and Conduct (COBEC) emphasizes the
importance of maintaining the security of company and customer information. This
includes protecting confidential and proprietary information, as well as preventing
unauthorized access, disclosure, or use of sensitive data. The COBEC outlines policies and
procedures for information security, including guidelines for password management,
network security, data encryption, and employee training.
- Never share passwords
- Never connect laptops to public LANs.
- Device should be locked
- Data and information confidentiality.

1.3 Export Compliance:


As a global company, Wabtec Corporation is committed to complying with all applicable
laws and regulations related to the export of goods and technology. The COBEC includes
a section on export compliance, which outlines the company's policies and procedures for
ensuring that all exports are in compliance with relevant regulations, including those related
to licensing, end-use, and embargoed countries.

1
1.4 Dimensions of Data Privacy:
The COBEC also recognizes the importance of protecting the privacy of personal data
and outlines the company's commitment to complying with all applicable privacy laws
and regulations. This includes ensuring that data is collected, processed, and stored in
accordance with applicable laws and industry best practices and that appropriate
measures are taken to prevent unauthorized access, disclosure, or use of personal data.
The COBEC also includes guidelines for handling requests for access to or deletion of
personal data, as well as for notifying individuals in the event of a data breach.

CHAPTER-2 INTRODUCTION TO PYTHON

Python is an interpreted high-level general-purpose programming language. Python's design philosophy


emphasizes code readability with its notable use of significant indentation. Its language constructs as well
as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale
projects.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms,
including structured (particularly, procedural), object-oriented, and functional programming. Python is
often described as a "batteries included" language due to its comprehensive standard library.
Guido van Rossum began working on Python in the late 1980s, as a successor to the ABC programming
and first released it in 1991 as Python 0.9.0.[32] Python 2.0 was released in 2000 and introduced new
features, such as list comprehensions and a garbage collection system using reference counting. Python 3.0
was released in 2008 and was a major revision of the language that is not completely backwardcompatible
and much Python 2 code does not run unmodified on Python 3. Python 2 was discontinued with version
2.7.18 in 2020.
Python consistently ranks as one of the most popular programming languages
2.1 History
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI)
in the Netherlands as a successor to ABC programming language, which was inspired by SETL, capable of
exception handling and interfacing with the Amoeba operating system. Its implementation began in
December 1989. Van Rossum shouldered sole responsibility for the project, as the lead developer, until 12
July 2018, when he announced his "permanent vacation" from his responsibilities as Python's Benevolent
Dictator For Life, a title the Python community bestowed upon him to reflect his long-term commitment
as the project's chief decision-maker In January 2019, active Python core developers elected a 5-member
"Steering Council" to lead the project. As of 2021, the current members of this council are Barry Warsaw,
Brett Cannon, Carol Willing, Thomas Wouters, and Pablo Galindo Salgado.
Python 2.0 was released on 16 October 2000, with many major new features, including a cycledetecting
garbage collector and support for Unicode.

2
Python 3.0 was released on 3 December 2008. It was a major revision of the language that is not completely
backward-compatible. Many of its major features were backported to Python 2.6.x and 2.7.x version
series. Releases of Python 3 include the utility, 2to3 which automates (at least partially) the translation
of Python 2 code to Python 3.
Python 2.7's end-of-life date was initially set at 2015 then postponed to 2020 out of concern that a large
body of existing code could not easily be forward-ported to Python 3. No more security patches or other
improvements will be released for it. With Python 2's end-of-life, only Python 3.6.x and later are supported.
Python 3.9.2 and 3.8.8 were expedited] as all versions of Python (including 2.7) had security issues, leading
to possible remote code execution[56] and web cache poisoning.

2.2 Design philosophy and features


Python is a multi-paradigm programming language. Object-oriented programming and structured
programming are fully supported, and many of its features support functional programming and
aspectoriented programming (including by meta programming and meta objects (magic methods)). Many
other paradigms are supported via extensions, including design by contract and logic programming.
Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage
collector for memory management. It also features dynamic name resolution (late binding), which binds
method and variable names during program execution.
Python's design offers some support for functional programming in the Lisp
filter , map and reduce tradition. It has functions; list comprehensions, dictionaries, sets, and
generator expressions.[64] The standard library has two modules (itertools and
functools) that implement functional tools borrowed from Haskell and Standard ML.
The language's core philosophy is summarized in the document The Zen of Python (PEP 20), which
includes aphorisms such as:

• Beautiful is better than ugly.


• Explicit is better than implicit. • Simple is better than complex.
• Complex is better than complicated.
• Readability counts.
Rather than having all of its functionality built into its core, Python was designed to be highly extensible
(with modules). This compact modularity has made it particularly popular as a means of adding
programmable interfaces to existing applications. Van Rossum's vision of a small core language with a
large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which
espoused the opposite approach. Python strives for a simpler, less-cluttered syntax and grammar while
giving developers a choice in their coding methodology. In contrast to Perl's "there is more than one way
to do it" motto, Python embraces a "there should be one— and preferably only one —obvious way to do
3
it" design philosophy. Alex Martelli, a Fellow at the Python Software Foundation and Python book author,
writes that "To describe something as 'clever' is not considered a compliment in the Python culture.
Python's developers strive to avoid premature optimization, and reject patches to non-critical parts of the
CPython reference implementation that would offer marginal increases in speed at the cost of clarity. When
speed is important, a Python programmer can move time-critical functions to extension modules written in
languages such as C, or use PyPy, a just-in-time compiler. Cython is also available, which translates a
Python script into C and makes direct C-level API calls into the Python interpreter.
An important goal of Python's developers is keeping it fun to use. This is reflected in the language's name—
a tribute to the British comedy group Monty Python—and in occasionally playful approaches to tutorials
and reference materials, such as examples that refer to spam and eggs (from a famous Monty Python sketch)
instead of the standard foo and bar.
A common neologism in the Python community is pythonic, which can have a wide range of meanings
related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is
natural or shows fluency in the language, that it conforms with Python's minimalist philosophy and
emphasis on readability. In contrast, code that is difficult to understand or reads like a rough transcription
from another programming language is called unpythonic.
Users and admirers of Python, especially those considered knowledgeable or experienced, are often referred
to as Pythonistas

2.3 Installation of Python

2.3.1 Introduction

Python is a widely used high-level programming language first launched in 1991. Since then, Python has
been gaining popularity and is considered as one of the most popular and flexible server-side
programming languages.

Unlike most Linux distributions, Windows does not come with the Python programming language by
default. However, you can install Python on your Windows server or local machine in just a few easy
steps.

4
Fig 2.3.1: Python Installation

Prerequisites
• A system running Windows 10 with admin privileges
• Command Prompt (comes with Windows by default)

• A Remote Desktop Connection app (use if you are installing Python on a remote Windows server)

2.3.2 Python 3 Installation on Windows

Step 1: Select Version of Python to Install

The installation procedure involves downloading the official Python .exe installer and running it on your
system.

The version you need depends on what you want to do in Python. For example, if you are working on a
project coded in Python version 2.6, you probably need that version. If you are starting a project from
scratch, you have the freedom to choose.

5
If you are learning to code in Python, we recommend you download both the latest version of Python 2 and
3. Working with Python 2 enables you to work on older projects or test new projects for backward
compatibility.

Step 2: Download Python Executable Installer


1. Open your web browser and navigate to the Downloads for Windows section of the official Python
website.
2. Search for your desired version of Python. At the time of publishing this article, the latest Python 3
release is version 3.7.3, while the latest Python 2 release is version 2.7.16.
3. Select a link to download either the Windows x86-64 executable installer or Windows x86
executable installer. The download is approximately 25MB.

Fig 2.3.2: Python Releases for Windows

Step 3: Run Executable Installer

1. Run the Python Installer once downloaded. (In this example, we have downloaded Python 3.7.3.)

2. Make sure you select the Install launcher for all users and Add Python 3.7 to PATH checkboxes. The
latter places the interpreter in the execution path. For older versions of Python that do not support the
Add Python to Path checkbox,

3. Select Install Now – the recommended installation options.

6
Fig 2.3.3: Python 3.7.3

For all recent versions of Python, the recommended installation options include Pip and IDLE. Older
versions might not include such additional features.

4. The next dialog will prompt you to select whether to Disable path length limit. Choosing this option
will allow Python to bypass the 260-character MAX_PATH limit. Effectively, it will enable Python to use
long path names.

7
Fig 2.3.4: Python Setup

The Disable path length limit option will not affect any other system settings. Turning it on will resolve
potential name length issues that may arise with Python projects developed in Linux.

Step 4: Verify Python Was Installed On Windows

1. Navigate to the directory in which Python was installed on the system. In our case, it is
C:\Users\Username\AppData\Local\Programs\Python\Python37 since we have installed the
latest version.
2. Double-click python.exe.
3. The output should be similar to what you can see below:

8
Fig 2.3.5: Python Command Prompt

Step 5: Verify Pip Was Installed

If you opted to install an older version of Python, it is possible that it did not come with Pip preinstalled.
Pip is a powerful package management system for Python software packages. Thus, make sure that you
have it installed.

We recommend using Pip for most Python packages, especially when working in virtual environments.

To verify whether Pip was installed:

1. Open the Start menu and type "cmd."


2. Select the Command Prompt application.
3. Enter pip -V in the console. If Pip was installed successfully, you should see the following output:

9
Fig 2.3.6: Python Terminal

Pip has not been installed yet if you get the following output:

'pip' is not recognized as an internal or external command,

Operable program or batch file.

If your version of Python is missing Pip, see our article How to Install Pip to Manage Python Packages on
Windows.

Step 6: Add Python Path to Environment Variables (Optional)

We recommend you go through this step if your version of the Python installer does not include the Add
Python to PATH checkbox or if you have not selected that option. Setting up the Python path to system
variables alleviates the need for using full paths. It instructs Windows to look through all the PATH folders
for “python” and find the install folder that contains the python.exe file.

1. Open the Start menu and start the Run app.

10
Fig 2.3.7: Windows Run app

2. Type sysdm.cpl and click OK. This opens the System Properties window.

3. Navigate to the Advanced tab and select Environment Variables.

4. Under System Variables, find and select the Path variable.

5. Click Edit.

6. Select the Variable value field. Add the path to the python.exe file preceded with a semicolon (;). For
example, in the image below, we have added ";C:\Python34."

Fig 2.3.8: Edit System Variable

7. Click OK and close all windows.

By setting this up, you can execute Python scripts like this: Python script.py

Instead of this: C:/Python34/Python script.py

As you can see, it is cleaner and more manageable.

Step 7: Install virtualnv (Optional)

You have Python, and you have Pip to manage packages. Now, you need one last software package -
virtualnv. Virtualnv enables you to create isolated local virtual environments for your Python projects.

Why use virtualnv

Python software packages are installed system-wide by default. Consequently, whenever a single
projectspecific package is changed, it changes for all your Python projects. You would want to avoid this,
and having separate virtual environments for each project is the easiest solution.

11
To install virtualnv:

1. Open the Start menu and type "cmd."

2. Select the Command Prompt application.

3. Type the following pip command in the console:

C:\Users\Username> pip install virtualenv

Upon completion, virtualnv is installed on your system.

In this tutorial, we detailed how to install Python 3.7.3 on Windows. If you are installing a different version
of Python, you can expect a similar process.

2.4 Syntax and Semantics


Python is meant to be an easily readable language. Its formatting is visually uncluttered, and it often uses
English keywords where other languages use punctuation. Unlike many other languages, it does not use
curly brackets to delimit blocks, and semicolons after statements are allowed but are rarely, if ever, used.
It has fewer syntactic exceptions and special cases than C or Pascal.
2.4.1 Indentation
Python uses whitespace indentation, rather than curly brackets or keywords, to delimit blocks. An increase
in indentation comes after certain statements; a decrease in indentation signifies the end of the current
block. Thus, the program's visual structure accurately represents the program's semantic structure. This
feature is sometimes termed the off-side rule, which some other languages share, but in most languages
indentation doesn't have any semantic meaning. The recommended indent size is four spaces.
Statements and control flow
Python's statements include (among others):

• The assignment statement, using a single equals sign =.


• The if statement, which conditionally executes a block of code, along with else and elif (a contraction
of else-if).
• The for statement, which iterates over an iterable object, capturing each element to a local variable for
use by the attached block.
• The while statement, which executes a block of code as long as its condition is true.
• The try statement, which allows exceptions raised in its attached code block to be caught and handled
by except clauses; it also ensures that clean-up code in a finally block will always be run regardless of
how the block exits.
• The raise statement, used to raise a specified exception or re-raise a caught exception.
• The class statement, which executes a block of code and attaches its local namespace to a class, for use
in object-oriented programming.
• The def statement, which defines a function or method.

12
• The with statement, which encloses a code block within a context manager (for example, acquiring a
lock before the block of code is run and releasing the lock afterwards, or opening a file and then closing
it), allowing resource-acquisition-is-initialization (RAII)-like behavior and replaces a common
try/finally idiom.
• The break statement, exits from a loop.
• The continue statement, skips this iteration and continues with the next item.
• The del statement, removes a variable, which means the reference from the name to the value is deleted
and trying to use that variable will cause an error. A deleted variable can be reassigned.
• The pass statement, which serves as a NOP. It is syntactically needed to create an empty code block.
• The assert statement, used during debugging to check for conditions that should apply.
• The yield statement, which returns a value from a generator function and yield is also an operator. This
form is used to implement coroutines.
• The return statement, used to return a value from a function.
• The import statement, which is used to import modules whose functions or variables can be used in the
current program.
The assignment statement( =) operates by binding a name as a reference to a separate, dynamicallyallocated
object. Variables may be subsequently rebound at any time to any object. In Python, a variable name is a
generic reference holder and doesn't have a fixed data type associated with it. However, at a given time, a
variable will refer to some object, which will have a type. This is referred to as dynamic typing and is
contrasted with statically-typed programming languages, where each variable may only contain values of
a certain type.
Python does not support tail call optimization or first-class continuations, and, according to Guido van
Rossum, it never will. However, better support for coroutine-like functionality is provided, by extending
Python's generators. Before 2.5, generators were lazy iterators; information was passed unidirectionally out
of the generator. From Python 2.5, it is possible to pass information back into a generator function, and
from Python 3.3, the information can be passed through multiple stack levels.
2.4.2 Expressions
Some Python expressions are similar to those found in languages such as C and Java, while some are not:

• Addition, subtraction, and multiplication are the same, but the behavior of division differs. There are
two types of divisions in Python. They are floor division (or integer division)// and
floatingpoint/division. Python also uses the ** operator for exponentiation.
• From Python 3.5, the new@ infix operator was introduced. It is intended to be used by libraries such
as NumPy for matrix multiplication.
• From Python 3.8, the syntax:=, called the 'walrus operator' was introduced. It assigns values to variables
as part of a larger expression.[87]
• In Python,== compares by value, versus Java, which compares numeric by value and objects by
reference. (Value comparisons in Java on objects can be performed with the equals()
method.) is Python's operator may be used to compare object identities (comparison by reference). In
Python,
comparisons may be chained, for example a<=b<=c.
• Python uses the words and, or not for its Boolean operators rather than the symbolic &&,||,! used in
Java and C.
• Python has a type of expression termed a list comprehension as well as a more general expression
termed a generator expression.
13
• Anonymous functions are implemented using lambda expressions; however, these are limited in that
the body can only be one expression.

• Conditional expressions in Python are written as x if c else y (different in order of operands from the
c?x:y operator common to many other languages).
• Python makes a distinction between lists and tuples. Lists are written as[1,2,3], are mutable, and cannot
be used as the keys of dictionaries (dictionary keys must be immutable in Python). Tuples are written
as(1,2,3), are immutable and thus can be used as the keys of dictionaries, provided all elements of the
tuple are immutable. The + operator can be used to concatenate two tuples, which does not directly
modify their contents, but rather produces a new tuple containing the elements of both provided tuples.
Thus, given the variable t initially equal to(1,2,3) executing t=t+(4,5) first evaluates t=t+(4,5) which
yields(1,2,3,4,5) which is then assigned back to t, thereby effectively "modifying the contents" of t ,
while conforming to the immutable nature of tuple objects. Parentheses are optional for tuples in
unambiguous contexts.
• Python features sequence unpacking wherein multiple expressions, each evaluating to anything that can
be assigned to (a variable, a writable property, etc.), are associated in an identical manner to that forming
tuple literals and, as a whole, are put on the left-hand side of the equal sign in an assignment statement.
The statement expects an iterable object on the right-hand side of the equal sign that produces the same
number of values as the provided writable expressions when iterated through and will iterate through
it, assigning each of the produced values to the corresponding expression on the left.
• Python has a "string format" operator %. This functions analogously to printf format strings in C, e.g.
"spam=%s eggs=%d" % ("blah", 2) evaluates to "spam=blah eggs=2". In Python 3 and 2.6+, this was
supplemented by the format() method of the str class, e.g. "spam={0} eggs={1}".format("blah", 2).
Python 3.6 added "f-strings": blah = "blah"; eggs = 2; f'spam={blah} eggs={eggs}'.
• Strings in Python can be concatenated, by "adding" them (same operator as for adding integers and
floats). E.g., "spam" + "eggs" returns "spameggs". Even if your strings contain numbers, they are still
added as strings rather than integers. E.g. "2" + "2" returns "22".Python has various kinds of string
literals:
o Strings delimited by single or double quote marks. Unlike in Unix shells, Perl and Perl-influenced
languages, single quote marks and double quote marks function identically. Both kinds of string
use the backslash (\) as an escape character. String interpolation became available in Python 3.6 as
"formatted string literals".[93] o Triple-quoted strings, which begin and end with a series of three
single or double quote marks. They may span multiple lines and function like here documents in shells,
o Raw string varieties, denoted by prefixing the string literal with an r. Escape sequences are not
interpreted; hence raw strings are useful where literal backslashes are common, such as regular
Perl and Ruby.
expressions and Windows-style paths. Compare "@ -quoting" in C#.
Python has array index and array slicing expressions on lists, denoted as a[key], a[start:stop] or
a[start:stop:step]. Indexes are zero-based, and negative indexes are relative to the end. Slices take elements
from the start index up to, but not including, the stop index. The third slice parameter, called step or stride,
allows elements to be skipped and reversed. Slice indexes may be omitted, for example a[:] returns a copy
of the entire list. Each element of a slice is a shallow copy.In Python, a distinction between expressions and
statements is rigidly enforced, in contrast to languages such as Common Lisp, Scheme, or Ruby. This leads
to duplicating some functionality. For example:

• List comprehensions vs.for-loops


14
• Conditional expressions vs.if blocks
• The eval() vs. exec() built-in functions (in Python 2, exec is a statement); the former is for expressions,
the latter is for statements.

Statements cannot be a part of an expression, so list and other comprehensions or lambda expressions, all
being expressions, cannot contain statements. A particular case of this is that an assignment statement such
as a = 1 cannot form part of the conditional expression of a conditional statement. This has the advantage
of avoiding a classic C error of mistaking an assignment operator = for an equality operator == in
conditions: if (c = 1) { ... } is syntactically valid (but probably unintended) C code but if c = 1: ... causes a
syntax error in Python.
2.4.3 Methods
Methods on objects are functions attached to the object's class; the syntax instance. Method(argument) is,
for normal methods and functions, syntactic sugar for Class. Method (instance, argument). Python methods
have an explicit self-parameter to access instance data, in contrast to the implicit self (or this) in some other
object-oriented programming languages (e.g., C++, Java, Objective-C, or Ruby).
2.4.4 Typing
Python uses duck typing and has typed objects but untyped variable names. Type constraints are not
checked at compile time; rather, operations on an object may fail, signifying that the given object is not of
a suitable type. Despite being dynamically-typed, Python is strongly-typed, forbidding operations that are
not well-defined (for example, adding a number to a string) rather than silently attempting to make sense
of them.
Python allows programmers to define their own types using classes, which are most often used for
objectoriented programming. New instances of classes are constructed by calling the class (for example,
SpamClass() or EggsClass()), and the classes are instances of the metaclass type (itself an instance of itself),
allowing metaprogramming and reflection.
Before version 3.0, Python had two kinds of classes: old-style and new-style. The syntax of both styles is
the same, the difference being whether the class object is inherited from, directly or indirectly (all newstyle
classes inherit from object and are instances of type). In versions of Python 2 from Python 2.2 onwards,
both kinds of classes can be used. Old-style classes were eliminated in Python 3.0.
The long-term plan is to support gradual typing and from Python 3.5, the syntax of the language allows
specifying static types but they are not checked in the default implementation, CPython. An experimental
optional static type checker named mypy supports compile-time type checking.
2.5 Python Operators
2.5.1 Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication and division. There are 7 arithmetic operators in Python:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
6. Exponentiation
15
7. Floor division

Arithmetic Operators

2.5.2 Logical Operators

2.5.3 Comparison operator

16
2.5.4 Identity operator

2.5.5 Membership

2.5.6 Assignment operator

17
2.5.7 Bitwise Operators

2.6 Python Collections

There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate members.


• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is ordered and changeable. No duplicate members.

2.6.1 Python Lists

Lists are just like dynamic sized arrays, declared in other languages (vector in C++ and Array List in Java).
Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may
contain Datatypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered
even after their creation.

List in Python are ordered and have a definite count. The elements in a list are indexed according to a
definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has
its definite place in the list, which allows duplicating of elements in the list, with each element having its
own distinct place and credibility.
Creating a List
Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, list
doesn’t need a built-in function for creation of list.

18
Creating a list with multiple distinct or duplicate elements

A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate
values can be passed as a sequence at the time of list creation.
Adding Elements to a List
Using append() method
Elements can be added to the List by using built-in append() function. Only one element at a time can be
added to the list by using append() method, for addition of multiple elements with the append() method,
loops are used. Tuples can also be added to the List with the use of append method because tuples are
immutable. Unlike Sets, Lists can also be added to the existing list with the use of append() method.

Using insert() method append() method only works for addition of elements at the end of the List, for
addition of element at the desired position, insert() method is used. Unlike append() which
takes only one argument, insert() method requires two arguments(position, value).

Using extend() method


Other than append() and insert() methods, there’s one more method for Addition of elements, extend(), this
method is used to add multiple elements at the same time at the end of the list.

Accessing elements from the List


In order to access the list items, refer to the index number. Use, the index operator [] to access an
item in a list. The index must be an Integer Nested list are accessed using nested indexing.

Negative indexing In Python, negative sequence indexes represent positions from the end of the
array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-
last item, etc.
Removing Elements from the List
Using remove() method
Elements can be removed from the List by using built-in remove() function but an Error arises if
element doesn’t exist in the set. Remove() method only removes one element at a time, to remove
range of elements, iterator is used. The remove() method removes the specified item.

Using pop() method


Pop() function can also be used to remove and return an element from the set, but by default it
removes only the last element of the set, to remove element from a specific position of the List,
index of the element is passed as an argument to the pop() method.

19
Slicing of a List
In Python List, there are multiple ways to print the whole List with all the elements, but to print a
specific range of elements from the list, we use Slice operation. Slice operation is performed on
Lists with the use of a colon(:). To print elements from beginning to a range use [: Index], to print
elements from end-use [:-Index], to print elements from specific Index till the end use [Index:], to
print elements within a range, use [Start Index:End Index] and to print the whole List with the use
of slicing operation, use [:]. Further, to print the whole List in reverse order, use [::1].

2.6.2 Tuples in Python

A Tuple is a collection of Python objects separated by commas. In some ways a tuple is similar to
a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which
are mutable. Tuples are enclosed in open brackets

2.6.3 Sets in Python

A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Python’s set class represents the mathematical notion of a set. The major advantage of using a set,
as opposed to a list, is that it has a highly optimized method for checking whether a specific element
is contained in the set. This is based on a data structure known as a hash table. Since sets are
unordered, we cannot access items using indexes like we do in lists. This is based on a data structure
known as a hash table.
If Multiple values are present at the same index position, then the value is appended to that index
position, to form a Linked List. In, Python Sets are implemented using dictionary with dummy
variables, where key beings the members set with greater optimizations to the time complexity.

Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that produce
a result without affecting the frozen set or sets to which they are applied. While elements of a set
can be modified at any time, elements of the frozen set remain the same after creation. If no
parameters are passed, it returns an empty frozen set.
Adding elements
Insertion in set is done through set.add() function, where an appropriate record value is created to
store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case
it can become O(n).
Union
Two sets can be merged using union() function or | operator. Both Hash Table values are accessed
and traversed with merge operation perform on them to combine the elements, at the same time
duplicates are removed. Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two
sets whose union needs to be done.
20
Intersection
This can be done through intersection () or & operator. Common Elements are selected. They are
similar to iteration over the Hash lists and combining the same values on both the Table. Time
Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to
be done.
Difference
To find difference in between sets. Similar to find difference in linked list. This is done through
difference () or – operator. Time complexity of finding difference s1 – s2 is O(len(s1)) Clearing
sets
Clear() method empties the whole set.

2.6.4 Python Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds key: value
pair. Key value is provided in the dictionary to make it more optimized.
Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other
corresponding pair element being its Key: value. Values in a dictionary can be of any datatype and
can be duplicated, whereas keys can’t be repeated and must be immutable.

Nested

Fig 2.6..1 : Nested Dictionary

21
Adding elements to a Dictionary
In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added
to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value
in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to
an existing Dictionary.

Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
Accessing element of a nested dictionary
In order to access the value of any key in nested dictionary, use indexing [] syntax.
Removing Elements from Dictionary
Using del keyword
In Python Dictionary, deletion of keys can be done by using the del keyword. Using del keyword,
specific values from a dictionary as well as whole dictionary can be deleted. Items in a Nested
dictionary can also be deleted by using del keyword and providing specific nested key and
particular key to be deleted from that nested Dictionary.

Using pop() method


Pop() method is used to return and delete the value of the key specified.

Using popitem() method


The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.
Using clear() method

All the items from a dictionary can be deleted at once by using clear() method.

2.7 Conditional Statements


2.7.1 Python if else

They’re come situations in real life when we need to make some decisions and based on these decisions,
we decide what should we do next. Similar situations arise in programming also where we need to make
some decisions and based on these decisions, we will execute the next block of code.
Decision making statements in programming languages decides the direction of flow of program execution.
Decision making statements available in python are:
• if statement
• if..else statements
• nested if statements
• if-elif ladder
22
• Short Hand if statement
• Short Hand if-else statement 2.7.2 if statement if statement is the simplest decision-making statement.
It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a
certain condition is true then a block of statement is executed otherwise not.
Syntax: if
condition:
# Statements to execute if
# Condition is true
Here, condition after evaluation will be either true or false. if statement accepts Boolean values – if the
value is true then it will execute the block of statements below it otherwise not. We can use condition with
bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So, the block under an if statement will be
identified as shown in the below example: if condition: statement1 statement2
# Here if the condition is true, if block #
Will consider only statement1 to be inside #
Its block.

Flow chart:

23
Fig
2.7.1 : if else

2.7.3 if- else


The if statement alone tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t. But what if we want to do something else if the condition is false. Here
comes the else statement. We can use the else statement with if statement to execute a block of code when
the condition is false.

Syntax: if
(condition):
# Executes this block if
# condition is true

else:
# Executes this block if
# condition is false

Flow Chart:

24
Fig 2.7.2 : if elif

2.7.4 Nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements means, an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e.,
we can place an if statement inside another if statement.
Syntax: if
(condition1):
# Executes when condition1 is true if
(condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Flow chart:

25
Fig 2. 7.3: Nested if

2.7.5 if-elseif-else ladder


Here, a user can decide among multiple options. The if statements are executed from the top down. As soon
as one of the conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

Syntax: if
(condition):
statement elif
(condition):
statement else:
statement

Flow Chart:

26
Fig 2.7.4: if-elseif-else ladder

2.8 Python Loops


2.8.1 Python While Loop

In Python, While Loops 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. While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn’t specified explicitly in advance. Syntax:
while expression:
statement(s)
Statements represent all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements. When a while loop is executed, expr is first evaluated in a Boolean
context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then
the body is executed again and this continues until the expression becomes false.

Working of While Loop:

27
Fig 2.8.1: While Loop

Single statement while block


Just like the if block, if the while block consists of a single statement the we can declare the entire
loop in a single line. If there are multiple statements in the block that makes up the loop body, they
can be separated by semicolons (;).
2.8.2 While-else loop
As discussed above, while loop executes the block until a condition is satisfied. When the condition
becomes false, the statement immediately after the loop is executed. The else clause is only
executed when your while condition becomes false. If you break out of the loop, or if an exception
is raised, it won’t be executed.

2.8.3 Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as
found in other object-orientated programming languages.

28
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

2.8.4 Loop Control Statements


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.
• Continue Statement: It returns the control to the beginning of the loop.
• Break Statement: It brings control out of the loop.
• Pass Statement: We use pass statement to write empty loops. Pass is also used for empty
control statements, functions and classes.
2.9 Functions in Python
A function in Python is an aggregation of related statements designed to perform a computational, logical,
or evaluative task. The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different inputs, we can call the
function to reuse code contained in it over and over again.
Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and
organized.
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. As you already know,
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.
• 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 these parentheses.
• 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 is indented.
• 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 return None.
Syntax: def
function_name(parameters):
"""docstring"""
statement(s)

Docstring
The first string after the function is called the Document string or Docstring in short. This is used to describe
the functionality of the function. The use of docstring in functions is optional but it is considered a good
practice.

29
The below syntax can be used to print out the docstring of a function:

Syntax: print(function_name.__doc__)

The return statement


The return statement is used to exit from a function and go back to the function caller and return the
specified value or data item to the caller.
Syntax: return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is returned to the end of
the function execution. If none of the above is present with the return statement a None object is returned.

Function Classifications
You can call a function by using the following types of formal arguments-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
2.9.1 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.

Example: #!/usr/bin/python3 # Function definition is here

def printinfo( name, age ):

"This prints a passed info into this function" print ("Name: ", name)

print ("Age ", age) return # Now you can call printinfo function

printinfo( age=50, name="miki"

2.9.2 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. The following example gives an idea on default arguments, it prints default age if it
is not passed.

Example: def printinfo( name, age = 35 ):

30
"This prints a passed info into this function"

print ("Name: ", name)

print ("Age ", age) return # Now you can call printinfo function printinfo( age=50,

name="miki" ) printinfo( name="miki" )

2.9.3 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 given below

def functionname([formal_args,] *var_args_tuple ):

"function_docstring" f

unction_suite return [expression]

An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function call.
Following is a simple example

2.9.4 The Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by using the
def keyword. You can use the lambda keyword to create small anonymous functions.

• Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression.
• Lambda functions have their own local namespace and cannot access variables other than those in
their parameter list and those in the global namespace.
• Although it appears that lambdas are a one-line version of a function, they are not equivalent to
inline statements in C or C++, whose purpose is to stack allocation by passing function, during
invocation for performance reasons.
Syntax: lambda [arg1 [,arg2,.....argn]]:expression

2.10 MODULES
A module allows you to logically organize your Python code. Grouping related code into a module makes
the code easier to understand and use. A module is a Python object with arbitrarily named attributes that
you can bind and reference. Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.
31
2.10.1 The import Statement

When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module hello.py, you need to put the following command at the top of the script-

#!/usr/bin/python3

# Import module support import support

# Now you can call defined function that module as follows support.print_func("Zara")

Output: Hello : Zara

The from...import Statement

Python's from statement lets you import specific attributes from a module into the current namespace. The
from...import has the following syntax

from modname import name1[, name2[, ... nameN]]

2.10.2 Executing Modules as Scripts

Within a module, the module’s name (as a string) is available as the value of the global variable
__name__. The code in the module will be executed, just as if you imported it, but with the __name__ set
to "__main__".

Locating Modules

When you import a module, the Python interpreter searches for the module in the following sequences-

• The current directory.


• If the module is not found, Python then searches each directory in the shell variable PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python3/. The module search path is stored in the system module sys as the sys.path
variable. The sys.path variable contains the current directory, PYTHONPATH, and the
installationdependent default.

2.10.3 Namespaces and Scoping

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys)
and their corresponding objects (values).

• A Python statement can access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable shadows the global variable.

32
• Each function has its own local namespace. Class methods follow the same scoping rule as ordinary
functions
• Python makes educated guesses on whether variables are local or global. It assumes that any
variable assigned a value in a function is local.
• Therefore, in order to assign a value to a global variable within a function, you must first use the
global statement.
• The statement global VarName tells Python that VarName is a global variable. Python stops
searching the local namespace for the variable. For example, we define a variable Money in the
global namespace. Within the function Money, we assign Money a value, therefore Python assumes
Money as a local variable. However, we accessed the value of the local variable Money before
setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the
problem. Example:
#!/usr/bin/python3 Money = 2000 def
AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)

AddMoney()

print (Money)

2.10.4 The globals() and locals() Functions

The globals() and locals() functions can be used to return the names in the global and local namespaces
depending on the location from where they are called.

• If locals() is called from within a function, it will return all the names that can be accessed locally
from that function.
• If globals() is called from within a function, it will return all the names that can be accessed globally
from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys()
function.

33
2.11 Python Packages
A package is a hierarchical file directory structure that defines a single Python application environment
that consists of modules and sub packages and sub-sub packages, and so on. A package is basically a
directory with Python files and a file with the name __init__.py. every directory inside of the Python
path, which contains a file named __init__.py, will be treated as a package by Python. It's possible to put
several modules into a Package. Packages supports nested packages

sound

|-- effects

| |-- echo.py

| |-- __init__.py

| |-- reverse.py

| `-- surround.py

|-- filters

| |-- equalizer.py

| |-- __init__.py |

|-- karaoke.py

| `-- vocoder.py

|-- formats

| |-- aiffread.py

`-- __init__.py

Similarly, we have other two files having different functions with the same name as above. They are –

Phone/Isdn.py file having function Isdn()

Phone/G3.py file having function G3()

#!/usr/bin/python3

def Pots(): print ("I'm

Pots Phone")
34
• To make all of your functions available when you have imported Phone, you need to put explicit
import statements in __init__.py from Pots import Pots from Isdn import Isdn from G3 import
G3
• After you add these lines to __init__.py, you have all of these classes available when you import
the Phone package.
#!/usr/bin/python3

# Now import your Phone Package.

import Phone

Phone.Pots()

Phone.Isdn()

Phone.G3()

2.12 Regular Expressions


A regular expression is a special sequence of characters that helps you match or find other strings or sets
of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX
world.
The module re provides full support for Perl-like regular expressions in Python. The re module raises the
exception re.error if an error occurs while compiling or using a regular expression. We would cover two
important functions, which would be used to handle regular expressions.

Nevertheless, a small thing first: There are various characters, which would have special meaning when
they are used in regular expression. To avoid any confusion while dealing with regular expressions, we
would use Raw Strings asr'expression'. Python has a built-in package called re, which can be used to work
with Regular Expressions

>>>import re

Basic patterns that match single chars

• a, X, 9, < -- ordinary characters just match themselves exactly.


• (a period) -- matches any single character except newline '\n'
• \w -- matches a "word" character: a letter or digit or underbar [a-zA-Z0-9_].
• \W -- matches any non-word character.
• \b -- boundary between word and non-word
• \s -- matches a single whitespace character -- space, newline, return, tab
• \S -- matches any non-whitespace character.
• \t, \n, \r -- tab, newline, return
35
• \d -- decimal digit [0-9]
• ^ = matches start of the string
• $ = match the end of the string
• \ -- inhibit the "specialness" of a character.

2.12.1Metacharacters:

Metacharacters are considered as the building blocks of regular expressions. Regular expressions are
patterns used to match character combinations in the strings. Metacharacter has special meaning in finding
patterns and are mostly used to define the search criteria and any text manipulations.

Some of the mostly used metacharacters along with their uses are as follows:Meta characters for Python
regular expressions.. The table lists some of the standard escape characters that can be used in Perl regular
expressions. These expressions are supported in the EmailPlusRule and EmailPlusTemplate records.

Character Description Example

[] A set of characters "[a-m]"

36
\ Signals a special sequence (can also be used to escape special "\d"
characters)

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "world$"

* Zero or more occurrences "aix*"

+ One or more occurrences "aix+"

{} Exactly the specified number of occurrences "al{2}"

| Either or "falls|stays"

() Capture and group ()

2.12.2 Set

A set is a set of characters inside a pair of square brackets [] with a special meaning

Set Description

[arn] Returns a match where one of


the specified characters (a, r,
or n) are present

[a-n] Returns a match for any lower


case character, alphabetically
between a and n

37
[^arn] Returns a match for any
character EXCEPT a, r, and n

[0123] Returns a match where any of


the specified digits (0, 1, 2, or
3) are present

[0-9] Returns a match for any digit


between 0 and 9

[0-5][0-9] Returns a match for any two-


digit numbers from 00 and 59

[a-zA-Z] Returns a match for any


character alphabetically
between a and z, lower case
OR upper case

[+] In sets, +, *, ., |, (), $,{} has


no special meaning, so [+]
means: return a match for
any + character in the string

12.4 Functions in RegEx


findall() :function returns a list containing all matches, If no matches are found, an empty Example:

import re txt = "The


rain in Spain" x=
re.findall("ai", txt)
print(x)

#output: [‘ai’, ‘ai’]

search():The search() function searches the string for a match, and returns a Match object if there is a
match. If there is more than one match, only the first occurrence of the match will be returned:

Example:

import re txt =
"The rain in Spain" x=
re.search("\s", txt)
print("The 1st whitespace character is located in position:", x.start())

#output: The 1st whitespace character is located in position: 3 split():


38
The split() function returns a list where the string has been split at each match

Example: import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)

#Output:[‘The’,‘rain’,‘in’, ‘Spain’] Sub():

The sub() function replaces the matches with the text of your choice

Example:import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)

Output: The9rain9in9Spain

2.12.5 Match Object:

A Match Object is an object containing information about the search and the result, The Match object
has properties and methods used to retrieve information about the search, and the result

1..span() method returns a tuple containing starting and ending index of the matched string. If group did
not contribute to the match it returns(-1,-1). Parameters: group (optional) By default this is 0. Return: A
tuple containing starting and ending index of the matched string. Returns a tuple containing the start-, and
end positions of the match.

2..string returns the string passed into the function

3.group()A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group
by placing the regex pattern inside the set of parentheses () and
returns the part of the string where there was a match

2.13 Object Oriented Programming


Object Oriented means directed towards objects. In other words, it means functionally directed towards
modelling objects. This is one of the many techniques used for modelling complex systems by describing
a collection of interacting objects via their data and behavior. Python, an Object-Oriented programming
(OOP), is a way of programming that focuses on using objects and classes to design and build applications.
Major pillars of Object-Oriented Programming (OOP) are Inheritance, Polymorphism, Abstraction, ad
Encapsulation. Object Oriented Analysis (OOA) is the process of examining a problem, system or task and
identifying the objects and interactions between them.

Python was designed with an object-oriented approach. OOP offers the following advantages:

39
• Provides a clear program structure, which makes it easy to map real world problems and their
solutions.
• Facilitates easy maintenance and modification of existing code.
• Enhances program modularity because each object exists independently and new features can be
added easily without disturbing the existing ones.
• Presents a good framework for code libraries where supplied components can be easily adapted
and modified by the programmer.
• Imparts code reusability

Fig 2.13.1 : Oops

Let us understand each of the pillars of object-oriented programming in brief:

Encapsulation

This property hides unnecessary details and makes it easier to manage the program structure. Each object’s
implementation and state are hidden behind well-defined boundaries and that provides a clean and simple
interface for working with them. One way to accomplish this is by making the data private.

Inheritance

Inheritance, also called generalization, allows us to capture a hierarchal relationship between classes and
objects. For instance, a ‘fruit’ is a generalization of ‘orange’. Inheritance is very useful from a code reuse
perspective. Abstraction

This property allows us to hide the details and expose only the essential features of a concept or object.
For example, a person driving a scooter knows that on pressing a horn, sound is emitted, but he has no idea
about how the sound is actually generated on pressing the horn. Polymorphism Poly-morphism means
many forms. That is, a thing or action is present in different forms or ways. One good example of
polymorphism is constructor overloading in classes
40
2.13.1 Classes

have methods and attributes In Python, creating a method defines a class behavior. The word method is the
OOP name given to a function that is defined within a class. To sum up:

• Class functions is synonym for methods


• Class variables is synonym for name attributes.

• Class – a blueprint for an instance with exact behavior.


• Object – one of the instances of the class, perform functionality defined in the class.
• Type – indicates the class the instance belongs to
• Attribute – Any object value: object. Attribute
• Method – a “callable attribute” defined in the class
Creation and Instantiation

The following code shows how to create our first class and then its instance. Here we have created
a class called MyClass and which does not do any task. The argument object in MyClass class involves
class inheritance and will be discussed in later chapters. pass in the above code indicates that this block is
empty, that is it is an empty class definition.

Instance Methods

A function defined in a class is called a method. An instance method requires an instance in order to call it
and requires no decorator. When creating an instance method, the first parameter is always self. Though
we can call it (self) by any other name, it is recommended to use self, as it is a naming convention.

2.13.2 Init Constructor

The __init__ method is implicitly called as soon as an object of a class is instantiated. This will initialize
the object.

The line of code shown above will create a new instance and assigns this object to the local variable x. The
instantiation operation, that is calling a class object, creates an empty object. Many classes like to create
objects with instances customized to a specific initial state. Therefore, a class may define a special method
named ‘ __init__() ‘ as shown:

Python calls __init__ during the instantiation to define an additional attribute that should occur when a
class is instantiated that may be setting up some beginning values for that object or running a routine
required on instantiation. So in this example, a new, initialized instance can be obtained by:

The __init__() method can have single or multiple arguments for a greater flexibility. The init stands for
initialization, as it initializes attributes of the instance. It is called the constructor of a class.

41
2.13.3 Inheritance

One of the major advantages of Object-Oriented Programming is re-use. Inheritance is one of the
mechanisms to achieve the same.

Fig 2.13.2 : Types of inheritance

42
Inheritance allows programmer to create a general or a base class first and then later extend it to more
specialized class. It allows programmer to write better code. Using inheritance you can use or inherit all
the data fields and methods available in your base class. Later you can add you own methods and data
fields, thus inheritance provides a way to organize code, rather than rewriting it from scratch. In
objectoriented terminology when class X extend class Y, then Y is called super/parent/base class and X is
called subclass/child/derived class. One point to note here is that only data fields and method which are not
private are accessible by child classes. Private data fields and methods are accessible only inside the class.
Syntax to create a derived class is

class BaseClass:

Body of base class

class DerivedClass(BaseClass):

Body of derived class

There are five types of inheritances:


1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance Single Inheritance:
This type of inheritance enables a subclass or derived class to inherit properties and characteristics of the
parent class, this avoids duplication of code and improves code reusability. Multiple Inheritance
This inheritance enables a child class to inherit from more than one parent class. This type of inheritance
is not supported by java classes, but python does support this kind of inheritance. It has a massive advantage
if we have a requirement of gathering multiple characteristics from different classes. print(“first number is
: “,c.demo1)
print(“second number is : “,c.demo2)

Multilevel Inheritance:
In multilevel inheritance, the transfer of the properties of characteristics is done to more than one class
hierarchically. To get a better visualization we can consider it as an ancestor to grandchildren relation or a
root to leaf in a tree with more than one level. def speciality(self):
print(“electric car runs on electricity”)
electric=electric_car()
electric.speciality()
electric.wheels()
electric.functioning()

Hierarchical Inheritance:
This inheritance allows a class to host as a parent class for more than one child class or subclass. This
provides a benefit of sharing the functioning of methods with multiple child classes, hence avoiding code
duplication. Hybrid Inheritance:
An inheritance is said hybrid inheritance if more than one type of inheritance is implemented in the same
code. This feature enables the user to utilize the feature of inheritance at its best. This satisfies the
requirement of implementing a code that needs multiple inheritances in implementation.
43
2.13.4 Encapsulation

Encapsulation is one of the fundamentals of OOP. OOP enables us to hide the complexity of the internal
working of the object which is advantageous to the developer in the following ways:

• Simplifies and makes it easy to understand to use an object without knowing the internals
• Any change can be easily manageable. Object-oriented programming relies heavily on
encapsulation.

Fig 2.13.1 : Encapsulation

The terms encapsulation and abstraction (also called data hiding) are often used as synonyms. They are
nearly synonymous, as abstraction is achieved through encapsulation. Encapsulation provides us the
mechanism of restricting the access to some of the object’s components, this means that the internal
representation of an object can’t be seen from outside of the object definition. Access to this data is typically
achieved through special methods: Getters and Setters. OOP in Python 32 This data is stored in instance
attributes and can be manipulated from anywhere outside the class. To secure it, that data should only be
accessed using instance methods. Direct access should not be permitted. It is one of the fundamental
concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit. This puts restrictions on accessing variables and methods directly and
can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only
be changed by an object’s method. Those types of variables are known as private variable. A class is an
example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
2.13.5 Method Overriding

It allows a child class to provide a specific implementation of a method that is already provided by one of
its parent classes. When a method in a child class has the same name, same parameters or signature and
same return type(or sub-type) as a method in its parent class, then the method in the subclass is said to
override the method in the super-class. The data should be stored only if it is correct and valid, using
Exception handling constructs.. It could be a string, a number, or a list. So we need to check onto above
code to ensure correctness of being stored.

2.13.6 Abstraction
Abstraction is used to hide the internal functionality of the function from the users. The users only interact
with the basic implementation of the function, but inner working is hidden. In Python, an abstraction is
used to hide the irrelevant data/class in order to reduce the complexity. It also enhances the application
efficiency. Next, we will learn how we can achieve abstraction using the Python program.
44
Abstraction classes
A class that consists of one or more abstract method is called the abstract class. Abstract methods do not
contain their implementation. Abstract class can be inherited by the subclass and abstract method gets its
definition in the subclass. Abstraction classes are meant to be the blueprint of the other class. An abstract
class can be useful when we are designing large functions. An abstract class is also helpful to provide the
standard interface for different implementations of components.

Abstract Base Classes


An abstract base class is the common application program of the interface for a set of subclasses. It can be
used by the third-party, which will provide the implementations such as with plugins. It is also beneficial
when we work with the large code-base hard to remember all the classes.

Unlike the other high-level language, Python doesn't provide the abstract class itself. We need to import
the abc module, which provides the base for defining Abstract Base classes (ABC). The ABC works by
decorating methods of the base class as abstract. It registers concrete classes as the implementation of the
abstract base. We use the @abstractmethod decorator to define an abstract method or if we don't provide
the definition to the method, it automatically becomes the abstract method

Below are the points which we should remember about the abstract base class in Python.

• An Abstract class can contain the both method normal and abstract method.
• An Abstract cannot be instantiated; we cannot create objects for the abstract class.

Abstraction is essential to hide the core functionality from the users. We have covered the all the basic
concepts of Abstraction in Python.

45
CHAPTER-3: NATIVE LANGUAGE TRANSLATION TOOL SUITE

ABSTRACT
The Trip Optimizer team of Wabtec Corporation is responsible for developing and implementing advanced
train control systems for the freight rail industry. The Trip Optimizer system is a state-of-the-art technology
that uses real-time data and sophisticated algorithms to optimize train operations, resulting in improved
safety, fuel efficiency, and reliability. The system automatically adjusts train speed based on various factors,
such as track topography, weather conditions, and train weight, to ensure that trains run at the optimal speed
while minimizing fuel consumption and emissions. The Trip Optimizer team works closely with customers
to tailor the system to their specific needs and optimize train operations for maximum efficiency and
profitability.

A native language translation tool is a type of software or application that is designed to assist in the
translation of content from one language to another, with a focus on ensuring that the resulting translation
meets the necessary conditions, such as string length, pixel, and special characters.

The tool can analyze the translated text and compare it to the original text, highlighting any discrepancies
or issues that may arise. For example, it will identify instances where the translated text is too long in
comparison to the original, or where special characters have been lost. By identifying these issues, the
native language translation tool can help to improve the accuracy and quality of translations, ensuring that
the final output is appropriate for the intended stakeholders and meets the necessary requirements. This is
very useful tool as it reduces human work drastically and produces reliable results. Also the application is
very handy.

The tool also has ability to recheck the translations after getting back from the translators so that it can be
analyzed quickly and if any changes is required, they can give it back to translators. The tool is also capable
of other functionality such as Extract SCN where the all the failed translations of different categories are
added to the sheets of the new excel sheet.

46
3.1 Definition
A native language translation tool is a type of software or application that is designed to assist in the
translation of content from one language to another, with a focus on ensuring that the resulting translation
meets the necessary conditions, such as string length, pixel, and special characters.

3.2 Purpose
The purpose of developing the Native language translation tool suite is to optimize time and reduce the
human errors.

3.3 Scope
This Tool can be used by validation, testing and software team.

3.4 Design and Implementation Constraints


The Software has following implementation constraints:

1. The tool is user friendly, dynamic and intuitive.

2. Accuracy: Tool can help ensure that translations are accurate.

3. Efficiency: By automating the process of identifying translations that do not meet necessary
conditions, a native language translation tool can help save time and increase efficiency.

4. Manual Errors are eliminated in the process.

5. The tool will minimize human involvement and drastically save man-hours.

6. The user can change the default values for checking reasonability parameters.

7. This tool is used for software developer, design engineer and testing teams.

47
CHAPTER-4

SYSTEM AND SOFTWARE SPECIFICATIONS

4.1 Operating Environment


1. 1.Windows: Windows 8 or higher.
4.2.2 Software

In this project I have used the IDLE(Python 3.6 64 Bit) Version DLE (Integrated Development and
Learning Environment) is an integrated development environment (IDE) for Python. The Python installer
for Windows contains the IDLE module by default. IDLE can be used to execute a single statement just
like Python Shell and also to create, modify, and execute Python scripts. IDLE is not available by default
in Python distributions for Linux. It needs to be installed using the respective package managers. IDLE can
be used to execute a single statement just like Python Shell and also to create, modify, and execute Python
scripts. IDLE provides a fully-featured text editor to create Python script that includes features like syntax
highlighting, autocompletion, and smart indent. It also has a debugger with stepping and breakpoints
features.

4.3 Hardware
1. RAM:-8GB
2. Processor:-Intel core i5 or higher
3. Disk Space:-100 GB or more

4.4 Software Requirements


1. Operating System: Windows 10
2. Python IDE
3. Visual Studio

48
CHAPTER-5 PACKAGES REQUIRED

This project is implemented using Python. In order to run the python scripts we need to install the
following Libraries in python

• Openpyxl
• TKINTER

5.1 Openpyxl
Openpyxl is a powerful Python library used for reading, writing, and manipulating Microsoft Excel files. It
allows you to work with Excel files in the .xlsx format, which is the default format for Excel files starting
from Excel 2007.Here are some key features and functionalities of Openpyxl: Reading and Writing:
Openpyxl provides methods to read data from Excel files, modify existing data, and create new Excel files
from scratch. It supports various data types, such as numbers, dates, formulas, and hyperlinks. Worksheet
Manipulation: With Openpyxl, you can create, delete, and rename worksheets in an Excel file. You can also
manipulate various aspects of a worksheet, such as cell formatting, merging and unmerging cells, adjusting
column widths, and hiding or unhiding rows and columns.Cell Operations: Openpyxl allows you to access
individual cells and perform operations on them. You can set cell values, retrieve cell contents, apply
formatting (e.g., font style, color, alignment), and work with cell ranges.
Formula Support: Openpyxl supports working with formulas in Excel files. You can set formula expressions
in cells, read existing formulas, and evaluate them to get the calculated result.Chart Generation: Openpyxl
enables you to create charts and add them to Excel files. You can generate various chart types, such as bar
charts, line charts, pie charts, and scatter plots, and customize their appearance and data sources.Data
Validation: Openpyxl provides support for data validation rules in Excel files. You can define validation
criteria for cells, such as numeric ranges, list values, or custom formulas, to ensure data integrity.Styling
and Formatting: Openpyxl offers a range of formatting options for cells, including font styles, colors,
borders, and fills. You can apply conditional formatting based on specific criteria and create visually
appealing Excel files.Pivot Tables: Openpyxl allows you to create and manipulate pivot tables, which
provide a way to summarize and analyze data in Excel files. You can define pivot table fields, set
aggregation functions, and customize the layout and appearance of pivot tables.

5.2 Tkinter
Tkinter is a standard Python library used for creating graphical user interfaces (GUIs). It provides a set of
tools and widgets that allow developers to build interactive applications with windows, buttons, text boxes,
menus, and other GUI elements.

49
CHAPTER-6 SYSTEM ARCHITECTURE

Fig 6.1: Architecture

The above figure 1 shows the methodology adopted for the project. Input files are either dat files or excel
files for functionalities such as generate requirement data sheet and perform reasonability check
respectively. In GUI there is provision to select the language and categories by user to check and based on
the categories selected, user will import files and can give reasonability parameters for each category. After
selecting all these tool uses these inputs in the backend and will generate the required failure strings and
add it to the excel sheet using python’s openpyxl library.

50
CHAPTER-7
SIMULATION RESULTS DISCUSSIONS
7.1 Output Files:

Fig 7.1: Output Files

Fig 7.2: Executable Application

51
Fig 7.3: Executable Application

8.1 Risks
• Light variations may cause the effects on marking the attendance.
• Shortage of pixels of camera results in poor recognition.
• Poor connection results in bad functionality of system

8.2 Security Requirements


User have to generate a highly protected password as per the instructions. It should not be shared with
other people. The security of the user data should be protected from the external attacks.

8.3 Maintainability
• Database regular update
• Calculation of Attendance percentage
• Training is required for new data

52
CHAPTER-9 CONCLUSION
In conclusion, a Native Language Translation Tool suite that is designed to identify translations that do not
meet necessary conditions like length, pixel and special characters can be a valuable quality control
mechanism for improving the accuracy and consistency of translations. By flagging translations that fall
outside the expected parameters, such a tool can help prevent errors and ensure that translations meet the
necessary standards for readability.

REFERENCES

• tkinter — Python interface to Tcl/Tk — Python 3.11.3 documentation


• Course titled ‘Python GUI Development with Tkinter’ in LinkedIn learning.
• openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files — openpyxl 3.1.2 documentation
• Course titled ‘Using Python with Excel’ in LinkedIn learning.

53

You might also like