Report of Python (1.) (1)
Report of Python (1.) (1)
Table Of Content
1. Introduction to Python
4. Basic Operations
5. Control Structures
6. Functions
7. Collections
9. File Handling
15. Conclusion
Page | 1
Python
1. Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991. Python is open-
source and has a large community, making it a versatile tool for many programming tasks
including web development, data analysis, artificial intelligence, and scientific computing.
Key Features:
❖ Easy to Read, Learn, and Write: Python has a simple syntax similar to English,
making it an excellent choice for beginners.
❖ Open Source: python is free and open source , meaning the source code is also free
and open.
❖ Dynamically Typed: No need to declare the type of variable; the type is determined
at runtime.
Python has a rich standard library and many third-party modules and frameworks.
❖ Interactive Mode:
Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
❖ Portable:
Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
Page | 2
Python
❖ Extendable:
You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
❖ Databases:
Python provides interfaces to all major commercial databases.
❖ GUI Programming:
Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
❖ Scalable:
Python provides a better structure and support for large programs than shell
scripting.
Scripting Language:
Scripting languages are often interpreted (rather than compiled). Primitives are
usually the elementary tasks or API calls, and the language allows them to be
combined into more complex programs. Environments that can be automated
through scripting include software applications, web pages within a web browser,
the shells of operating systems (OS), embedded systems, as well as numerous
games.
Comments:
Page | 3
Python
Comments are used to explain code. Single-line comments start with #, and multi-line
comments are enclosed in triple quotes (''' or """).
Variables are used to store data. Python's variables do not require explicit declaration
to reserve memory space.
Data Types:
Page | 4
Python
4. Basic Operations
Arithmetic Operators:
Comparison Operators:
Page | 5
Python
Logical Operators:
5. Control Structures
Conditional Statements:
Page | 6
Python
Loops:
For Loop:
While Loop:
Page | 7
Python
6. Functions
Functions are reusable blocks of code that perform a specific task.
Defining a Function:
def greet(name):
return(f”Hello,{name}!”)
Calling a Function:
message = greet("Bob")
print(message) # Outputs: Hello, Bob!
result = add(5, 3)
print(result) # Outputs: 8
Lambda Functions:
print(square(5)) # Outputs: 25
Page | 8
Python
7. Collections
Python provides several built-in collection data types for managing groups of data.
List:
The list is a most versatile datatype available in Python which can be written as a list
of comma- separated values (items) between square brackets. Important thing about a
list is that items in a list need not be of the same type.
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print (list[2])
Page | 9
Python
fruits.append("orange")
Page | 10
Python
Page | 11
Python
Tuples:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses.
To access values in tuple, use the square brackets for slicing along with the index or indices
to obtain value available at that index.
tup2 = (1, 2, 3, 4, 5, 6, 7 );
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string. In fact, tuples respond to
all of the general sequence operations we used on strings in the prior chapter
Page | 12
Python
Sets:
unique_numbers = {1, 2, 3, 2}
print(unique_numbers) # Outputs: {1, 2, 3}
ex:
# Creating a Set
set1 = set()
print(set1)
set1 = set("GeeksForGeeks")
print(set1)
Page | 13
Python
print(set1)
print(set(d))
Output:
set()
{'e', 'r', 'o', 'k', 'G', 's', 'F'}
{'For', 'Geeks'}
{'for', 'Geeks'}
{'for', 'Geeks'}
Dictionaries:
Page | 14
Python
Output:
Page | 15
Python
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
# Create an object
my_dog = Dog("Rex", 5)
Inheritance:
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
self.name = name
def speak(self):
class Dog(Animal):
def speak(self):
Page | 16
Python
class Cat(Animal):
def speak(self):
return f"{self.name} says meow!"
# Create objects
dog = Dog("Rex")
cat = Cat("Whiskers")
class Person:
def get_name(self):
return self.__name
def get_age(self):
return self.__age
Page | 17
Python
class Bird:
def speak(self):
return "Chirp!"
class Duck(Bird):
def speak(self):
return "Quack!"
# Create objects
bird = Bird()
duck = Duck()
# Polymorphism
9. File Handling
Python provides built-in functions for reading and writing files.
Reading Files:
Writing Files:
file.write("Hello, file!")
Appending to Files:
Page | 18
Python
Modules are files containing Python code that can define functions, classes, and
variables. They can also include runnable code. Using modules helps in organizing
your code into manageable sections and promotes code reuse.
Importing Modules
import math
You can import specific attributes from a module using the from keyword.
from math import pi, sqrt
Aliasing
import numpy as np
Creating a Module
# my_module.py
def greet(name):
import my_module
message = my_module.greet("Alice")
print(message) # Outputs: Hello, Alice!
Page | 19
Python
Introduction to Packages:
Creating a Package
mypackage/
__init__.py
module1.py
module2.py
Using a Package:
Exception handling is a mechanism to handle runtime errors, ensuring the flow of the
program can continue or gracefully terminate.
Try-Except Block
try:
result = 10 / 0
except ZeroDivisionError:
try:
result = 10 / 0
except ZeroDivisionError:
Page | 20
Python
except TypeError:
print("Invalid type!")
Finally Block
The finally block is executed regardless of whether an exception occurred or not.
try:
content = file.read()
except FileNotFoundError:
finally:
file.close()
print("File closed.")
Raising Exceptions
if b == 0:
return a / b
try:
print(divide(10, 0))
except ValueError as e:
Page | 21
Python
Generators:
Generators are functions that return an iterable set of items, one at a time, using the
yield keyword.
def count_up_to(max):
count = 1
count += 1
counter = count_up_to(5)
print(next(counter)) # Outputs: 1
print(next(counter)) # Outputs: 2
Decorators:
Decorators are functions that modify the behavior of other functions.
def my_decorator(func):
def wrapper():
func()
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Context Managers:
Context managers allow you to allocate and release resources precisely when you
want.
Page | 22
Python
content = file.read()
print(content)
Multithreading:
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
Multiprocessing:
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
Page | 23
Python
Page | 24
Python
Source Code
import time
• The time module is imported to introduce delays in the code execution using
time.sleep() function.
print("======================================================")
print("======================================================")
• Two lines with equal signs are printed to create a visual separator or header.
3. Defining and Printing the Welcome Logo
Page | 25
Python
welcome_logo = """
............
"""
print(welcome_logo)
• A multi-line string welcome_logo contains an ASCII art representation of a welcome
message.
print("======================================================")
print("======================================================")
• Two more lines with equal signs are printed to create another visual separator.
time.sleep(5)
password = 1010
balance = 10000
if pin == password:
• If the entered PIN matches the stored password (1010), the following block of code is
executed.
9. Displaying the ATM Menu
Page | 26
Python
while True:
print('''
1 : Check Balance
2 : Withdraw
3 : Deposit
4 : Exit
''')
• A while loop is used to repeatedly display the ATM menu until the user decides to
exit.
• The menu offers four options: Check Balance, Withdraw, Deposit, and Exit.
try:
if option == 1:
print("___________________________________________________________")
print("***********************************************************")
print("___________________________________________________________")
print("***********************************************************")
if option == 2:
print("___________________________________________________________")
print("***********************************************************")
Page | 27
Python
print("___________________________________________________________")
print("***********************************************************")
print("========================================================
===")
print("___________________________________________________________")
print("***********************************************************")
print("***********************************************************")
• If the user selects option 2, they are prompted to enter the withdraw amount.
• Messages are printed to confirm the transaction and display the updated balance.
if option == 3:
deposit_amount = int(input("\n\tPlease enter your Deposit Amount: "))
print("___________________________________________________________")
print("***********************************************************")
print("___________________________________________________________")
print("***********************************************************")
print("======================================================")
print("___________________________________________________________")
print("***********************************************************")
print("___________________________________________________________")
print("***********************************************************")
Page | 28
Python
• If the user selects option 3, they are prompted to enter the deposit amount.
• Messages are printed to confirm the transaction and display the updated balance.
break
• If the user selects option 4, the while loop breaks, and the program exits.
except:
• If the user enters an invalid option (non-integer or out of range), an error message is
printed.
else:
print("\n\tPIN inserted by you is not correct")
• If the entered PIN does not match the stored password, an error message is displayed.
Output:
Page | 29
Python
There are many ways to improve the performance of a Python program. Some of these are as
follows:
Data Structure: We have to select the right data structure for our purpose in a
Python program.
have to find and select the suitable algorithm to solve our problem with
Python is strong that even Google uses it. Some of the benefits of using Python are as
follows:
organizations for different projects. Due to this wide usage, there are thousands of
add-ons available for use with Python.
biggest benefit of using Python. Complex tasks can be very easily implemented in
Python.
Page | 30
Python
3. How will you specify source code encoding in a Python source file?
By default, every source code file in Python is in UTF-8 encoding. But we can also specify
our own encoding for source files. This can be done by adding following line after #! line in
the source file.
In the above line we can replace encoding with the encoding that we want to use.
PEP 8 is a style guide for Python code. This document provides the coding conventions for
writing code in Python. Coding conventions are about indentation, formatting, tabs,
maximum line length, imports organization, line spacing etc. We use PEP 8 to bring
consistency in our code. We consistency it is easier for other developers to read the code.
Python has a module named pickle. This module has the implementation of a powerful
algorithm for serialization and de-serialization of Python object structure.
There is a private heap space in Python that contains all the Python objects and data
structures. In C, Python there is a memory manager responsible for managing the heap
space.
There are different components in Python memory manager that handle segmentation,
sharing, caching, memory pre-allocation etc.
Python memory manager also takes care of garbage collection by using Reference counting
algorithm.
Page | 31
Python
We can use Static Analysis tool called PyChecker for this purpose. PyChecker can detect
errors in Python code.
Some other tools to find bugs in Python code are pylint and pyflakes.
III. Size: A Tuple takes much lesser space than a List in Python.
good performance.
A Python Decorator is a mechanism to wrap a Python function and modify its behavior by
adding more functionality to it. We can use @ symbol to call a Python Decorator function.
Page | 32
Python
Every argument in a Python method is an Object. All the variables in Python have reference
to an Object. Therefore arguments in Python method are passed by Reference.
Since some of the objects passed as reference are mutable, we can change those objects in a
method. But for an Immutable object like String, any change done within a method is not
reflected outside.
11. What is the difference between List and Dictionary data types in Python?
Main differences between List and Dictionary data types in Python are as follows:
12. What are the different built-in data types available in Python?
Sequence types: These data types are used to represent sequence of characters or objects.
Page | 33
Python
dict: This is also called hashmap. It has key value pair to store information by using hashing.
E.g. the set of built-in exception names, the set of built-in names, local names in a function
For the list of built-in names, Namespace is created when Python interpreter starts.
When Python interpreter reads the definition of a module, it creates global namespace for that
module.
When Python interpreter calls a function, it creates local namespace for that function.
I. use + operator:
Page | 34
Python
II. Minimal Class: It can be used for creating minimal classes: >>> class MyMinimalClass:
... pass
III. Place-holder for TODO work:
We can also use it as a placeholder for TODO work on a function or code that needs to be
implemented at a later point of time.
>>> def initialization(): ... pass # TODO
We can use Slicing in Python to get a substring from a String. The syntax of Slicing is very
convenient to use.
E.g. In following example we are getting a substring out of the name John. >>> name="John"
In Slicing we can give two indices in the String to create a Substring. If we do not give first
index, then it defaults to 0.
If we do not give second index, then it defaults to the size of the String. >>> name="John"
17. What is the difference between Docstring in Python and Javadoc in Java?
A Docstring in Python is a string used for adding comments or summarizing a piece of code
in Python.
The main difference between Javadoc and Docstring is that docstring is available during
runtime as well. Whereas, Javadoc is removed from the Bytecode and it is not present in
.class file.
We can even use Docstring comments at run time as an interactive help manual.
In Python, we have to specify docstring as the first statement of a code object, just after the
def or class statement.
The docstring for a code object can be accessed from the '__doc__' attribute of that object.
Page | 35
Python
We can use the unit testing modules unittest or unittest2 to create and run unit tests for
Python code.
We can even do automation of tests with these modules. Some of the main components of
unittest are as follows:
II. Test case: This is main unit test that we run on a piece of code. We
can use Testcase base class to create new test cases.
III. Test suite: We can aggregate our unit test cases in a Test suite.
IV. Test runner: We use test runner to execute unit tests and produce
19. What is the difference between and Iterator and Iterable in Python?
An Iterable is an object that can be iterated by an Iterator. In Python, Iterator object provides
_iter_() and next() methods.
In Python, an Iterable object has _iter_ function that returns an Iterator object.
When we work on a map or a for loop in Python, we can use next() method to get an Iterable
item from the Iterator.
We can use Generator to create Iterators in Python. A Generator is written like a regular
function. It can make use yield statement to return data during the function call. In this way
we can write complex logic that works as an Iterator.
A Generator is more compact than an Iterator due to the fact that _iter_() and next() functions
are automatically created in a Generator.
Also within a Generator code, local variables and execution state are saved between multiple
calls. Therefore, there is no need to add extra variables like self.index etc to keep track of
iteration.
Generator also increases the readability of the code written in Python. It is a very simple
implementation of an Iterator.
Page | 36
Python
21. What is the significance of functions that start and end with _ symbol in Python?
Python provides many built-in functions that are surrounded by _ symbol at the start and end
of the function name. As per Python documentation, double _ symbol is used for reserved
names of functions.
These are also known as System-defined names. Some of the important functions are:
Python provides another function xrange() that is similar to range() but xrange() returns a
sequence object instead of list object. In xrange() all the values are not stored simultaneously
in memory. It is a lazy loading based function.
But as per Python documentation, the benefit of xrange() over range() is very minimal in
regular scenarios.
The above mentioned lambda expression takes two arguments and returns their sum.
In Python we have two options to copy an object. It is similar to cloning an object in Java.
I. Shallow Copy: To create a shallow copy we call copy.copy(x). In
a shallow copy, Python creates a new compound object based on
Page | 37
Python
the original object. And it tries to put references from the original
deep copy, Python creates a new object and recursively creates and inserts copies of the
objects from original object into copy object. In a deep copy, we may face the issue of
recursive loop due to infinite recursion.
new programmer.
II. Large library: There is a large library for utilities in Python that
that are quite readable and very explicit in their use. It increases the readability of overall
code.
into the Interpreter. So a developer does not have to spend effort on managing memory
among objects.
types like list, set, dict etc. These data types give very good
performance as well as save time in coding new features.
A metaclass in Python is also known as class of a class. A class defines the behavior of an
instance. A metaclass defines the behavior of a class.
One of the most common metaclass in Python is type. We can subclass type to create our own
metaclass.
Page | 38
Python
A frozenset is a collection of unique values in Python. In addition to all the properties of set, a
frozenset is immutable and hashable.
Once we have set the values in a frozenset, we cannot change. So we cannot use and update
methods from set on frozenset.
It is a very simple application framework that has many extensions to build an enterprise
level application.
Flask does not provide a data abstraction layer or form validation by default. We can use
external libraries on top of Flask to perform such tasks.
During comparison we have to use “is” operator instead of “==” for None.
In Python, we have a built-in function zip() that can be used to aggregate all the Iterable
objects of an Iterator.
We can use it to aggregate Iterable objects from two iterators as well. E.g.
Output:
a1 b2 c3
By using zip() function we can divide our input data from different sources into fixed number
of sets.
Page | 39
Python
Python provides // operator to perform floor division of a number by another. The result of //
operator is a whole number (without decimal part) quotient that we get by dividing left
number with right number.
E.g.
10// 4 = 2
-10//4 = -3
With Modules, we can divide the functionality of our application in smaller chunks that can
be easily managed.
33. How can we create a dictionary with ordered set of keys in Python?
In a normal dictionary in Python, there is no order maintained between keys. To solve this
problem, we can use OrderDict class in Python. This class is available for use since version
2.7.
It is similar to a dictionary in Python, but it maintains the insertion order of keys in the
dictionary collection.
Python uses most of the Object Oriented programming concepts. But we can also do
functional programming in Python. As per the opinion of experts, Python is a multi-paradigm
programming language.
We can do functional, procedural, object-oriented and imperative programming with the help
of Python.
35. How can we retrieve data from a MySQL database in a Python script?
To retrieve data from a database we have to make use of the module available for that
database. For MySQL database, we import MySQLdb module in our Python script.
Page | 40
Python
We have to first connect to a specific database by passing URL, username, password and the
name of database.
Once we establish the connection, we can open a cursor with cursor() function. On an open
cursor, we can run fetch() function to execute queries and retrieve data from the database
tables.
36. What is the difference between append() and extend() functions of a list in Python?
In Python, we get a built-in sequence called list. We can call standard functions like append()
and extend() on a list.
We call append() method to add an item to the end of a list. We call extend() method to add
another list to the end of a list.
In append() we have to add items one by one. But in extend() multiple items from another list
can be added at the same time.
We can implement exception handling to handle error conditions in Python code. If we are
expecting an error condition that we cannot handle, we can raise an error with appropriate
message.
E.g.
If we do not want to stop the program, we can just catch the error condition, print a message
and continue with our program.
E.g. In following code snippet we are catching the error and continuing with the default value
of age.
#!/usr/bin/python try:
age=18+'duration' except:
age=18 print(age)
Page | 41
Python
Slicing is a way of getting substring from a String. It returns another String. E.g. >>> 'a b
c'[2:3] returns b.
39. How will you check in Python, if a class is subclass of another class?
True.
In Python, we can use the debugger pdb for debugging the code. To start debugging we have
to enter following lines on the top of a Python script.
After adding these lines, our code runs in debug mode. Now we can use commands like
breakpoint, step through, step into etc for debugging.
Python provides a profiler called cProfile that can be used for profiling Python code.
We can call it from our code as well as from the interpreter.
It gives use the number of function calls as well as the total time taken to run the script.
We can even write the profile results to a file instead of standard out.
We use ‘is’ to check an object against its identity. We use ‘==’ to check equality of two
objects.
E.g.
Page | 42
Python
This common module can be imported in all the modules in which we want to share the
variables.
In this way, all the shared variables will be in one module and available for sharing with any
new module as well.
Python provides built-in functions that can be used for Functional programming. Some of
these functions are:
I. Map()
II. reduce()
III. filter()
Event iterators and generators can be used for Functional programming in Python.
E.g.
>>> thelist=['a','b']
0a
1b
Unix environment.
In addition to that we have to add following line as the first line in a Python
script file.
Page | 43
Python
#!/usr/local/bin/python
This will tell Unix to use Python interpreter to execute the script.
47. What are the popular Python libraries used in Data analysis?
Some of the popular libraries of Python used for Data analysis are:
IV. SciPy: This is an open source system for science, mathematics and
[]
Even though the list has only 2 elements, the call to thelist with index 3
>>>name=’John Smith’
John Smith
This is an example of Slicing. Since we are slicing at the same index, the
first name[:5] gives the substring name upto 5th location excluding 5th
location. The name[5:] gives the rest of the substring of name from the 5th
Page | 44
Python
50. If you have data with name of customers and their location, which data type will you
use to store it in Python?
In Python, we can use dict data type to store key value pairs. In this
example, customer name can be the key and their location can be the value
key.
Python Programs
1. Area of Rectangle
Output:
2. Area of Circle
Output:
Page | 45
Python
3. Factorial of a number
Output:
4. Neon number
Page | 46
Python
Output:
6. Strong Number
Page | 47
Python
Output:
7. Sunny Number
Output:
8. Vowels of String
Page | 48
Python
Output:
n=5
alph = 65
alph = 65
print()
Output:
Page | 49
Python
AB
ABC
ABCD
ABCDE
def print_number_pyramid(rows):
for i in range(1, rows + 1):
# Print spaces
for j in range(rows - i):
print(" ", end="")
# Print numbers
for j in range(2 * i - 1):
print(j + 1, end="")
# Move to the next line after each row
print()
# Example usage
num_rows = 5
print_number_pyramid(num_rows)
Output:
1
123
12345
1234567
123456789
Page | 50
Python
Output;
*********
*******
*****
***
a = 4 # integer
b = 4.5 # float
c = 4j # complex number
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Page | 51
Python
15. Conclusion
In conclusion, Python is a versatile and powerful programming language that offers a
wide range of functionalities for developers of all levels. Its simplicity and readability
make it an ideal choice for beginners, while its extensive libraries and frameworks
make it suitable for complex applications and advanced users. Throughout this
training and internship, we have explored various aspects of Python, from basic
syntax and data types to more advanced topics such as object-oriented programming
and file handling.
Key Takeaways
• Simplicity and Readability: Python's clean and straightforward syntax makes it easy
to learn and write, reducing the likelihood of errors and improving maintainability.
• Dynamic Typing: The language's dynamic typing system allows for flexibility in
variable usage and reduces the need for explicit type declarations.
• Rich Standard Library: Python's extensive standard library and the availability of
numerous third-party libraries enable developers to accomplish a wide range of tasks
without reinventing the wheel.
• Community and Support: The large and active Python community provides
extensive resources, including documentation, tutorials, and forums, making it easier
to find solutions and improve skills.
Practical Experience
The hands-on experience gained during this training and internship has provided a
solid foundation in Python programming. By working on real-world projects and
solving practical problems, we have developed a deeper understanding of how to
apply Python in various contexts. This experience will undoubtedly be valuable in
future endeavors, whether in academic pursuits or professional careers.
Future Prospects
As Python continues to evolve and grow in popularity, mastering this language opens
up numerous opportunities in the tech industry. Its applications in emerging fields
such as machine learning, data science, and automation ensure that Python skills will
remain in high demand. Continuous learning and staying updated with the latest
advancements in Python and its ecosystem will be crucial for leveraging its full
potential.
Page | 52