UNIT-1: Python Fundamentals
Concepts of Interpreter-Based Programming Language
An interpreter-based programming language is a type of programming language in which the code is executed line by line, rather than being compiled into machine code before execution.
The key characteristics of such languages include:
Line-by-Line Execution: The interpreter reads and executes code sequentially.
No Separate Compilation Step: Unlike compiled languages (e.g., C, C++), an interpreter does not generate a separate executable file.
Platform Independence: Since the interpreter executes code at runtime, it allows for easier cross-platform compatibility.
Slower Execution Speed: Interpreted code is generally slower than compiled code because it is translated at runtime.
Easier Debugging: Errors are detected during execution, making debugging more straightforward.
Examples of Interpreter-Based Languages
Python
JavaScript
Ruby
PHP
2.5.1 Structure of Python Programming Language
Python has a well-defined and simple structure that makes it easy to read and write. The basic structure of a Python program includes:
1. Python Script Structure
A typical Python script follows this structure:
# Example of Python Program Structure # 1. Shebang (Optional, for Linux/Unix) #!/usr/bin/python3 # 2. Importing Required Modules import math # 3. Defining Global Variables PI = 3.14159 # 4. Defining Functions def calculate_area(radius): return PI * radius * radius # 5. Main Code Execution if __name__ == "__main__": radius = float(input("Enter radius: ")) area = calculate_area(radius) print(f"Area of circle: {area}")
2. Major Components of Python Program
Shebang (#!) – Used in Unix/Linux environments to specify the interpreter.
Comments (#) – Used to describe the purpose of the code.
Import Statements – To include external libraries/modules.
Global Variables – Defined outside functions for reuse.
Functions – Blocks of reusable code.
Main Execution Block –
if __name__ == "__main__":ensures code runs only when the script is executed directly.
3. Python File Structure
A Python project can have multiple files organized as:
project_name/ │── main.py │── module1.py │── module2.py │── config.py │── /submodules │ ├── helper.py │ ├── utilities.py
main.py – The main entry point of the program.
module1.py, module2.py – Additional Python modules.
config.py – Stores configuration variables.
submodules/ – A directory containing helper functions and utilities.
2.5.2 Python Code Indentation and Execution
1. Importance of Indentation in Python
Python uses indentation to define code blocks instead of braces
{}or keywords likebeginandend.This ensures better readability and enforces structured programming.
Example of correct indentation:
def greet(name): if name: print(f"Hello, {name}!") # Properly indented else: print("Hello, World!") # Consistent indentation greet("Alice")
2. Indentation Errors.
Incorrect indentation leads to IndentationError:
def greet(name): if name: # Incorrect indentation print(f"Hello, {name}!") # This will cause an error ERROR: IndentationError: expected an indented block
3. Python Code Execution Methods
Python programs can be executed in different ways:
1. Running Python in Interactive Mode.
Python provides an interactive shell where you can run Python commands one at a time.
$ python >>> print("Hello, World!") Hello, World!
2. Running a Python Script
You can execute a Python file using the terminal or command prompt:
3. Using an Integrated Development Environment (IDE)
Popular IDEs and text editors for Python development:
IDLE (Default Python IDE)
PyCharm (Powerful IDE for professional use)
VS Code (Lightweight and feature-rich)
Jupyter Notebook (Best for data science and interactive programming)
4. Executing Python Code in Online Interpreters
Web-based platforms like Replit, Google Colab, and OnlineGDB allow Python execution without installation.
4. Python Virtual Environments
A virtual environment in Python is an isolated environment where dependencies are installed separately from the system-wide Python packages.
Creating a virtual environment:
$ python -m venv myenv $ source myenv/bin/activate # On macOS/Linux $ myenv\Scripts\activate # On Windows
2.6 Python Variables
A variable in Python is a container used to store data. Unlike statically typed languages (e.g., C, Java), Python allows dynamic typing, meaning you don’t have to declare the variable type explicitly.
The type is inferred at runtime based on the assigned value.
Example of Variables in Python
x = 10 # Integer y = 3.14 # Float name = "Alice" # String is_active = True # Boolean
2.6.1 Naming of Variables and Dynamic Declaration of Variables
1. Naming Variables in Python
Python follows certain rules and conventions for naming variables:
Rules for Naming Variables
✅ Allowed:
A variable name must start with a letter (A-Z or a-z) or an underscore (_)
It can contain letters, digits (0-9), and underscores (_)
It is case-sensitive (
ageandAgeare different)It cannot be a Python keyword (e.g.,
if,else,for, etc.)
valid_var = 10 # ✅ Valid _age = 25 # ✅ Valid my_var123 = "Hello" # ✅ Valid
❌ Not Allowed:
Cannot start with a number
Cannot contain special characters (!, @, #, $, etc.)
Cannot use spaces in variable names
2var = "Invalid" # ❌ Starts with a number my var = "Invalid" # ❌ Contains space for = 10 # ❌ "for" is a keyword
2. Naming Conventions
Snake Case (Recommended for variables):
user_name,total_priceCamel Case (Common in Java):
userName,totalPriceUppercase (For Constants):
PI = 3.14159
2. Dynamic Declaration of Variables.
Python supports dynamic typing, meaning you do not need to specify the data type when declaring a variable.
Python determines the type at runtime.
x = 10 # Integer x = "Hello" # Now x is a string x = 3.14 # Now x is a float
💡 Advantages of Dynamic Typing:
Makes Python flexible and easy to write
Allows reassignment of different data types
❌ Disadvantage:
Can lead to unintended errors if variable types change unexpectedly
a = 5 # Integer a = "Five" # Now a is a string print(a + 2) # ❌ TypeError: can’t concatenate str and int
2.6.2 Comments in Python.
Comments in Python are lines of text ignored by the interpreter. They are used for documentation and explanation.
1. Single-Line Comments.
Use the # symbol for single-line comments.
# This is a single-line comment x = 10 # Assigning value 10 to x
2. Multi-Line Comments
Python does not have an official syntax for multi-line comments, but you can use triple quotes (''' or """).
""" This is a multi-line comment explaining the code. """ print("Hello, World!")
💡 Best Practices for Comments:
✅ Write meaningful comments to explain complex logic
✅ Use comments to mark TODOs and fixme notes
❌ Avoid redundant comments that restate obvious things
2.6.4 Global Variables
1. What are Global Variables?
A global variable is a variable declared outside a function and is accessible throughout the script.
x = "Global Variable" # Global variable def display(): print(x) # Accessible inside the function display() # Output: Global Variable
2. Modifying Global Variables Inside Functions
To modify a global variable inside a function, use the global keyword.
count = 0 # Global variable def increment(): global count # Declare 'count' as global count += 1 increment() print(count) # Output: 1
3. Local vs. Global Variables
Local Variable: Defined inside a function and cannot be accessed outside.
Global Variable: Defined outside a function and can be accessed anywhere
def test(): local_var = "I'm local" print(local_var) # Works inside the function test() # print(local_var) # ❌ NameError: local_var is not defined
2.7 Python Data Types
A data type in Python defines the type of data that a variable can hold.
Python provides built-in data types that are dynamically assigned based on the value given to a variable.
Major Categories of Python Data Types
Text Type:
str(String)Numeric Types:
int,float,complexBoolean Type:
bool(True/False)
2.7.1 Text (str), Numeric Types (int, float, complex), Boolean (bool)
1. Text Type: str
A string (str) is a sequence of characters enclosed in single (‘ ‘), double (” “), or triple quotes (”’ ”’ or “”” “””).
text1 = 'Hello' # Single quotes text2 = "World" # Double quotes text3 = '''Multiline string example''' # Triple quotes print(text1, text2) print(text3)
✅ Strings support indexing, slicing, and various string methods.
word = "Python" print(word[0]) # Output: P (First character) print(word[-1]) # Output: n (Last character) print(word[1:4]) # Output: yth (Substring from index 1 to 3)
2. Numeric Types
(a) Integer (int)
Integers (int) are whole numbers, positive or negative, without decimals.
x = 10 # Positive integer y = -20 # Negative integer z = 1000000 # Large integer print(type(x)) # Output:
(b) Floating Point (float)
Floating-point numbers (float) represent real numbers with decimal points.
a = 3.14 # Float value b = -0.75 # Negative float c = 1.2e3 # Scientific notation (1.2 * 10^3) print(type(a)) # Output:
(c) Complex Numbers (complex)
Complex numbers (complex) have a real and imaginary part, denoted as a + bj, where j is the imaginary unit.
num = 2 + 3j print(num.real) # Output: 2.0 print(num.imag) # Output: 3.0
3. Boolean Type (bool)
The Boolean type represents True or False values.
x = True y = False print(type(x)) # Output:
✅ Boolean values are commonly used in conditions and comparisons.
a = 5 b = 10 print(a > b) # Output: False print(a < b) # Output: True
2.7.2 Setting Data Types
Python automatically determines the data type when assigning values, but we can explicitly specify the type using the type() function or casting.
1. Implicit Type Assignment
Python dynamically assigns types based on values.
x = 5 # Integer y = 3.14 # Float z = "Hello" # String print(type(x)) # Output:
print(type(y)) # Output: print(type(z)) # Output:
2. Explicit Type Assignment (Using Constructors)
You can set a specific data type using type constructors.
a = str("Hello") # Explicitly setting a string b = int(10) # Explicitly setting an integer c = float(5) # Explicitly setting a float print(type(a)) # Output:
print(type(b)) # Output: print(type(c)) # Output:
2.7.3 Type Conversion and Casting
Python allows conversion between different data types using type conversion and casting.
1. Type Conversion (Automatic Conversion)
Python automatically converts one data type to another when needed.
Example: Implicit Type Conversion
x = 10 # int y = 2.5 # float result = x + y # int + float → float print(result) # Output: 12.5 print(type(result)) # Output:
2. Explicit Type Conversion (Casting)
You can manually convert data types using casting functions:
int()→ Converts to integerfloat()→ Converts to floatstr()→ Converts to string
(a) Converting to Integer (int())
a = int(3.14) # 3 (Truncates decimal) b = int("10") # 10 (Converts string to integer) c = int(True) # 1 (True → 1, False → 0) print(a, b, c) # Output: 3 10 1
(b) Converting to Float (float()).
x = float(10) # 10.0 y = float("3.14") # 3.14 z = float(True) # 1.0 print(x, y, z) # Output: 10.0 3.14 1.0
(c) Converting to Complex (complex())
num = complex(5) print(num) # Output: (5+0j)
(d) Converting to String (str())
a = str(100) # "100" b = str(3.14) # "3.14" c = str(True) # "True" print(a, b, c) # Output: 100 3.14 True
2.8 User-Defined Functions in Python
A function in Python is a block of reusable code that performs a specific task.
Functions make code modular, organized, and reusable, improving readability and maintainability. Python allows users to define their own functions using the
defkeyword.
2.8.1 Defining Functions & Functions with Parameters
1. Defining a Function
A function in Python is defined using the def keyword, followed by a function name, parentheses (), and a colon :.
The function body is indented.
Syntax:
def function_name(): # Function body print("This is a user-defined function") Example: def greet(): print("Hello! Welcome to Python.") greet() # Calling the function
2. Function with Parameters
A function can accept input values, called parameters or arguments, which allow passing dynamic data to the function.
Syntax:
def function_name(parameter1, parameter2): # Function body
Example: Function with Parameters
def greet(name): print("Hello,", name) greet("Alice") # Passing an argument greet("Bob")
Example: Function with Multiple Parameters
def add_numbers(a, b): sum = a + b print("Sum:", sum) add_numbers(5, 10) # Output: Sum: 15
2.8.2 Parameters with Default Values & Functions with Return Values
1. Parameters with Default Values
Python allows setting default values for parameters. If no argument is passed, the default value is used.
Syntax:
def function_name(parameter=value): # Function body EXAMPLE def greet(name="Guest"): print("Hello,", name) greet("Alice") # Output: Hello, Alice greet() # Output: Hello, Guest (Uses default value)
✅ Advantages of Default Parameters:
Makes functions more flexible.
Prevents errors if an argument is missing.
Useful for optional parameters.
2. Function with a Return Value
Functions can return a value using the return statement. This allows us to store and use the function’s output.
Syntax:
def function_name(parameters): return value EXAMPLE def add(a, b): return a + b # Returning the sum result = add(5, 3) print("Result:", result) # Output: Result: 8
✅ Benefits of Return Values:
Allows storing function results in variables.
Makes functions reusable in different parts of the program.
Combining Default Values & Return Values.
def multiply(a, b=2): # b has a default value return a * b print(multiply(5)) # Uses default b=2 → Output: 10 print(multiply(5, 3)) # Uses b=3 → Output: 15
Conclusion.
Python follows a structured approach with scripts organized into modules.
Indentation is mandatory for defining blocks of code.
Python programs can be executed in interactive mode, script mode, IDEs, or online interpreters.
Using a virtual environment helps manage dependencies efficiently.
Variables in Python are dynamically declared and follow specific naming rules.
Comments improve code readability and debugging.
Python supports multiple assignments and value unpacking.
Global variables can be accessed everywhere, but need the
globalkeyword for modification inside functions.Python has built-in text (
str), numeric (int,float,complex), and boolean (bool) data types.You can set data types explicitly using type constructors.
Python allows implicit type conversion and explicit type casting (
int(),float(),str()).Understanding data types helps in writing efficient and error-free Python programs.
Functions allow code reusability and modularity.
Parameters help pass dynamic data.
Default values make parameters optional.
Return values allow functions to send data back for further use.