0% found this document useful (0 votes)
2 views5 pages

Python Programming Study Guide - MD

This study guide provides an overview of Python programming, covering its history, structure, data types, operators, control flow, functions, data structures, and object-oriented programming concepts. It also includes information on file handling, exception management, and practical tips for studying. Key topics include mutable vs immutable objects, input/output operations, and the use of libraries like NumPy.

Uploaded by

krishgupta1702
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Python Programming Study Guide - MD

This study guide provides an overview of Python programming, covering its history, structure, data types, operators, control flow, functions, data structures, and object-oriented programming concepts. It also includes information on file handling, exception management, and practical tips for studying. Key topics include mutable vs immutable objects, input/output operations, and the use of libraries like NumPy.

Uploaded by

krishgupta1702
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming — Study Guide

UNIT 1: Introduction
History & Application Areas
Python was created by Guido van Rossum, first released in 1991, designed for readability
and simplicity. It's used in web development, data science, AI/ML, automation/scripting,
scientific computing, and embedded systems.

Structure of a Python Program


A Python program is a sequence of statements executed top to bottom. It can include
comments ( # ), import statements, function/class definitions, and a main execution block.
Indentation (not braces) defines code blocks.

Identifiers and Keywords


Identifiers: names given to variables, functions, classes (e.g., total , my_func ). Rules:
must start with a letter or underscore, can contain letters/digits/underscores, case-
sensitive, cannot be a keyword.
Keywords: reserved words with special meaning ( if , else , for , while , def ,
class , import , True , False , None , etc.). Cannot be used as identifiers.

Operators and Precedence


Arithmetic: + - * / // % **

Relational: == != > < >= <=


Logical: and or not
Assignment: = += -= *= /= etc.
Bitwise: & | ^ ~ << >>
Precedence (high to low, simplified): () > ** > * / // % > + - > comparisons >
not > and > or

Basic Data Types & Type Conversion


Types: int , float , complex , str , bool , list , tuple , dict , set , NoneType .
Implicit conversion: Python automatically converts (e.g., int + float → float ).
Explicit conversion: using functions like int() , float() , str() , bool() .
Statements and Expressions
A statement is an instruction (e.g., x = 5 ). An expression is anything that evaluates to a
value (e.g., 5 + 3 ).

Input/Output Statements
input() reads user input as a string.
print() displays output; supports sep and end parameters and f-strings for
formatting.

Strings
Creating/storing: enclosed in single, double, or triple quotes; immutable.
Built-in functions: len() , upper() , lower() , strip() , replace() , split() , find() ,
count() , startswith() , endswith() .

String operators: + (concatenation), * (repetition), in / not in (membership).


Slicing: s[start:stop:step] extracts a substring/sub-sequence.
Joining: "separator".join(list_of_strings) .
Formatting: f-strings ( f"{name} is {age}" ), .format() , % operator.

Control Flow Statements


Conditional: if , elif , else .
Loops: for (iterates over a sequence), while (repeats while a condition is true).
Nested control flow: loops/conditionals inside other loops/conditionals.
Loop control:
break — exits the loop entirely.

continue — skips to the next iteration.


pass — does nothing, used as a placeholder.
exit() — terminates the program.
UNIT 2: Functions, Data Structures, OOP
Functions
Built-in functions: len() , print() , range() , type() , etc. — provided by Python.
Function definition/call: defined using def name(params): , called using name(args) .
Scope and lifetime: local variables exist only within a function; global variables exist
throughout the program; lifetime is how long a variable stays in memory.
Default parameters: parameters with preset values, used if no argument is passed
( def f(x=5): ).
Command line arguments: passed via [Link] when running a script from the
terminal.
Lambda functions: anonymous, one-line functions ( lambda x: x*2 ).
Assert statement: assert condition, "message" — raises an error if the condition is
false; used for debugging/testing.
Importing user-defined modules: use import module_name to reuse code from
another .py file.

Mutable and Immutable Objects


Mutable (can be changed after creation): lists, dictionaries, sets.
Immutable (cannot be changed): tuples, strings, integers, floats.
Lists: ordered, mutable collections — [] . Common functions: append() , insert() ,
remove() , pop() , sort() , reverse() .

Tuples: ordered, immutable collections — () . Common functions: count() ,


index() .

Dictionaries: key-value pairs — {} . Common functions: keys() , values() , items() ,


get() , update() .

Passing as arguments: lists/dicts are passed by reference (changes inside function


affect original); tuples are immutable so can't be changed.

Math and NumPy


math module: provides functions like sqrt() , floor() , ceil() , pi .
NumPy : library for fast operations on arrays of numbers (vectorized math, larger than
plain lists allow efficiently).

Classes, Objects, Inheritance, Polymorphism


Class: a blueprint for creating objects ( class Car: ).
Object: an instance of a class.
Inheritance: a class (child) can inherit attributes/methods from another class
(parent), enabling code reuse ( class ElectricCar(Car): ).
Polymorphism: different classes can implement the same method name in their own
way (e.g., a speak() method behaving differently for Dog vs Cat ).

Regex (Regular Expressions)


Pattern-matching tool from the re module, used to search, match, or replace text patterns
(e.g., validating emails, extracting numbers).

UNIT 3: Files and Exception Handling


Files
Types: text files ( .txt ) and binary files (images, executables).
Operations: open() , read() , write() , close() (or use with open(...) as f: for
automatic closing).
Modes: 'r' read, 'w' write, 'a' append, 'rb' / 'wb' for binary.
Pickle module: serializes (saves) and deserializes (loads) Python objects to/from
binary files using [Link]() and [Link]() .
CSV files: tabular data files; read/write using the csv module ( [Link] ,
[Link] , or [Link] / DictWriter ).

JSON files: structured data format; read/write using the json module ( [Link]() ,
[Link]() ).

Exception Handling
try-except-else-finally:
try : code that might raise an error.

except : handles the error if one occurs.


else : runs if no error occurred.

finally : always runs, regardless of error (used for cleanup).


Raise statement: manually triggers an exception ( raise ValueError("message") ).
Hierarchy of exceptions: all exceptions inherit from the base Exception class;
specific exceptions (e.g., ZeroDivisionError , TypeError ) are subclasses.
Adding exceptions: custom exceptions can be created by defining a new class that
inherits from Exception .
Quick Revision Tips
Practice writing small code snippets for each topic rather than just reading definitions.
For Unit 2, focus on the difference between mutable vs immutable — it's a common
exam question.
For Unit 3, know the order of execution in try-except-else-finally, and be comfortable
reading/writing both CSV and JSON.

You might also like