Report of python
Report of python
Table Of Content
1. Introduction to Python
4. Basic Operations
5. Control Structures
6. Functions
7. Collections
9. File Handling
11.Exception Handling
12.Advanced Topics
14.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.
Interpreted Language: Python is executed line by line at runtime, which makes
debugging easier.
Dynamically Typed: No need to declare the type of variable; the type is determined
at runtime.
Extensive Libraries and Frameworks: Python has a rich standard library and
many third-party modules and frameworks.
Comments:
Comments are used to explain code. Single-line comments start with #, and multi-line
comments are enclosed in triple quotes (''' or """).
Page | 2
Python
Variables are used to store data. Python's variables do not require explicit declaration
to reserve memory space.
Data Types:
4. Basic Operations
Arithmetic Operators:
Page | 3
Python
Comparison Operators:
Compare values and return a boolean.
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
Logical Operators:
Combine conditional statements.
a = True
b = False
5. Control Structures
Conditional Statements:
Execute code based on conditions.
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
Page | 4
Python
else:
print("Negative")
Loops:
For Loop:
Iterates over a sequence.
for i in range(5):
print(i) # 0 1 2 3 4
While Loop:
Repeats as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1 # 0 1 2 3 4
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!
Parameters and Arguments:
Functions can accept parameters and return values.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Outputs: 8
Page | 5
Python
Lambda Functions:
Anonymous functions defined with the lambda keyword.
square = lambda x: x ** 2
print(square(5)) # Outputs: 25
7. Collections
Python provides several built-in collection data types for managing groups of data.
List:
Ordered, mutable, and allows duplicate elements.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'orange']
Tuples:
Ordered, immutable, and allows duplicate elements.
point = (10, 20)
print(point) # Outputs: (10, 20)
Sets:
Unordered, mutable, and does not allow duplicate elements.
unique_numbers = {1, 2, 3, 2}
print(unique_numbers) # Outputs: {1, 2, 3}
Dictionaries:
Unordered, mutable, and stores data in key-value pairs.
student = {"name": "Alice", "age": 21}
print(student["name"]) # Outputs: Alice
Page | 6
Python
def bark(self):
return f"{self.name} says woof!"
# Create an object
my_dog = Dog("Rex", 5)
print(my_dog.bark()) # Outputs: Rex says woof!
Inheritance:
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
class Cat(Animal):
def speak(self):
Page | 7
Python
# Create objects
dog = Dog("Rex")
cat = Cat("Whiskers")
print(dog.speak()) # Outputs: Rex says woof!
print(cat.speak()) # Outputs: Whiskers says meow!
Encapsulation:
Encapsulation restricts access to certain components of an object.
class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
self.__age = age # Private attribute
def get_name(self):
return self.__name
def get_age(self):
return self.__age
Page | 8
Python
class Duck(Bird):
def speak(self):
return "Quack!"
# Create objects
bird = Bird()
duck = Duck()
# Polymorphism
for animal in [bird, duck]:
print(animal.speak()) # Outputs: Chirp! Quack!
9. File Handling
Python provides built-in functions for reading and writing files.
Reading Files:
with open('example.txt', 'r') as file:
content = file.read()
print(content) # Outputs the content of example.txt
Writing Files:
with open('example.txt', 'w') as file:
file.write("Hello, file!")
Appending to Files:
with open('example.txt', 'a') as file:
file.write("\nAppending new line.")
Page | 9
Python
Importing Modules
You can import a module using the import statement.
import math
print(math.sqrt(16)) # Outputs: 4.0
Importing Specific Attributes
You can import specific attributes from a module using the from keyword.
from math import pi, sqrt
print(pi) # Outputs: 3.141592653589793
print(sqrt(25)) # Outputs: 5.0
Aliasing
Modules can be aliased using the as keyword.
import numpy as np
array = np.array([1, 2, 3])
print(array) # Outputs: [1 2 3]
Creating a Module
A module is simply a Python file with a .py extension.
# my_module.py
def greet(name):
return f"Hello, {name}!"
You can use the module in another file by importing it.
# main.py
import my_module
message = my_module.greet("Alice")
print(message) # Outputs: Hello, Alice!
Introduction to Packages:
A package is a way of organizing related modules into a directory hierarchy. A
package must contain an __init__.py file.
Creating a Package
1. Create a directory for the package.
Page | 10
Python
Page | 11
Python
try:
print(divide(10, 0))
except ValueError as e:
print(e) # Outputs: Cannot divide by zero!
Page | 12
Python
def count_up_to(max):
count = 1
while count <= max:
yield count
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():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
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.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# The file is automatically closed after the block
Page | 13
Python
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 | 14
Python
Page | 15
Python
Source Code
1. Importing the Time Module
import time
The time module is imported to introduce delays in the code execution using
time.sleep() function.
2. Printing Header Lines
print("======================================================")
print("======================================================")
Two lines with equal signs are printed to create a visual separator or header.
3. Defining and Printing the Welcome Logo
Page | 16
Python
welcome_logo = """
............
"""
print(welcome_logo)
A multi-line string welcome_logo contains an ASCII art representation of a welcome
message.
The welcome logo is printed to the console.
4. Printing Footer Lines
print("======================================================")
print("======================================================")
Two more lines with equal signs are printed to create another visual separator.
5. Prompting User to Insert Card
print("\n====------------------------- Please inert your Card ---------------------------
====")
time.sleep(5)
A message prompts the user to insert their card.
A delay of 5 seconds is introduced to simulate the time taken for card insertion.
6. Setting the ATM PIN and Initial Balance
password = 1010
balance = 10000
The ATM PIN is set to 1010.
The initial balance is set to 10,000.
7. Asking User for PIN Input
pin = int(input("\n\tEnter your ATM PIN: "))
The user is prompted to enter their ATM PIN, which is converted to an integer.
8. Verifying the PIN
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 | 17
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.
10. Handling User Selection with Exception Handling
try:
option = int(input("\tPlease select any one option: "))
The user is prompted to select an option from the menu.
The input is converted to an integer and wrapped in a try block to handle invalid
input.
11. Checking Balance Option
if option == 1:
print("___________________________________________________________")
print("***********************************************************")
print(f"\n\tYour current balance is {balance}")
print("___________________________________________________________")
print("***********************************************************")
If the user selects option 1, their current balance is displayed.
12. Withdraw Option
if option == 2:
withdraw_amount = int(input("\n\tPlease enter your Withdraw Amount: "))
balance = balance - withdraw_amount
print("___________________________________________________________")
print("***********************************************************")
Page | 18
Python
print("========================================================
===")
print("___________________________________________________________")
print("***********************************************************")
print(f"\tYour update current balance is {balance}")
print("___________________________________________________________")
print("***********************************************************")
If the user selects option 2, they are prompted to enter the withdraw amount.
The balance is updated by subtracting the withdraw amount.
Messages are printed to confirm the transaction and display the updated balance.
13. Deposit Option
if option == 3:
deposit_amount = int(input("\n\tPlease enter your Deposit Amount: "))
balance = balance + deposit_amount
print("___________________________________________________________")
print("***********************************************************")
print(f"\t{deposit_amount} is credited to your account")
print("___________________________________________________________")
print("***********************************************************")
print("======================================================")
print("___________________________________________________________")
print("***********************************************************")
print(f"\tYour updated current balance is {balance}")
print("___________________________________________________________")
print("***********************************************************")
Page | 19
Python
If the user selects option 3, they are prompted to enter the deposit amount.
The balance is updated by adding the deposit amount.
Messages are printed to confirm the transaction and display the updated balance.
14. Exit Option
if option == 4:
break
If the user selects option 4, the while loop breaks, and the program exits.
15. Handling Invalid Input
except:
print("\tPlease enter a valid option between 1 to 4")
If the user enters an invalid option (non-integer or out of range), an error message is
printed.
16. Incorrect PIN Handling
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:
Output
Page | 20
Python
14. 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.
Versatile Application: Python's ability to support multiple programming paradigms,
including procedural, object-oriented, and functional programming, makes it suitable
for various types of projects, from web development and data analysis to artificial
intelligence and scientific computing.
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
Page | 21
Python
advancements in Python and its ecosystem will be crucial for leveraging its full
potential.
In summary, Python is not just a programming language but a gateway to endless
possibilities in technology and innovation. The knowledge and skills acquired during
this training and internship form a strong foundation for future success and growth in
the world of programming and beyond.
Page | 22
Python
Page | 23
Python
Page | 24
Python
Page | 25
Python
Page | 26
Python
Table Of Contents
1. Introduction to Python
2. Python Syntax and Semantics
Page | 27
Python
Page | 28