BASIC PROGRAMING IN PYTHON
INTERNAL ASSESSMENT 1
TOPIC 1: INTRODUCTION TO PYTHON
1.1 Comparison of Python with other Programming languages-
In practice, the choice of a programming language is often dictated by real-world constraints such as cost,
availability, training, and prior investment, or even emotional attachment. Since these aspects are highly variable, we
can make a general comparison of Python Programming with the other programming languages are as follows:-
A) JAVA V/S PYTHON
Language Type: Python is an interpreted language with dynamic typing whereas Java is a compiled language with
static typing.
Performance and Speed: Python is interpreted line-by-line at runtime, which adds overhead, whereas Java is
significantly faster as its compiles into bytecode before execution. This makes Java suited for high performance than
Python.
Readability and Development Speed: Python ‘s syntax is much simpler, concise, requiring fewer lines of code to
accomplish task, allowing for faster development, easier to learn and prototyping. Java, on the other hand, uses
verbose syntax with semicolons and curly brackets, making it complex to write and debug.
B) JAVASCRIPT V/S PYTHON
Primary Domain: Python is traditionally a back end language, used for server-side logic, data processing and APIs.
JavaScript is used for Front-end web development to create interactive user interfaces. It also has strong back-end
development presence through [Link].
Concurrency: Python's Global Interpreter Lock (GIL) restricts it to running one thread at a time, which can limit
performance on CPU-bound tasks. JavaScript, particularly with [Link], uses an event-driven, non-blocking I/O
model that is highly effective for handling a large number of concurrent connections, making it excellent for real-
time applications.
Ecosystem and Libraries: Python has a massive advantage in scientific computing, machine learning, and data
analysis due to its specialized libraries. JavaScript's ecosystem is heavily focused on front-end and full-stack web
frameworks.
C) C++ V/S PYTHON
Language type: Python is an interpreted language with dynamic typing whereas C++ Is a lower level statically typed
language that allows users to have control.
Performance and Memory management: Python's automatic garbage collection and interpreted nature make it
much slower. C++ is one of the fastest languages available. It offers manual memory management, allowing
developers to optimize for speed and memory usage, making it ideal for performance-critical applications.
Complexity and Learning Curve: Python's high-level syntax, which closely resembles plain English, makes it much
easier for beginners to learn. C++ has a steep learning curve due to its complex syntax, pointers, and manual
memory management.
D) PYTHON V/S R
Purpose: Python is a general-purpose language that has been adapted for data science and machine learning. R was
designed by statisticians for statistical analysis and data visualization. Its strengths lie in its powerful statistical
packages and its ability to create complex, publication-quality plots.
Learning Curve: Python's syntax is generally considered more intuitive and easier to learn for those with a
programming background. R's syntax can feel less conventional for traditional programmers but is a natural fit for
those with a statistics or academic background.
Versatility: Python's versatility allows it to be used for the entire data pipeline—from data collection and cleaning to
model building and deployment in a web application. R is more specialized, making it a powerful tool for deep
statistical analysis but less suitable for building large-scale, general-purpose applications.
Thus, Python is currently a widely used programming language in various domains with its easy to use syntax,
concise and wider applications.
1.2 The execution model of Python
The Python execution model involves a multi-step process that translates human-readable Python code into
instructions the computer can understand and execute.
Compilation to Bytecode:
When a Python script is run, the Python interpreter first compiles the source code into an intermediate format
called bytecode. This bytecode is platform-independent and is stored in .pyc files for faster loading in subsequent
runs.
Execution by the Python Virtual Machine (PVM):
The compiled bytecode is then executed by the Python Virtual Machine (PVM). The PVM is a runtime engine that
interprets the bytecode instructions and translates them into machine-specific instructions that the underlying
operating system and hardware can understand.
Flow of Execution:
Python executes code line by line, from top to bottom.
1. Top-level statements: When a module is imported or executed, all top-level statements (outside of function or
class definitions) are executed sequentially. This includes variable assignments, function calls, and any other
executable code.
2. Function and Class Definitions: def statements for functions and class statements for classes are executed to
define these entities within the module's scope. However, the code inside a function or method is only executed
when that function or method is explicitly called.
3. Control Flow: Statements like if, for, and while control the flow of execution, determining which blocks of code
are executed based on conditions or iterations.
Execution Modes:
Python code can be executed in two primary modes:
1. Script Mode: The Python code is written in a .py file and executed from the command line
using python your_script.py.
2. Interactive Mode: Individual statements can be executed directly in the Python interpreter shell,
providing immediate feedback.
In essence, Python's execution model combines compilation (to bytecode) and interpretation (by the PVM), enabling
platform independence and a relatively fast execution process.
1.3 Salient Features of Python
Easy to Learn and Use: Python's syntax is straightforward, resembling natural language. This makes it an ideal
language for beginners. Its simple structure and clear keywords reduce the cost of program maintenance.
Expressive Language: Python allows for writing complex programs in a very concise manner. It has a rich set of
built-in libraries and a large standard library, which means you don't have to write code from scratch for many
common tasks.
Interpreted Language: Python code is executed line by line, which makes debugging easier. The interpreter
executes the code directly without the need for a separate compilation step.
Dynamically Typed: You don't need to declare the data type of a variable when you create it. The interpreter
automatically assigns a type to a variable at runtime. For example, x = 10 makes x an integer, and x = "hello"
makes it a string.
Platform Independent: Python code can run on various platforms like Windows, macOS, and Linux without
needing to be changed. This is due to the Python interpreter being available for all major operating systems.
Extensive Standard Library: Python comes with a vast collection of modules and packages, providing a wide
range of functionalities from web development to scientific computing and data analysis. This "batteries
included" philosophy saves developers a lot of time and effort.
Object-Oriented: Python fully supports object-oriented programming (OOP) concepts such as classes, objects,
inheritance, polymorphism, and encapsulation. This makes it suitable for large-scale application development.
Open Source: Python is developed under an OSI-approved open-source license, making it freely available for use
and distribution, even for commercial purposes. The Python Software Foundation (PSF) manages its
development.
1.4 Areas where Python is in use and Industries that are using Python
Areas where Python is in use:
Web Development:
Python is utilized for building web applications and back-end services using frameworks like Django and Flask.
Data Science and Analysis:
It is a cornerstone for data manipulation, analysis, and visualization with libraries such as Pandas, NumPy, and
Matplotlib.
Artificial Intelligence and Machine Learning:
Python is the dominant language for developing AI and ML models, supported by frameworks like TensorFlow,
Keras, and PyTorch.
Software Development:
It serves as a support language for various software development tasks, including build control, testing, and
automation.
Automation and Scripting:
Python is widely used for automating repetitive tasks and creating system scripts.
Game Development:
It is employed in game development, often for scripting and tool creation.
Scientific Computing and Research:
Python is a preferred language in scientific fields for complex calculations, simulations, and data processing.
Education:
Its beginner-friendly nature makes it a popular choice for teaching programming and computational thinking.
Industries that are using Python:
Technology and Software:
Tech giants and startups alike leverage Python for web services, AI, and internal tools (e.g., Google, Meta, Netflix,
Spotify).
Finance and Fintech:
Python is used for financial modeling, algorithmic trading, risk management, and data analysis in the financial
sector.
Healthcare:
It finds application in medical data analysis, image processing, and developing healthcare applications.
E-commerce:
Python powers recommendation engines, inventory management, and data analytics in online retail.
Academia and Research:
Universities and research institutions extensively use Python for scientific computing, data analysis, and
educational purposes.
Media and Entertainment:
Python is utilized in animation, visual effects, and content delivery platforms.
Space Technology:
Agencies like NASA employ Python for data analysis, research, and scientific computing.
TOPIC 2
2.1 Python Keywords
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator
TOPIC 3: DATA TYPES AND VARIABLES
3.1 Basic Operators
Basic Arithmetic operations that can be performed in Python are explained with examples as under:-
A) Addition
a=10
b=5
c= a+b
print ( c )
B) Subtraction
a=10
b=5
c= a-b
print ( c )
C) Multiplication
a=10
b=5
c= a*b
print ( c )
D) Division
a=10
b=5
c= a/b
print ( c )
TOPIC 4: CONTROL STRUCTURES
4.1 Boolean Operators –
Boolean operators in Python are special keywords that you use to combine conditional statements. They
evaluate to either True or False. Python has three main boolean operators: and, or, and not.
A=10
B=5
C= A==B
Result=False
A=10
B=5
C=!=B
Result=True
4.2 Conditional Execution –
Conditional execution in Python allows a program to make decisions and execute different code blocks based
on whether a given condition is true or false. The primary constructs used for this are the if, elif (short for
"else if"), and else statements.
if statement
The code block following the if statement will only execute if its condition evaluates to True.
A=10
If A>10:
print (“Not Eligible”)
else statement
The else statement is used to define a block of code that should be executed if the if condition is
False. It provides an alternative path for the program to follow.
A=10
If A>10:
print (“Not Eligible”)
else:
print “Eligible”
Result=Eligible
elif statement
The elif statement allows you to check for multiple conditions sequentially. It is placed between the
if and else blocks. Python will check each elif condition in order until one is found to be true. As soon
as a true condition is met, its corresponding code block is executed, and the rest of the elif and else
blocks are skipped.
A=10
If A>10:
print (“Not Eligible”)
elif A>=10
print (“Can be considered”)
else:
print (“Eligible”)
Result=Can be Considered
4.3 Pass Statements –
The pass statement in Python is a null operation. It's a placeholder used when a statement is syntactically
required but you don't want any code to execute. It allows the program to continue without any action.
Passing _Marks=50
Obtained_Marks=40
Result=Obtained_Marks<Passing_Marks
Print (“Fail”)
TOPIC 5: FUNCTIONS
Function- A function is a block of code which only runs when it is called. We can pass data,
known as parameters, into a function. A function can return data as a result.
Eg: def name():
Print(Lisa)
name()
Here, “Name” has been defined as a Function.
Arguments- information that are passed into a function. A parameter is the variable listed
inside the parentheses in the function definition. An argument is the value that is sent to
the function when it is called.
Eg: def name(full name):
print(“My name is” {full name})
name(full name: “Lisa Biswas”)
Return Values and Return Statements- To let a function return a value, we use this.
Eg: def data(x):
return 5*x
print(data(3))
Result=15
Comparison between Return and Print()