Python essential 1 report
Python essential 1 report
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING
Submitted by
Dr. Yaswanth
Gavini
Associate
Professor
DECLARATION
I hereby declare that the summer internship report entitled “PYTHON ESSENTISLS” is an
original work done in the Department of Computer Science and Engineering, GITAM School of
Technology, GITAM (Deemed to be University) submitted in partial fulfilment of the
requirements for the award of the degree of “Bachelor of Technology” in Computer Science and
Engineering. The work had not been submitted to any other college or university for the award
of any degree or diploma.
Place-HYDERABD
Date-06-03-2025
Ganesh Sai Santosh
Chivukula
(HU22CSEN0101777)
2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GITAM SCHOOL OF TECHNOLOGY
GITAM
(DEEMED TO BE UNIVERSITY)
HYDERABAD CAMPUS
CERTIFICATE
This is to certify that the Internship report entitled “PYTHON ESSENTIALS” is a Bonafide record of
work carried out by Ganesh Sai Santosh Chivukula (HU22SCEN0101777) submitted in partial
fulfillment of the requirement for the award of the degree of Bachelors of Technology in Computer
Science and Engineering.
3
CERTIFICATE OF COMPLETION
4
ABSTRACT
This report presents a comprehensive reflection on my three-month
internship , where I focused on mastering Python essentials for web application
development. During the internship, I worked extensively with key Python
frameworks, such as Flask and Django, learning how to integrate them with
databases like SQLite and MySQL to develop dynamic, data-driven
applications. Additionally, I gained hands-on experience in web scraping using
libraries like BeautifulSoup and Scrapy, enabling efficient extraction of
valuable data from websites.My responsibilities included developing, testing,
and optimizing Python code, integrating APIs, and collaborating with senior
developers on real-world projects. The internship presented challenges that
enhanced my ability to solve programming problems, debug errors, and write
clean, efficient code. Furthermore, it reinforced the significance of unit testing,
version control (Git), and teamwork in a professional development
environment.This internship was a transformative learning experience,
allowing me to apply theoretical concepts to real-world projects while adapting
to a professional work culture. I acquired invaluable insights into software
development best practices, time management, and collaboration. Ultimately,
this experience has strengthened my Python web development skills, preparing
me for future roles in the field while enhancing my problem-solving and
communication abilities.
5
Table of Contents
1. Introduction to Python and Computer Programming
o What is Programming?
o String Manipulation
6
o Introduction to Loops: for and while loops
7
CHAPTER 1
What is Programming?: An overview of the role of programming in solving real-world problems and creating
applications.
Overview of Python: Why Python is popular—simple syntax, powerful libraries, and its role in web development,
data analysis, and automation.
Setting up Python Environment: Installation of Python on different operating systems, IDEs (like
PyCharm, VSCode), and setting up virtual environments.
Your First Python Program: Writing a basic "Hello, World!" program to understand how Python works.
Role of the Interpreter: The Python interpreter's function in translating code into executable instructions and how
it helps debug code.
Data Types: Explore Python's built-in types like integers, floating-point numbers, strings, and booleans.
Variables: Learn how Python manages data with variables and how to assign values to them.
Basic I/O: Learn how to accept input from the user and display output using input() and print().
Operators: Understand Python's arithmetic operators, comparison operators, and logical operators for
manipulating data.
Module 3: Boolean Values, Conditional Execution, Loops, Lists and List Processing
This module delves into control flow and data structures like lists. Key topics include:
Boolean Values: Understand the concept of truth values (True and False) and their importance in
decision- making.
Conditional Execution: Learn how to use if-else statements for decision-making and apply logic to control the flow
of a program.
Loops: Master loops, including for and while loops, for repeating tasks.
Lists: Lists are Python's ordered, mutable collections. Learn how to create, modify, and access list elements.
List Processing: Discover list comprehensions, a Pythonic way to process lists. Explore methods like
filtering, mapping, and sorting.
Functions: Functions allow you to bundle code into reusable blocks. Learn how to define and call functions,
pass arguments, and return results.
Tuples: Tuples are immutable sequences in Python. Explore how they differ from lists and their use cases.
Dictionaries: Learn how to work with key-value pairs in dictionaries and perform operations like adding, updating,
and deleting elements.
Exceptions: Learn about Python's exception-handling mechanism with try, except, and finally to manage
errors.
Data Processing: Learn basic techniques for reading and writing data files, such as CSV and JSON.
Understand libraries and techniques used for data extraction and processing.
The interpreter translates high-level Python code into machine-readable instructions and executes the program.
This happens line by line, which allows for rapid development and testing.
Error Reporting: When a program has an issue, the interpreter attempts to pinpoint the problem's location.
However, the error messages it provides might not always point directly to the root cause. Errors are detected when
the interpreter reaches a point where it cannot understand or execute the code as intended.
Misleading Error Messages: Sometimes the interpreter identifies the location of an error, but this might be
misleading because Python does not always trace the issue to the correct line or statement. This is especially
true when the error occurs within a complex expression, or when the cause of the issue is earlier in the code.
Syntax Errors: These occur when the syntax does not follow the rules of Python. The interpreter will stop
execution and report the error location.
Runtime Errors: These happen when the program is executed but encounters an issue (e.g., division by zero, file not
found). The interpreter will attempt to handle this via error messages and traceback
Definition: Programming is a way to communicate with computers and tell them what tasks to perform.
It involves using a set of instructions to control the behavior of a machine.
Importance of Programming:
o Problem Solving: Programming allows us to solve complex problems by breaking them down into
smaller, manageable parts. It’s a structured way to automate processes, perform calculations, and manage
data.
o Automation: Many routine tasks (e.g., data entry, file management) can be automated using code, making
systems more efficient and error-free.
o Technological Development: Almost every modern application, from smartphones to web services, relies on
programming for development. Programming skills empower individuals to create solutions and contribute
to technological innovations.
Programming Languages: There are many programming languages (like Python, Java, C++, etc.), and
each has its syntax and strengths. Python, for example, is favored for its simplicity and readability,
making it ideal for beginners and professionals alike.
Application of Programming: Programming is used in various fields:
o Web Development: Building websites and web applications.
o Data Science: Analyzing and processing data for insights.
o Automation: Writing scripts for repetitive tasks.
o Game Development: Creating games and interactive entertainment.
o Artificial Intelligence: Developing algorithms that allow machines to learn and make decisions.
Installing Python:
o Visit the official Python website at python.org and download the latest version for your operating system.
o Follow the installation instructions for Windows, macOS, or Linux. On Windows, ensure that the option
to "Add Python to PATH" is checked during installation.
Setting up an Integrated Development Environment (IDE):
o An IDE helps you write, debug, and run Python code efficiently. Some popular Python IDEs include:
PyCharm: A powerful, feature-rich IDE for Python.
VSCode: A lightweight and customizable code editor with Python support through extensions.
Jupyter Notebooks: A popular choice for data science and interactive coding.
o Text Editors: For those who prefer lighter editors, you can use Sublime Text or Atom, which support
Python with the help of plugins.
Creating a Python Virtual Environment:
o A virtual environment isolates your project’s dependencies from other Python projects. This ensures
that different projects with different package requirements don’t interfere with each other.
o Create a virtual environment with:
bash
Copy
python -m venv myenv
python
Copy
print("Hello, World!")
What is an Interpreter?:
o An interpreter is a program that executes Python code by translating it line-by-line into machine code
that the computer can understand. Unlike compilers, which translate the entire program at once,
interpreters translate and execute the code at runtime.
o Python is an interpreted language, meaning the code is executed directly by the Python interpreter
rather than being compiled into machine code first.
The Python Interpreter:
o The Python interpreter is invoked when you run a Python program. It reads your code, processes it, and
gives feedback in the form of results or error messages.
Error Handling in the Interpreter:
o The interpreter helps identify errors and exceptions in the code. However, sometimes error messages may
not directly point to the exact location of the error. This is because the interpreter processes code line-by-line
and might find an issue later, but the actual mistake could be several lines above.
Common Python Errors:
o Syntax Errors: Occur when Python doesn’t understand the structure of the code (e.g., missing parentheses).
o Runtime Errors: Happen when the code is executed but encounters an issue (e.g., dividing by zero).
o Logic Errors: These are harder to spot and occur when the program runs but doesn’t perform the
desired task.
Chapter-2
Module 2: Data Types, Variables, Basic Input/Output, and Operators
2.1 Data Types in Python
Understanding data types is one of the most fundamental aspects of programming. In Python, every value has a
specific type, and knowing how to work with these types is essential for performing operations on data.
Definition of Data Types: Data types define the kind of data a variable can hold and the operations that
can be performed on that data. Python supports several built-in data types, which are classified into
primitive types and composite types.
Primitive Data Types:
o Integers (int): Whole numbers, positive or negative, without decimals.
Example: x = 10
o Floating-Point Numbers (float): Numbers that contain a decimal point.
Example: y = 3.14
o Strings (str): A sequence of characters enclosed in either single or double quotes.
Example: name = "Python"
o Booleans (bool): Represents two values: True or False.
Example: is_valid = True
Composite Data Types:
o Lists: Ordered, mutable collections of items that can store multiple data types.
Example: my_list = [1, 2, 3, "apple", True]
o Tuples: Ordered, immutable collections of items.
Example: coordinates = (10.0, 20.5)
o Dictionaries: Unordered collections of key-value pairs, where each key is unique.
Example: person = {"name": "John", "age": 30, "is_student": False}
Type Checking and Conversion:
o You can check the data type of a variable using the built-in type() function:
python
Copy
x = 10
print(type(x)) # Output: <class 'int'>
o Type casting (also known as type conversion) is the process of converting one data type to another, using
functions like int(), float(), str(), etc.
python
Copy
x = "10"
y = int(x) # Converts string to integer
2.2 Variables and Memory Allocation
In Python, variables are symbolic names associated with values. They act as containers for storing data that can be
referenced and manipulated throughout a program.
Variable Assignment:
o In Python, you assign a value to a variable using the assignment operator (=).
python
Copy
x = 5 # Assigns the value 5 to the variable x
name = "Alice" # Assigns the string "Alice" to the variable name
Naming Variables:
o Variable names in Python must begin with a letter (a-z, A-Z) or an underscore (_), followed by letters, digits,
or underscores.
o Example of valid names: my_variable, x1, _counter
o Python Naming Rules:
Variables are case-sensitive (Age and age are different variables).
Avoid using Python keywords (e.g., if, else, True, None) as variable names.
Memory Allocation:
o Python automatically handles memory allocation and deallocation using a mechanism called automatic
garbage collection. This makes Python less memory-intensive compared to languages that require manual
memory management (like C).
Reassigning Variables:
o Python allows you to reassign values to variables during runtime. If you assign a new value to an
existing variable, the old value is overwritten.
python
Copy
x = 10 # x initially holds the value 10
x = 20 # Now x holds the value 20, and the value 10 is discarded
python
Copy
print("Hello, World!") # Prints a string to the console
name = "Alice"
print("Hello, " + name) # Concatenates and prints "Hello, Alice"
python
Copy
age = input("Enter your age: ") # The value is stored as a string
age = int(age) # Converts the string to an integer
Formatted Output:
o You can also format output strings using f-strings or the format() method:
python
Copy
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.") # Using f-string
Or using format():
python
Copy
print("My name is {} and I am {} years old.".format(name, age))
Arithmetic Operators:
o Used for performing mathematical operations on numbers (integers or floats).
python
Copy
x = 10
y = 5
print(x + y) # Addition: 15
print(x - y) # Subtraction: 5
print(x * y) # Multiplication: 50
print(x / y) # Division: 2.0 (always returns a float)
print(x // y) # Floor Division: 2 (integer result)
print(x % y) # Modulus (remainder): 0
print(x ** y) # Exponentiation: 100000
Comparison Operators:
o Used for comparing two values and returning a boolean result (True or False).
python
Copy
x = 10
y = 5
print(x > y) # Greater than: True
print(x == y) # Equal to: False
print(x != y) # Not equal to: True
print(x <= y) # Less than or equal to: False
print(x >= y) # Greater than or equal to: True
Logical Operators:
o Used for combining conditional statements. Logical operators include and, or, and not.
python
Copy
x = 10
y = 5
print(x > 5 and y < 10) # True
print(x > 5 or y > 10) # True
print(not(x > 5)) # False
Assignment Operators:
o Used to assign values to variables. Python supports shorthand assignment operators.
python
Copy
x = 10
x += 5 # x = x + 5
print(x) # Output: 15
x *= 2 # x = x * 2
print(x) # Output: 30
python
Copy
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False: Different memory locations
print(a == b) # True: Equal values
o Membership Operators: in and not in check if a value exists in a sequence (list, tuple, etc.).
python
Copy
a = [1, 2, 3]
print(2 in a) # True
print(4 not in a) # True
Data Types: Python has several built-in data types like integers, floats, strings, and booleans, as well as
composite types like lists, tuples, and dictionaries.
Variables: Variables are used to store data, and Python handles memory management automatically.
Basic Input and Output: The input() function is used to take user input, and the print() function
displays output. We also learned how to format strings and display dynamic content.
Operators: Python supports a wide range of operators—arithmetic, comparison, logical, assignment,
and membership/identity operators.
Chapter-3
python
Copy
x=5
y = 10
Common Uses:
python
Copy
x=0
if x:
print("This is True.")
else:
If Statements:
python
Copy
age =
18
o If the initial if condition is False, Python checks the condition of the elif
statement.
python
Copy
age =
15
o The else block is executed when all preceding if and elif conditions are
False.
python
Copy
age =
10
else:
python
Copy
age =
25
print("You are an adult, but not yet 21.") # Output: You are an adult, but not
yet 21.
else:
Loops allow repetitive execution of a block of code. Python provides two main
types of loops: for loops and while loops.
For Loop:
o The for loop is used to iterate over a sequence (like a list, tuple, string, or
range) and execute a block of code for each element.
python
Copy
print(i) # Output: 0 1 2 3 4
python
Copy
print(i)
While Loop:
python
Copy
count = 0
print(count) # Output: 0 1 2 3 4
count += 1
o Be careful to avoid infinite loops, which occur when the loop condition
never becomes False.
o Continue: Skips the current iteration and moves to the next one.
python
Copy
for i in range(5):
if i == 3:
print(i) # Output: 0 1 2
for i in range(5):
if i == 3:
print(i) # Output: 0 1 2 4
Lists are one of the most common and flexible data structures in Python. They are
ordered, mutable, and can store multiple data types.
Defining Lists:
python
Copy
my_list = [1, 2, 3, 4, 5]
Accessing List Elements:
o You can access elements of a list using indexing (starting from index 0)
or slicing.
python
Copy
Modifying Lists:
python
Copy
python
Copy
List Length:
o You can find the number of items in a list using the len() function.
python
Copy
length = len(my_list)
print(length) # Output: 5
Python allows powerful ways to process and manipulate lists, and one of the most
Pythonic methods is list comprehensions.
List Comprehensions:
python
Copy
python
Copy
Copy
List Methods:
o Sorting: The sort() method sorts the list in place, while sorted() returns a
new sorted list.
Module 3 delved into several core concepts in Python that control the flow of
execution and enable us to handle lists and their processing efficiently. Here are
the key takeaways:
Conditional Execution: Use if, elif, and else statements to make decisions.
Loops: Both for and while loops are used to repeat code. Break and continue
statements provide control over loop execution.
Lists: Powerful data structures that store ordered, mutable collections. Learn
how to access, modify, and process lists.
With these tools at hand, you can build more interactive, dynamic, and efficient
programs. The next module will focus on functions and advanced data structures
such as dictionaries and exceptions.
Chapter-4
Module 4: Functions, Tuples, Dictionaries, Exceptions, and Data Processing
4.1 Functions in Python
Functions are a fundamental concept in programming, allowing you to organize your code into reusable blocks that
can be executed when called. In Python, functions are defined using the def keyword.
Defining a Function:
o Functions allow you to group related statements together. A function can take parameters (inputs) and return
a result (output).
python
Copy
def greet(name):
return f"Hello, {name}!"
python
Copy
def add(a, b):
return a + b
Default Parameters:
o You can define default values for parameters, which will be used if no argument is passed for that parameter.
python
Copy
def greet(name="Guest"):
return f"Hello, {name}!"
Returning Values:
o Functions can return values, which can then be used by other parts of the program.
python
Copy
def multiply(a, b):
return a * b
Variable Scope:
o Local variables are defined within a function and can only be accessed inside that function.
o Global variables are defined outside of any function and can be accessed throughout the program.
python
Copy
x = 10 # Global variable
def func():
x = 5 # Local variable
print(x) # Output: 5
func()
print(x) # Output: 10 (global x remains unchanged)
Lambda Functions:
o A lambda function is a small anonymous function defined with the lambda keyword. It’s used for
short, throwaway functions.
python
Copy
square = lambda x: x ** 2
print(square(4)) # Output: 16
Defining Tuples:
o Tuples are defined using parentheses () and can contain any type of data.
python
Copy
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
python
Copy
print(my_tuple[0]) # Output: 1
Tuple Immutability:
o Once a tuple is created, its elements cannot be changed, which makes them more efficient in memory
and performance when compared to lists.
python
Copy
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error: 'tuple' object does not support item assignment
Nested Tuples:
o Tuples can contain other tuples or collections.
python
Copy
nested_tuple = (1, (2, 3), 4)
print(nested_tuple[1]) # Output: (2, 3)
python
Copy
my_tuple = (1, 2, 3)
a, b, c = my_tuple # Unpacking
print(a, b, c) # Output: 1 2 3
Defining a Dictionary:
o Dictionaries are created using curly braces {} with key-value pairs separated by a colon :. The key must
be unique.
python
Copy
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
python
Copy
print(my_dict["name"]) # Output: Alice
Modifying Dictionary:
o You can add or update key-value pairs in a dictionary.
python
Copy
my_dict["age"] = 26 # Update value for 'age'
my_dict["email"] = "alice@example.com" # Add new key-value pair
Removing Elements:
o Use del to remove a key-value pair.
python
Copy
del my_dict["city"]
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
Dictionary Methods:
o keys(): Returns a view of all the keys in the dictionary.
o values(): Returns a view of all the values.
o items(): Returns a view of all the key-value pairs.
python
Copy
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'email'])
print(my_dict.values()) # Output: dict_values(['Alice', 26, 'alice@example.com'])
Handling Exceptions:
o The try block contains the code that might raise an exception, and the except block handles the error if
it occurs.
python
Copy
try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!") # Output: Cannot divide by zero!
python
Copy
try:
x = int("hello") # This will raise a ValueError
except ValueError:
print("Value error occurred!")
except ZeroDivisionError:
print("Zero division error occurred!")
python
Copy
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division was successful!")
finally:
print("This block is always executed.")
List Processing:
o As seen earlier, lists are commonly used to store and process data. You can use list comprehensions and
map/filter functions to efficiently process data.
python
Copy
# List comprehension
squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]
python
Copy
# Writing to a file
with open("data.txt", "w") as file:
file.write("Hello, World!")
Functions: Used to organize code into reusable blocks with parameters and return values.
Tuples: Immutable data structures that store ordered collections of items.
Dictionaries: Unordered collections of key-value pairs used to represent mappings.
Exceptions: Used to handle errors and ensure smooth program execution even when things go wrong.
Data Processing: Includes techniques for manipulating lists, working with files, and using libraries to process
and analyze data.
With these tools, you can begin building more robust and complex applications, particularly those that involve data
manipulation, error handling, and modular code design.