UNIT-2: Python Fundamentals

UNIT-2: Python Fundamentals

2.1 Concepts of Interpreter-Based Programming Language.

What is an Interpreter-Based Programming Language?

  • An interpreter-based language executes the code line by line instead of compiling the entire program before running it. Python is an interpreted language, unlike C or Java, which are compiled.

How an Interpreter Works

  1. The Python Interpreter reads the source code (.py file).
  2. It converts it into an intermediate bytecode (.pyc).
  3. The Python Virtual Machine (PVM) executes the bytecode.

Key Characteristics of an Interpreter-Based Language

  1. Executes code line by line (helps in debugging).
  2. No separate compilation step (direct execution).
  3. Slower execution speed than compiled languages (since interpretation happens at runtime).
  4. Highly portable (can run on different platforms without recompilation).
  5. Dynamic typing (variable types are determined at runtime).
  6. Supports interactive execution (Python shell allows running commands interactively).

Example: Interpreter vs. Compiler

Feature Interpreter (Python) Compiler (C, Java)
Execution Line-by-line Whole program at once
Speed Slower execution Faster execution
Error Detection Stops at the first error Shows all errors after compilation
Platform Independence High (No recompilation needed) Low (Needs recompilation for different OS)

2.1.1 Structure of Python Programming Language

A Python program follows a structured approach with:
  • Comments
  • Imports
  • Variable declarations
  • Functions
  • Conditional statements
  • Loops
  • Main function execution (if __name__ == "__main__")

Basic Structure of a Python Program.

# 1. Importing necessary modules import math # 2. Defining a function def area_of_circle(radius): return math.pi * radius ** 2 # 3. Return statement # 4. Main block execution if __name__ == "__main__": r = 5 print("Area of Circle:", area_of_circle(r)) # Function Call

Detailed Breakdown of Python Structure

1. Comments in Python

Python supports single-line and multi-line comments.
 
# This is a single-line comment """ This is a multi-line comment. Python ignores these lines. """ print("Hello, Python!")

2. Importing Modules

Python allows the use of pre-built modules for additional functionality.
import math # Importing the math module print(math.sqrt(25)) # Output: 5.0

3. Declaring and Using Variables

Variables in Python don’t require explicit type declarations.
x = 10 # Integer y = 3.14 # Float name = "John" # String print(type(x), type(y), type(name))

4. Functions in Python

Functions help reuse code and make programs more structured.
def greet(name): # Function with a parameter return "Hello, " + name print(greet("Alice")) # Output: Hello, Alice

5. Conditional Statements (if-elif-else)

Python uses if, elif, and else to control the flow..
num = 10 if num > 0: print("Positive Number") elif num < 0: print("Negative Number") else: print("Zero")

6. Loops in Python

Python supports for loops and while loops.

For Loop

for i in range(1, 6): print("Iteration:", i)

While Loop

count = 0 while count < 5: print("Count:", count) count += 1

7. Using the __name__ == "__main__" Block

This block ensures that code runs only when the script is executed directly, not when imported as a module.
def say_hello(): print("Hello, World!") # Ensuring the function runs only if the script is executed directly if __name__ == "__main__": say_hello()

2.1.2 Python Code Indentation and Execution.

Indentation in Python

Python does not use {} like C/C++ for block structures. Instead, it uses indentation.

Correct Example:

def greet(): print("Hello, World!") # Indentation is correct greet()

Why Indentation is Important?

  1. Python uses indentation instead of curly braces {}.
  2. Each block of code (inside functions, loops, and conditions) must be indented.
  3. Incorrect indentation results in IndentationError.

Ways to Execute Python Code

  1. Using the Python Interpreter
    • Run python or python3 in the terminal and type commands interactively.
  2. Running a Python File
    • Save a file as program.py and execute it with:
python program.py
3. Using an IDE (PyCharm, VS Code, Jupyter Notebook, etc.)
  • Run scripts inside an IDE for better debugging and visualization.

Example: Complete Python Program.

Here’s a complete Python program demonstrating all elements:
# 1. Importing module import math # 2. Defining a function def circle_area(radius): return math.pi * radius ** 2 # 3. Conditional statement def check_number(num): if num > 0: return "Positive" elif num < 0: return "Negative" else: return "Zero" # 4. Loop example def print_numbers(n): for i in range(1, n + 1): print(i, end=" ") # 5. Main Execution if __name__ == "__main__": r = 5 print("Area of Circle:", circle_area(r)) num = -10 print("Number Type:", check_number(num)) print("Numbers from 1 to 5:") print_numbers(5)

2.2 Python Variables.

What is a Variable in Python?

A variable is a name that stores a value in memory. In Python, variables are dynamically typed, meaning we don’t need to declare their type explicitly.

Example: Declaring and Using Variables

x = 10 # Integer y = 3.14 # Float name = "Alice" # String print(x, y, name) # Output: 10 3.14 Alice

2.2.1 Naming of Variables and Dynamic Declaration of Variables

Naming Rules for Variables

  1. Must start with a letter (A-Z or a-z) or an underscore (_)
  2. Can contain letters, digits (0-9), and underscores (_), but no special characters
  3. Cannot start with a number
  4. Case-sensitive (myVar and myvar are different)
  5. Cannot use Python keywords (e.g., if, for, while, def, etc.)

Examples: Valid and Invalid Variable Names

Valid Variable Names
my_var = 10 _name = "Alice" age2 = 25 MAX_VALUE = 100
Invalid Variable Names (will cause errors)
2name = "John" # Cannot start with a number my-var = 20 # Cannot use special characters def = "Python" # Cannot use reserved keywords

Dynamic Declaration of Variables

  • Python is dynamically typed, meaning we don’t need to declare a variable type beforehand. Python automatically assigns a type based on the assigned value.
x = 10 # Integer x = "Hello" # Now x is a string (Dynamic typing) print(x) # Output: Hello

2.2.2 Comments in Python

Comments are used to make the code more readable. Python ignores comments during execution.

Types of Comments

  1. Single-Line Comment (#)
# This is a single-line comment print("Hello, Python!") # This is also a comment
2. Multi-Line Comment (""" """ or ''' ''')
""" This is a multi-line comment. It can span multiple lines. """ print("Python is fun!")

2.2.3 Assigning Values to Multiple Variables

Python allows multiple variable assignments in a single line.

Example 1: Assigning Different Values

a, b, c = 10, 20, 30 print(a, b, c) # Output: 10 20 30

Example 2: Assigning the Same Value

x = y = z = 50 print(x, y, z) # Output: 50 50 50

2.2.4 Global Variables.

What is a Global Variable?

A global variable is declared outside any function and can be accessed throughout the program.
global_var = "I am global" def my_function(): print(global_var) # Accessing global variable inside function my_function() # Output: I am global

Modifying a Global Variable Inside a Function

If we need to modify a global variable inside a function, we must use the global keyword.
x = 10 # Global variable def update(): global x # Declaring x as global x = x + 5 print("Inside function:", x) # Output: Inside function: 15 update() print("Outside function:", x) # Output: Outside function: 15

Using Global and Local Variables

  • Local variables exist only inside a function.
  • Global variables exist throughout the program.
def my_function(): local_var = "I am local" print(local_var) # This works my_function() # print(local_var) # This will cause an error (local_var is not accessible outside the function)

Complete Python Program Example.

# 1. Declaring global variable global_message = "Hello from global scope!" # 2. Function demonstrating local variable def my_function(): local_message = "Hello from local scope!" print(local_message) # 3. Function demonstrating modifying global variable def modify_global(): global global_message global_message = "Global variable modified!" print(global_message) # Main Execution if __name__ == "__main__": my_function() print(global_message) # Accessing global variable modify_global()

2.3 Python Data Types.

Python has several built-in data types that define the type of value a variable can hold. The most commonly used data types include:
  1. Text Typestr
  2. Numeric Typesint, float, complex
  3. Boolean Typebool
  4. Sequence Typeslist, tuple, range
  5. Set Typesset, frozenset
  6. Mapping Typedict
  7. Binary Typesbytes, bytearray, memoryview
  8. None TypeNoneType

2.3.1 Text (str), Numeric Type (int, float, complex), Boolean (bool)

1. Text Type (str)

  • Strings (str) are sequences of characters enclosed in single ('), double ("), or triple quotes (''' """).
  • Strings are immutable, meaning they cannot be changed once created.
text1 = "Hello, Python!" text2 = 'Single-quoted string' text3 = """Triple-quoted string""" print(text1) # Output: Hello, Python! print(type(text1)) # Output:

String Operations

name = "Alice" print(name.upper()) # Converts to uppercase print(name.lower()) # Converts to lowercase print(name[0]) # Access first character print(name[1:3]) # Slice string (index 1 to 2) print(len(name)) # Length of the string

2. Numeric Types

a) Integer (int)
  • Whole numbers, both positive and negative, without decimals.
num1 = 10 num2 = -20 print(num1, type(num1)) # Output: 10 print(num2, type(num2)) # Output: -20

b) Floating Point (float)

  • Numbers with decimal points or in scientific notation.
pi = 3.14159 large_num = 2.5e3 # Scientific notation (2.5 × 10³) print(pi, type(pi)) # Output: 3.14159 print(large_num, type(large_num)) # Output: 2500.0

c) Complex Numbers (complex)

  • Python supports complex numbers in the form of a + bj, where j represents the imaginary unit.
 
comp_num = 3 + 5j print(comp_num, type(comp_num)) # Output: (3+5j) print(comp_num.real) # Output: 3.0 (Real part) print(comp_num.imag) # Output: 5.0 (Imaginary part)

3. Boolean Type (bool)

  • Boolean values represent True or False.
  • In Python, True is equivalent to 1, and False is equivalent to 0.
is_python_fun = True is_raining = False print(is_python_fun, type(is_python_fun)) # Output: True print(5 > 3) # Output: True print(5 == 10) # Output: False

2.3.2 Setting Data Types

Python automatically assigns the data type based on the assigned value. However, we can also explicitly define data types using constructors.

Example: Setting Data Types

x = str("Hello") # Explicitly setting as string y = int(10) # Explicitly setting as integer z = float(20.5) # Explicitly setting as float c = complex(1, 2) # Explicitly setting as complex number b = bool(True) # Explicitly setting as boolean print(type(x), type(y), type(z), type(c), type(b)) # Output:

2.3.3 Type Conversion (int, float, complex), Casting (int, float, str)

Type Conversion

Type conversion allows us to convert data from one type to another.

a) Converting int to float and complex

a = 10 b = float(a) # Converts int to float c = complex(a) # Converts int to complex print(b, type(b)) # Output: 10.0 print(c, type(c)) # Output: (10+0j)

b) Converting float to int and complex

x = 7.9 y = int(x) # Converts float to int (removes decimal part) z = complex(x) # Converts float to complex print(y, type(y)) # Output: 7 print(z, type(z)) # Output: (7.9+0j)

c) Converting complex to int or float

  • Complex numbers cannot be converted directly to int or float. It will result in an error.
c = 3 + 4j # int(c) # ❌ This will raise an error # float(c) # ❌ This will also raise an error

Casting (Explicit Type Conversion)

Python provides built-in functions for type casting:

  • int(): Converts a value to an integer.
  • float(): Converts a value to a floating point number.
  • str(): Converts a value to a string.

a) Casting float and str to int

num1 = 10.99 num2 = "123" int_num1 = int(num1) # Converts float to int (truncates decimal) int_num2 = int(num2) # Converts string to int print(int_num1, type(int_num1)) # Output: 10 print(int_num2, type(int_num2)) # Output: 123

b) Casting int and str to float

num1 = 50 num2 = "45.67" float_num1 = float(num1) # Converts int to float float_num2 = float(num2) # Converts string to float print(float_num1, type(float_num1)) # Output: 50.0 print(float_num2, type(float_num2)) # Output: 45.67

c) Casting int and float to str

num1 = 100 num2 = 99.99 str_num1 = str(num1) # Converts int to string str_num2 = str(num2) # Converts float to string print(str_num1, type(str_num1)) # Output: "100" print(str_num2, type(str_num2)) # Output: "99.99"

2.4 User-Defined Functions in Python

  • In Python, functions are reusable blocks of code that perform specific tasks. A user-defined function is a function created by a programmer to organize code efficiently.

2.4.1 Defining Functions and Using Parameters

Defining a Function

To define a function, we use the def keyword, followed by the function name and parentheses ().

Syntax:

def function_name(): # Function body (code to execute) print("Hello, this is a user-defined function")

Example:

def greet(): print("Welcome to Python!") greet() # Calling the function

Function with Parameters

Functions can accept parameters (inputs) to process data dynamically.
Syntax:
def function_name(parameter1, parameter2): # Code that uses parameters

Example.

def greet_user(name): print(f"Hello, {name}!") greet_user("Alice") greet_user("Bob")

Example with Multiple Parameters:

def add_numbers(a, b): sum_result = a + b print("Sum:", sum_result) add_numbers(10, 20)

2.4.2 Parameter with Default Value & Function with Return Value

Function with Default Parameter Values

If no value is provided when calling the function, the default value is used.

Example:

def greet(name="Guest"): print(f"Hello, {name}!") greet() # Default value used greet("Charlie") # Custom value provided

Function with a Return Value

Functions can return results using the return statement.

Example:

def square(num): return num * num result = square(5) print("Square:", result)

Function with Multiple Return Values

A function can return multiple values using tuples.

Example:

def calculations(a, b): sum_result = a + b difference = a - b return sum_result, difference s, d = calculations(15, 5) print("Sum:", s, "Difference:", d)
Key Takeaways.
  • Variables in Python are dynamically typed (no need for explicit declaration).
  • Variable names must follow specific naming rules (letters, numbers, underscores, no special characters or keywords).
  • Comments (#, """ """) are used to make the code readable.
  • Multiple variables can be assigned values in one line.
  • Global variables can be accessed anywhere in the program but require the global keyword to be modified inside a function.
  • Local variables exist only inside the function where they are declared.
  • Python has various data types (int, float, str, complex, bool).
  • Type conversion allows conversion between int, float, complex.
    Casting functions (int(), float(), str()) are used for explicit conversion.
  • Functions allow code reusability.
  • Parameters enable functions to process dynamic input.
  • Default parameters prevent errors when arguments are missing.
  • Return statements give back results for further use.

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.