0% found this document useful (0 votes)
3 views8 pages

Basics of Python Advanced Lecture Notes

Python is a high-level, interpreted, and object-oriented programming language known for its readability and versatility, supporting various programming paradigms. It has two main versions: Python 2.x (discontinued) and Python 3.x (actively developed), with applications in web development, data science, machine learning, and more. Key features include dynamic typing, a large standard library, and easy installation across multiple platforms.

Uploaded by

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

Basics of Python Advanced Lecture Notes

Python is a high-level, interpreted, and object-oriented programming language known for its readability and versatility, supporting various programming paradigms. It has two main versions: Python 2.x (discontinued) and Python 3.x (actively developed), with applications in web development, data science, machine learning, and more. Key features include dynamic typing, a large standard library, and easy installation across multiple platforms.

Uploaded by

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

Basics of Python

Advanced / Detailed Lecture Notes


2.1 Introduction to Python, Python Features, Applications
Introduction
Python is a high-level, general-purpose, interpreted, and object-oriented programming language. It was created
by Guido van Rossum and first released in 1991 (named after the British comedy series “Monty Python’s Flying
Circus”, not the snake).
Python emphasizes code readability through significant use of indentation and a clean, minimal syntax, which
reduces the cost of program maintenance. It supports multiple programming paradigms, including procedural,
object-oriented, and functional programming.
Versions of Python
• Python 2.x – legacy version, officially discontinued (end-of-life January 2020).
• Python 3.x – current and actively developed version; all new projects use Python 3.

Features of Python (Detailed)


• Simple & Easy to Learn – syntax resembles plain English; ideal for beginners, reduces development time.
• Interpreted Language – code executes line-by-line via the Python interpreter; no separate compilation step,
which simplifies debugging.
• Free and Open Source – released under an OSI-approved open-source licence; source code can be modified
and redistributed.
• High-Level Language – abstracts away memory management and hardware-level operations (automatic
garbage collection).
• Portable / Platform-Independent – the same Python code runs on Windows, Linux, and macOS without
modification (“write once, run anywhere”).
• Object-Oriented – supports classes, objects, inheritance, polymorphism, and encapsulation.
• Extensible and Embeddable – Python code can call functions written in C/C++, and Python itself can be
embedded in other applications.
• Large Standard Library – “batteries included” philosophy; built-in modules for file I/O, networking, regex,
math, etc.
• Dynamically Typed – variable types are determined at runtime; no need to declare a type explicitly.
• Interactive Mode – supports an interactive shell (REPL) for testing code snippets instantly.
• Automatic Memory Management – uses reference counting and a garbage collector to free unused
memory.
• Support for GUI Programming – libraries like Tkinter, PyQt for building desktop applications.

Applications of Python (Detailed)


Domain Common Tools/Libraries Typical Use

Web Development Django, Flask, FastAPI Building server-side web applications


and APIs

Data Science & Analytics Pandas, NumPy, Matplotlib Data cleaning, analysis, and visualization

Machine Learning / AI TensorFlow, PyTorch, scikit-learn Building predictive models and AI


Domain Common Tools/Libraries Typical Use

systems

Automation / Scripting os, shutil, Selenium Automating repetitive tasks, web


scraping

Game Development Pygame 2D game development and prototyping

Desktop GUI Applications Tkinter, PyQt, Kivy Building desktop software with a UI

Networking & Security Scapy, socket module Network tools, penetration testing
scripts

Software Testing PyTest, unittest, Robot Framework Automated testing of applications

2.2 Python Installation


Installing Python (Windows/Mac/Linux)
1. Visit the official website: [Link] and go to the Downloads section.
2. Choose the installer matching your operating system (Windows/macOS/Linux) and the latest stable release.
3. Run the downloaded installer. On Windows, tick the checkbox “Add Python to PATH” before proceeding —
this allows Python to be run from any terminal location.
4. Click “Install Now” (or customize the install location if required) and wait for setup to finish.
5. Verify the installation by opening Command Prompt / Terminal and running:
python --version
pip --version
On Linux, Python 3 is often pre-installed; use python3 --version to check. Use sudo apt install python3 on
Debian/Ubuntu systems if it is missing.

IDEs and Editors


Tool Description

IDLE Comes bundled with Python; simple built-in editor and shell

PyCharm Full-featured professional IDE with debugging, refactoring tools

VS Code Lightweight, extensible editor with a strong Python extension

Jupyter Notebook Cell-based interactive environment, popular for data science

Google Colab Cloud-based Jupyter environment; no installation required

Running a Python Program


• Interactive Mode – type python (or python3) in the terminal to open the REPL and run statements directly.
• Script Mode – write code in a file with .py extension (e.g., [Link]) and run it using:
python [Link]
2.3 Basic Structure, Comments, Keywords, Identifiers, Variables, Data
Types, Operators
Basic Structure of a Python Program
# This program adds two numbers
a = 10
b = 20
sum = a + b
print("Sum is:", sum)
Key structural rules in Python:
• No semicolons are required to end a statement (though optional).
• No curly braces { } for blocks — indentation (usually 4 spaces) defines a block of code.
• Statements are generally written one per line; a backslash (\) can continue a statement onto the next line.
• Python programs typically follow this general structure: comments/documentation → import statements →
function/class definitions → main program logic.
# import module
import math

# function definition
def square(x):
return x * x

# main program logic


print(square(5))

Python Comments
Comments are non-executable lines used to explain code; the interpreter ignores them.
• Single-line comment – begins with the # symbol; everything after it on that line is ignored.
• Multi-line comment – Python has no dedicated multi-line comment symbol; triple-quoted strings (''' … ''' or
""" … """) are commonly used as a workaround, though technically they are string literals.
# This is a single-line comment
x = 5 # comment after a statement

"""
This is treated as a multi-line comment
when not assigned to a variable
"""

Keywords
Keywords are reserved words that have a fixed, predefined meaning to the Python interpreter. They cannot be
used as identifiers (variable/function/class names). Python 3 has 35 keywords, including:

Category Examples

Conditional / Loop if, elif, else, for, while, break, continue, pass

Function / Class def, return, class, lambda, yield


Category Examples

Logical / Boolean and, or, not, True, False, None

Exception Handling try, except, finally, raise

Module Handling import, from, as

Others global, nonlocal, in, is, with, del, assert

Identifiers
An identifier is the name used to identify a variable, function, class, module, or other object.
Rules for naming identifiers
• Can contain letters (a–z, A–Z), digits (0–9), and underscore (_).
• Must begin with a letter or an underscore — never with a digit.
• Cannot be a reserved keyword (e.g., class, for).
• Cannot contain spaces or special symbols such as @, #, %, etc.
• Python identifiers are case-sensitive — Age, age, and AGE are all different names.
Naming conventions (best practice)
• Variables and functions: lowercase with underscores — student_name, calculate_total().
• Constants: all uppercase — PI, MAX_SIZE.
• Classes: CamelCase — StudentRecord, BankAccount.

Variables
A variable is a named location in memory used to store data that can change during program execution. Python
variables do not need explicit type declaration — the type is inferred automatically from the assigned value
(dynamic typing).

x = 5 # integer
name = "John" # string
price = 99.5 # float
a = b = c = 10 # multiple assignment, same value
x, y, z = 1, 2, 3 # multiple assignment, different values
A variable's type can change during execution because Python re-binds the name to whatever object is assigned
to it (this is different from statically typed languages like C or Java).

Data Types
Python has several built-in data types, broadly classified as:

Category Data Type Example Description

Numeric int x = 10 Whole numbers, positive or negative

Numeric float x = 10.5 Decimal (floating-point) numbers

Numeric complex x = 2+3j Complex numbers with real & imaginary parts

Text str x = "Hi" Sequence of Unicode characters


Category Data Type Example Description

Boolean bool x = True Logical value: True or False

Sequence list x = [1,2,3] Ordered, mutable (changeable) collection

Sequence tuple x = (1,2,3) Ordered, immutable (unchangeable) collection

Mapping dict x = {"a":1} Unordered collection of key–value pairs

Set set x = {1,2,3} Unordered collection of unique items


The type() function can be used to check the data type of any variable, e.g. type(x).

Operators
Operators are special symbols used to perform operations on variables and values.

Type Operators Example Meaning

Arithmetic + - * / % ** // a + b a ** b a // b Addition/Sub/Mul/Div,
Modulus, Exponent,
Floor Division

Comparison (Relational) == != > < >= <= a == b Compares two values;


returns True/False

Logical and or not a > 5 and b < 10 Combines conditional


statements

Assignment = += -= *= /= %= **= a += 1 Assigns or updates a


value in one step

Bitwise & | ^ ~ << >> a&b Operates on binary


representations of
integers

Membership in , not in x in list Tests if a value exists in a


sequence

Identity is , is not a is b Tests if two variables


refer to the same object
in memory

a = 10
b = 3
print(a + b) # 13 -> addition
print(a % b) # 1 -> remainder
print(a ** b) # 1000 -> a to the power b
print(a // b) # 3 -> floor division

2.4 Type Conversion


Type conversion (type casting) means converting a value from one data type into another. Python supports two
kinds of type conversion:
1. Implicit Type Conversion
Performed automatically by the Python interpreter, without the programmer's intervention. Python converts a
smaller/lower data type into a larger/higher data type to prevent data loss (this is also called type promotion).

x = 5 # int
y = 2.5 # float
z = x + y # int is implicitly converted to float
print(z) # 7.5
print(type(z)) # <class 'float'>
Order of implicit promotion (simplified): bool → int → float → complex.

2. Explicit Type Conversion (Type Casting)


Performed manually by the programmer using Python's built-in conversion functions, when Python cannot or
should not convert automatically (e.g., converting a string to a number).

Function Purpose Example

int(x) Converts x to an integer int("10") → 10

float(x) Converts x to a float float("3.5") → 3.5

str(x) Converts x to a string str(25) → "25"

list(x) Converts an iterable to a list list((1,2,3)) → [1,2,3]

tuple(x) Converts an iterable to a tuple tuple([1,2,3]) → (1,2,3)

bool(x) Converts x to a Boolean value bool(0) → False

a = "10"
b = int(a) # explicitly converts string to int
print(b + 5) # 15

c = 25
d = str(c) # explicitly converts int to string
print("Value is " + d) # Value is 25

Points to remember
• Explicit conversion can raise a ValueError if the value cannot be logically converted (e.g., int("abc")).
• Converting a float to an int using int() truncates (removes) the decimal part; it does not round the number.
• Implicit conversion never leads to data loss; explicit conversion might (e.g., float to int).

Quick Summary
• Python is a simple, free, portable, object-oriented, interpreted language used across web, data science, AI,
automation, and more.
• Install from [Link]; verify with python --version; write code in .py files or use IDEs like PyCharm/VS
Code/Jupyter.
• Python programs use indentation instead of braces; comments use # (single-line) or triple quotes (multi-
line workaround).
• Keywords are reserved words; identifiers are user-defined, case-sensitive names following specific naming
rules.
• Variables need no explicit type declaration; common data types include int, float, complex, str, bool, list,
tuple, dict, and set.
• Operators include arithmetic, comparison, logical, assignment, bitwise, membership, and identity
operators.
• Type conversion can be implicit (automatic, safe) or explicit (manual, using int(), float(), str(), etc., which
may raise errors or lose precision).

You might also like