Introduction to Python

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability with its notable use of significant whitespace.

History of Python

  • 1989: Python development started by Guido van Rossum
  • 1991: Python 0.9.0 released
  • 2000: Python 2.0 released
  • 2008: Python 3.0 released
  • 2020: Python 2.7 end-of-life

First Python Program

# Simple Python Program print("Hello, World!")

Python Features

Python has several distinctive features that make it popular for various applications.

Key Features of Python

  • Easy to Learn: Simple syntax similar to English
  • Interpreted Language: Code executed line by line
  • Cross-platform: Runs on Windows, Linux, Mac OS
  • Object-Oriented: Supports OOP concepts
  • Dynamic Typing: No need to declare variable types
  • Large Standard Library: Rich set of modules and packages
  • Open Source: Free to use and distribute
  • GUI Programming: Supports GUI application development
Note: Python uses indentation (whitespace) to define code blocks instead of curly braces {} like other programming languages.

Python Data Types

Python has various built-in data types that are used to store different kinds of data.

Basic Data Types

Data Type Description Example
int Integer numbers 5, -10, 1000
float Floating point numbers 3.14, -2.5, 10.0
str String of characters "Hello", 'Python'
bool Boolean values True, False
complex Complex numbers 3+4j, 2-5j

Sequence Data Types

Data Type Description Example
list Ordered, mutable collection [1, 2, 3], ['a', 'b', 'c']
tuple Ordered, immutable collection (1, 2, 3), ('a', 'b', 'c')
range Sequence of numbers range(5), range(1, 10)
# Data type examples # Numeric types x = 5 # int y = 3.14 # float z = 2 + 3j # complex # String name = "Python" # Boolean is_active = True # List numbers = [1, 2, 3, 4, 5] # Tuple coordinates = (10.5, 20.3) print(type(x)) # Output: <class 'int'> print(type(name)) # Output: <class 'str'>

Variables and Operators

Variables are used to store data values. Python has no command for declaring variables - they are created when you assign a value.

Variable Naming Rules

  • Must start with a letter or underscore
  • Cannot start with a number
  • Can only contain alpha-numeric characters and underscores
  • Case-sensitive (age, Age, and AGE are different variables)

Python Operators

  • Arithmetic Operators: +, -, *, /, %, **, //
  • Comparison Operators: ==, !=, >, <,>=, <=
  • Logical Operators: and, or, not
  • Assignment Operators: =, +=, -=, *=, /=
  • Identity Operators: is, is not
  • Membership Operators: in, not in
# Variable assignment age = 25 name = "Alice" height = 5.6 is_student = True # Multiple assignment a, b, c = 5, 10, 15 # Operator examples x = 10 y = 3 print(x + y) # Addition: 13 print(x - y) # Subtraction: 7 print(x * y) # Multiplication: 30 print(x / y) # Division: 3.333... print(x % y) # Modulus: 1 print(x ** y) # Exponentiation: 1000 print(x // y) # Floor division: 3

Control Statements

Control statements determine the flow of execution in a Python program.

Conditional Statements

  • if statement: Executes block if condition is true
  • if-else statement: Executes one block if true, another if false
  • if-elif-else statement: Multiple conditions checking
# if-elif-else example marks = 85 if marks >= 90: print("Grade A") elif marks >= 75: print("Grade B") elif marks >= 50: print("Grade C") else: print("Grade F")

Looping Statements

  • for loop: Iterates over a sequence
  • while loop: Executes while condition is true
# for loop example for i in range(5): print(i) # Output: 0 1 2 3 4 # while loop example count = 0 while count < 5: print(count) count += 1 # Output: 0 1 2 3 4

Loop Control Statements

  • break: Exits the loop
  • continue: Skips the current iteration
  • pass: Does nothing (placeholder)

Functions in Python

A function is a block of code that performs a specific task and can be reused.

Function Definition and Calling

# Function definition def greet(name): print(f"Hello, {name}!") # Function call greet("Alice") # Output: Hello, Alice!

Function with Return Value

# Function with return value def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8

Types of Function Arguments

  • Positional arguments: Passed in correct positional order
  • Keyword arguments: Passed with parameter names
  • Default arguments: Parameters with default values
  • Variable-length arguments: *args and **kwargs
# Different types of arguments def student_info(name, age=18, *subjects, **details): print(f"Name: {name}") print(f"Age: {age}") print(f"Subjects: {subjects}") print(f"Details: {details}") # Function call student_info("John", 20, "Math", "Science", grade="A", city="New York")
Exam Tip: Remember that *args is used for variable non-keyword arguments (tuple), and **kwargs is used for variable keyword arguments (dictionary).

Python Data Structures

Python provides several built-in data structures to store and organize data efficiently.

Lists

# List operations fruits = ["apple", "banana", "cherry"] # Accessing elements print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry # List methods fruits.append("orange") # Add element fruits.insert(1, "mango") # Insert at position fruits.remove("banana") # Remove element print(len(fruits)) # Length of list

Tuples

# Tuple operations coordinates = (10, 20) # Accessing elements print(coordinates[0]) # Output: 10 # Tuple unpacking x, y = coordinates print(x, y) # Output: 10 20

Dictionaries

# Dictionary operations student = { "name": "Alice", "age": 20, "grade": "A" } # Accessing values print(student["name"]) # Output: Alice print(student.get("age")) # Output: 20 # Dictionary methods print(student.keys()) # All keys print(student.values()) # All values print(student.items()) # All key-value pairs

Sets

# Set operations set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} # Set operations print(set1 | set2) # Union: {1, 2, 3, 4, 5, 6} print(set1 & set2) # Intersection: {3, 4} print(set1 - set2) # Difference: {1, 2}

Object-Oriented Programming in Python

Python supports object-oriented programming (OOP) concepts like classes, objects, inheritance, polymorphism, and encapsulation.

Class and Object

# Class definition class Student: # Constructor def __init__(self, name, age): self.name = name self.age = age # Method def display(self): print(f"Name: {self.name}, Age: {self.age}") # Object creation s1 = Student("Alice", 20) s1.display() # Output: Name: Alice, Age: 20

Inheritance

# Inheritance example class Animal: def __init__(self, name): self.name = name def speak(self): print("Animal makes sound") class Dog(Animal): def speak(self): print("Dog barks") # Using inheritance dog = Dog("Buddy") dog.speak() # Output: Dog barks

Encapsulation

# Encapsulation example class BankAccount: def __init__(self): self.__balance = 0 # Private attribute def deposit(self, amount): if amount > 0: self.__balance += amount def get_balance(self): return self.__balance account = BankAccount() account.deposit(100) print(account.get_balance()) # Output: 100

File Handling in Python

Python provides built-in functions for creating, reading, updating, and deleting files.

File Operations

# Writing to a file with open("example.txt", "w") as file: file.write("Hello, Python!") # Reading from a file with open("example.txt", "r") as file: content = file.read() print(content) # Output: Hello, Python!

File Modes

Mode Description
"r" Read (default)
"w" Write (creates new file or truncates existing)
"a" Append
"r+" Read and write
"b" Binary mode
Exam Tip: Using the 'with' statement for file handling is recommended as it automatically closes the file, even if an exception occurs.

Exception Handling

Exception handling allows programs to handle runtime errors gracefully.

Try-Except Block

# Basic exception handling try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")

Multiple Exceptions

# Handling multiple exceptions try: num = int(input("Enter a number: ")) result = 10 / num except ValueError: print("Invalid input! Please enter a number.") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"An error occurred: {e}")

Finally Block

# Using finally block try: file = open("data.txt", "r") # File operations except FileNotFoundError: print("File not found!") finally: print("This block always executes")

Modules and Packages

Modules are Python files containing functions, classes, and variables. Packages are collections of modules.

Creating and Using Modules

# mymodule.py def greet(name): print(f"Hello, {name}!") def add(a, b): return a + b # main.py import mymodule mymodule.greet("Alice") # Output: Hello, Alice! result = mymodule.add(5, 3) print(result) # Output: 8

Standard Library Modules

  • math: Mathematical functions
  • datetime: Date and time operations
  • os: Operating system interfaces
  • sys: System-specific parameters
  • random: Generate random numbers
  • json: JSON encoding and decoding
# Using standard library modules import math import datetime import random print(math.sqrt(16)) # Output: 4.0 print(datetime.datetime.now()) # Current date and time print(random.randint(1, 10)) # Random number between 1-10

Popular Python Libraries

Python has a rich ecosystem of third-party libraries for various applications.

Data Science Libraries

  • NumPy: Numerical computing
  • Pandas: Data manipulation and analysis
  • Matplotlib: Data visualization
  • Scikit-learn: Machine learning

Web Development Libraries

  • Django: High-level web framework
  • Flask: Micro web framework
  • Requests: HTTP library

Other Important Libraries

  • Tkinter: GUI programming
  • OpenCV: Computer vision
  • BeautifulSoup: Web scraping
  • PyGame: Game development
Important: Python's extensive library ecosystem is one of its biggest strengths, allowing developers to build complex applications with minimal code.
Exam Tip: Be familiar with the purpose and basic usage of popular Python libraries like NumPy, Pandas, and Django, as these are frequently asked in competitive exams.