Docsity

Python Programming Complete Notes: OOP, Functions, File Handling, NumPy, Pandas & Programs, Lecture notes of Computer Science

Partial preview of the text

Download Python Programming Complete Notes: OOP, Functions, File Handling, NumPy, Pandas & Programs and more Lecture notes Computer Science in PDF only on Docsity!

PYTHON PROGRAMMING COMPLETE NOTES

Basics • Functions • OOP • File Handling • NumPy • Pandas • Solved Programs SEO Keywords: Python programming notes, Python basics, Python OOP, Python functions, file handling, NumPy, Pandas, solved Python programs, programming notes for beginners, computer science notes.

Table of Contents

ļ‚· 1. Introduction to Python ļ‚· 2. Python Basics and Syntax ļ‚· 3. Variables and Data Types ļ‚· 4. Operators and Expressions ļ‚· 5. Conditional Statements ļ‚· 6. Loops ļ‚· 7. Strings ļ‚· 8. Lists, Tuples, Sets and Dictionaries ļ‚· 9. Functions ļ‚· 10. Exception Handling ļ‚· 11. File Handling ļ‚· 12. Object-Oriented Programming ļ‚· 13. Classes, Objects, Inheritance and Polymorphism ļ‚· 14. NumPy ļ‚· 15. Pandas ļ‚· 16. Data Analysis Basics ļ‚· 17. Solved Python Programs ļ‚· 18. Practice Questions ļ‚· 19. Quick Revision Sheet ļ‚· 20. Final Mini Project

Chapter 2: Python Basics and Syntax

Python programs are written as statements and blocks. Indentation is significant in Python.

Comments

Use # for a single-line comment. Comments explain code and are ignored by Python.

Input and Output

input() receives text from the user. print() displays output.

Example

The following program reads a name and prints a greeting.

Chapter 3: Variables and Data Types

A variable is a name that refers to a value. Python determines the type at runtime.

Common Data Types

ļ‚· int: whole numbers ļ‚· float: decimal numbers ļ‚· str: text ļ‚· bool: True or False ļ‚· list: ordered mutable collection ļ‚· tuple: ordered immutable collection ļ‚· set: unordered collection of unique values ļ‚· dict: key-value collection

Type Conversion

int(), float(), str() and bool() can convert values when the conversion is valid.

Example

A student's marks can be stored in an integer variable and a percentage in a float variable.

Chapter 5: Conditional Statements

Conditional statements allow a program to make decisions.

if Statement

Runs a block when a condition is true.

if-else

Chooses between two alternatives.

elif

Tests additional conditions in sequence.

Example

A result program can display Pass when marks are at least 40; otherwise it can display Fail.

Chapter 6: Loops

Loops repeat a block of code.

for Loop

A for loop is commonly used to iterate through a sequence or range.

while Loop

A while loop repeats while its condition remains true.

break and continue

break exits a loop; continue skips the current iteration.

Example

Print numbers from 1 to 10 using a for loop.

Chapter 8: Lists, Tuples, Sets and Dictionaries

Python provides several built-in collection types for storing multiple values.

Lists

Lists are ordered and mutable. Common methods include append(), insert(), remove(), pop() and sort().

Tuples

Tuples are ordered and immutable.

Sets

Sets store unique elements and support union, intersection and difference.

Dictionaries

Dictionaries store key-value pairs and support methods such as keys(), values(), items() and get().

Example

Store student names and marks in a dictionary and display each record.

Chapter 9: Functions

A function is a reusable block of code that performs a task.

Defining a Function

Use the def keyword followed by the function name and parameters.

Parameters and Return Values

Parameters receive input; return sends a result back to the caller.

Default Arguments

A default value is used when an argument is omitted.

Lambda Functions

A lambda is a small anonymous function, useful for short expressions.

Example

Create a function that accepts two numbers and returns their sum.

Chapter 11: File Handling

File handling allows Python programs to read and write persistent data.

Opening Files

Use open(filename, mode). Common modes are r for read, w for write, a for append and x for create.

Reading

read(), readline() and readlines() provide different ways to retrieve file content.

Writing

write() adds text to a file.

Best Practice

Use a with open(...) block so the file is closed automatically.

Example

Write three student names to a text file and then read them.

Chapter 12: Object-Oriented Programming

OOP organizes programs around objects that contain data and behavior.

Core Concepts

ļ‚· Class: blueprint for objects ļ‚· Object: instance of a class ļ‚· Encapsulation: bundling data and methods ļ‚· Inheritance: creating a new class from an existing class ļ‚· Polymorphism: same interface with different behavior

Why OOP?

OOP can improve organization, reuse and maintainability in larger programs.

Example

Create a Student class with name and marks and a method to display the record.

Chapter 14: NumPy

NumPy is a Python library for numerical computing and multidimensional arrays.

Creating Arrays

np.array() converts Python sequences into NumPy arrays.

Array Operations

NumPy supports fast element-wise arithmetic, slicing and aggregation.

Useful Functions

ļ‚· np.zeros() ļ‚· np.ones() ļ‚· np.arange() ļ‚· np.mean() ļ‚· np.sum() ļ‚· np.max() ļ‚· np.min()

Example

Calculate the sum and average of a NumPy array.

Chapter 15: Pandas

Pandas is a Python library for data manipulation and analysis.

Series

A Series is a one-dimensional labeled data structure.

DataFrame

A DataFrame is a two-dimensional labeled table.

Common Operations

ļ‚· head() ļ‚· tail() ļ‚· info() ļ‚· describe() ļ‚· drop() ļ‚· sort_values() ļ‚· groupby()

Reading Data

pd.read_csv() is commonly used to load CSV data into a DataFrame.

Example

Create a DataFrame containing student names and marks and calculate the average.

Chapter 17: Solved Python Programs

1. Add Two Numbers

a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) print("Sum =", a + b) Explanation: The program reads two numbers and prints their sum.

2. Check Even or Odd

n = int(input("Enter a number: ")) if n % 2 == 0: print("Even") else: print("Odd") Explanation: A number is even when its remainder after division by 2 is zero.

3. Find Largest of Three Numbers

a = float(input("A: ")) b = float(input("B: ")) c = float(input("C: ")) print("Largest =", max(a, b, c)) Explanation: max() returns the largest value.

4. Factorial

n = int(input("Enter n: ")) fact = 1 for i in range(1, n + 1): fact *= i print("Factorial =", fact) Explanation: The loop multiplies all integers from 1 through n.

5. Multiplication Table

n = int(input("Enter number: ")) for i in range(1, 11): print(n, "x", i, "=", n * i) Explanation: The range creates ten iterations for the table.

6. Prime Number Check

n = int(input("Enter number: ")) if n < 2: print("Not prime") else: prime = True for i in range(2, int(n ** 0.5) + 1): if n % i == 0: prime = False break print("Prime" if prime else "Not prime")

Explanation: A prime number has no divisor other than 1 and itself.

7. Reverse a String

text = input("Enter text: ") print(text[::-1]) Explanation: Slicing with a step of -1 reverses the string.

8. Count Vowels

text = input("Enter text: ").lower() count = 0 for ch in text: if ch in "aeiou": count += 1 print("Vowels =", count) Explanation: The loop checks each character against the vowel set.

9. File Write and Read

with open("students.txt", "w") as f: f.write("Ali\nSara\nNoor") with open("students.txt", "r") as f: print(f.read()) Explanation: The with statement automatically closes each file.

10. OOP Student Class

class Student: def init(self, name, marks): self.name = name self.marks = marks def display(self): print(self.name, self.marks) s1 = Student("Noor", 85) s1.display() Explanation: The class stores student data and provides a display method.

11. NumPy Array Statistics

import numpy as np arr = np.array([10, 20, 30, 40, 50]) print("Sum:", np.sum(arr)) print("Mean:", np.mean(arr)) print("Maximum:", np.max(arr)) Explanation: NumPy functions calculate common statistics efficiently.