PYTHON PROGRAMMING
23UCSCC13 / 23UBCAC13
History of Python Programming Language
• Guido van Rossum, a Dutch programmer, created Python.
• The name “Python” was inspired by the British comedy group Monty Python, not the
snake
• Python 1.x (1991) version - Python 0.9.0
• Python 2.x (2000)
• Python 3.x (2008 – Present)-Current stable version (as of mid-2025): Python 3.12
• Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages
• Easy to read and write
• Open-source
• One of the most popular programming languages in the world (Top 3 since 2020s)
Python Features
sno Feature Description
1 Simple Syntax Easy to read and write; beginner-friendly
2 Interpreted No compilation required; runs code line by line
3 Dynamically Typed No need to declare data types; flexible variable handling
4 Standard Library Rich set of built-in modules for various functionalities
5 Object-Oriented Supports classes, inheritance, encapsulation, and polymorphism
6 Cross-Platform Runs on Windows, macOS, Linux without modification
7 Community Support Vast online resources, forums, and third-party libraries
8 Memory Management Automatic garbage collection and dynamic memory allocation
9 Multiple Paradigms Supports OOP, procedural, functional, and imperative styles
sno Feature Description
10 Exception Handling Structured handling of runtime errors using try/except
11 Supports multi-threading, multi-processing, and async
Concurrency
programming
12 Data Structures Built-in support for lists, tuples, dictionaries, and sets
13 Integration Can integrate with C, C++, Java, .NET, and databases
14 Libraries for Data Libraries like NumPy, Pandas, Matplotlib, TensorFlow,
Science PyTorch
15 Web Development Frameworks like Django, Flask, FastAPI for web applications
LITERALS
Literals are fixed values used directly in code to represent data.
1. String Literals
A string literal is a sequence of characters enclosed in quotes.
Examples:
name = "John"
greeting = 'Hello'
multiline1 = '''This is
a multiline
string'''
multiline2 = ”””This is
a multiline
string”””
2. Numeric Literals
Numeric literals represent numerical values and can be of different types like integers,
floating-point numbers, and complex numbers.
2.1 Integer Literals
Integer literals are whole numbers without a decimal point.
Examples:
decimal = 42
hexadecimal = 0x2A
octal = 0o52
binary = 0b101010
2.2 Floating-Point Literals
Floating-point literals represent real numbers that have a fractional part.
Examples:
pi = 3.14159
exp = 1.23e4
2.3 Complex Number Literals
Complex literals represent numbers with a real and imaginary part.
Examples:
complex_num = 3 + 4j
3. Boolean Literals
Boolean literals represent truth values: True and False.
Examples:
is_active = True
is_approved = False
4. None Literal
The None literal represents the absence of a value or a null value.
Examples:
result = None
5. Set Literals
A set literal represents a collection of unique, unordered elements.
Examples:
fruits = {'apple', 'banana', 'orange'}
numbers = set([1, 2, 3, 4])
6. Dictionary Literals
A dictionary literal represents a collection of key-value pairs.
Examples:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
7. List Literals
A list literal represents an ordered collection of elements.
Examples:
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
8. Tuple Literals
A tuple literal represents an ordered, immutable collection of elements.
Examples:
coordinates = (10, 20)
person_info = ("Alice", 30, "Engineer")
9. Bytes Literals
A bytes literal represents a sequence of bytes (immutable).
Examples:
data = b"Hello, world!" # Bytes literal
CONSTANT
A constant is a value that should not change during the execution of a program. Python
does not have built-in constant support, like some other languages (e.g., const in C++ or Java).
However, by convention, constants are written in uppercase letters with underscores.
1. Mathematical Constant:
PI = 3.14159
E = 2.71828
GRAVITY = 9.8
2. Configuration settings:
MAX_CONNECTIONS = 1000
TIMEOUT = 15
3. UI Color Constants:
BACKGROUND_COLOR = "#FFFFFF"
TEXT_COLOR = "#000000"
BUTTON_COLOR = "#FF5733"
VARIABLES
A variable is a name that refers to a value stored in memory. It acts as a container for storing
data that can be used and updated throughout a program.
Syntax:
variable_name = value
Example:
x = 10 # Integer
name = "Alice" # String
price = 9.99 # Float
is_active = True # Boolean
a, b, c = 1, 2, 3 # assigning values to Multiple variables
Rules for Naming Variables
Must start with a letter (A–Z or a–z) or an underscore _
Can contain letters, numbers, and underscores
Cannot start with a number
No spaces or special characters
Cannot be a Python keyword (like if, class, for, etc.)
Types of Variables
Global Variable: Defined outside functions, accessible anywhere.
Local Variable: Defined inside a function, accessible only within that function.
Example
x = 10 # Global
def example():
x = 5 # Local
print("Inside function:", x)
example()
print("Outside function:", x)
IDENTIFIERS
• An identifier is the name used to identify a variable, function, class,
module, or object.
• It is essentially any name you define in your code to label something. Python
uses identifiers to recognize different parts of a program.
• Identifiers are case-sensitive.
• Reserved Keywords Are Not Identifiers
Example:
name = "Alice" # 'name' is an identifier (variable)
def greet(): # 'greet' is an identifier (function)
class Person: # 'Person' is an identifier (class)
pass
Rules for Writing Identifiers
• Must start with a letter (A–Z or a–z) or an underscore _
• Can contain letters, digits (0–9), and underscores
• Cannot start with a digit (e.g., 1name is invalid)
• Cannot use special characters like @, $, %, etc.
• Cannot be a Python keyword (e.g., class, if, while)
KEYWORDS
Keywords are reserved words that have special meanings to the interpreter.
You cannot use them as identifiers (like variable names, function names, or class names).
DATA TYPES
Data types represent the kind of value a variable holds. Python has several built-in data
types that allow you to work with different kinds of values in your programs.
Text Type : str
Numeric Types : int, float, complex
Sequence Types : list, tuple, range
Mapping Type : dict
Set Types : set, frozenset
Boolean Type : bool
Binary Types : bytes, bytearray, memoryview
None Type : NoneType
Built-in Data Types in Python
1. Numeric Types
Integer (int): Represents whole numbers, both positive and negative.
Floating Point (float): Represents numbers with decimal points.
Complex Numbers (complex): Numbers with both a real and imaginary part.
Examples:
x = 42
y = 3.14
z = 1 + 2j
2. Text Type
String (str): Represents text. Strings are sequences of characters enclosed in quotes
(single or double).
Examples:
name = "Alice"
greeting = 'Hello'
multiline = '''This is
a multiline string'''
3. Sequence Types
List (list): Ordered collection of items, which can be of different data types. Lists are
mutable (can be changed).
Tuple (tuple): Ordered collection of items, but unlike lists, tuples are immutable
(cannot be changed once created).
Range (range): Represents an immutable sequence of numbers, often used for looping.
Examples:
my_list = [1, 2, 3, "a", True]
my_tuple = (1, 2, 3, "a")
my_range = range(10)
4. Mapping Type
Dictionary (dict): Represents a collection of key-value pairs. Keys must be unique and
immutable.
Example:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
5. Set Types
Set (set): Unordered collection of unique elements. Sets are mutable.
Frozen Set (frozenset): An immutable version of a set.
Examples:
my_set = {1, 2, 3}
my_frozenset = frozenset([1, 2, 3])
6. Boolean Type
Boolean (bool): Represents one of two values: True or False.
Example:
is_active = True
is_complete = False
7. Binary Types
Bytes (bytes): Immutable sequence of bytes, used for binary data.
Bytearray (bytearray): Mutable version of bytes.
Memoryview (memoryview): A memory view object that allows access to the internal
memory of a byte-like object without copying.
Examples:
b = b"hello"
byte_arr = bytearray([65, 66, 67])
mem_view = memoryview(b"hello")
OUTPUT STATEMENTS:-
The primary mechanism for producing output is the built-in print() function. This
function allows for the display of information to the console or other specified output streams.
Basic Syntax:
print(object(s))
Example
print("Hello, Python!")
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
object(s): This represents the value(s) to be printed. It can be a string, a number, a
variable, or any other Python object. Multiple objects can be passed, separated by commas.
Optional Parameters Syntax:
print(object(s),sep='separator', end='end_string', file=file_object, flush=False)
Example :-
print("Apple", "Banana", "Cherry", sep="-")
print("This is the first part.", end=" ")
print("This is the second part on the same line.")
with open("output.txt", "w") as f:
print("This will be written to a file.", file=f)
print("This will be printed immediately.", flush=True)
sep='separator': Specifies the separator between multiple objects when they are printed. By
default, it's a single space (' ').
end='end_string': Specifies what to print at the end of the output. By default, it's a newline
character ('\n'), causing subsequent print() calls to start on a new line.
file=file_object: Directs the output to a specified file-like object instead of the default standard
output (the screen, sys.stdout).
flush=False: A boolean value that, when True, forces the output buffer to be immediately
flushed, ensuring the output appears without delay. By default, it's False, meaning output might
be buffered.
INPUT STATEMENTS:-
Python uses Input () functions to take input from keyboard. This function takes value
from keyboard and returns as a string.
Syntax:-
variable_name = input(prompt_message)
x = input()
print(x)
print(“ Enter Your age”)
age_str = input("Enter your age: ")
age_int = int(age_str)
age_int = int(input("Enter your age: "))
variable_name: This is the name of the variable where the user's input will be stored.
input(): This is the function that prompts the user for input.
prompt_message (optional): This is a string that will be displayed to the user before they enter
their input. This message serves as a prompt, guiding the user on what to enter.
Comments
Comments in Python are used to explain code, making it more readable and
understandable for both the original developer and others who might work with the code in the
future. The Python interpreter ignores comments during program execution
Single-line comments: These start with a hash symbol (#). Everything from the # to the
end of the line is considered a comment.
Multi-line comments (using multi-line strings): multi-line strings enclosed in triple
quotes (''' or """) are often used for this purpose.
Example –
# This is a single-line comment
print("Hello, World!") # This is an inline comment
"""
This is a multi-line comment.
It can span across multiple lines.
"""
Indentation
Indentation refers to the spaces or tabs placed at the beginning of a code line.
Indentation is not just for readability—it defines the structure of the code.
Python uses indentation to define blocks of code.
Blocks of code are required for constructs such as functions, loops, conditionals (if, else,
elif), and classes.
All statements with the same indentation level are considered part of the same block.
Example:-
a = 10
if a > 5:
print("a is greater than 5") # This line is indented - inside if block
print("End")
Operators
Operators are special symbols or keywords that perform operations on operands (values
or variables) to produce a result.
Operator Type Significance Examples / Symbols Sample Usage
Arithmetic Math operations +, -, *, /, %, //, ** a + b,a * b
Assignment Assign/modify values =, +=, -=, *=, /=, //= a = 5,a += 1
Comparison Compare values ==, !=, >, <, >=, <= a == b,a <= b
Logical
(Boolean) Logical (True/False) ops and, or, not a and b,not a
a is b,a is not
Identity Object identity testing is, is not b
Sequence membership
Membership testing in, not in 'a' in 'abc'
Bitwise Bit-level operations &, ^, ~, <<, >> a<<b, a^b
Expression
An expression in Python is a combination of values, variables, operators, and function
calls that is interpreted to produce another value.
Type Example Code Output
Constant Expression x = 15 + 1.3 16.3
Arithmetic Expression x = 40; y = 12; x + y 52
Integral Expression a = 13; b = 12.0; c = a + int(b) 25
Floating Expression a = 13; b = 5; c = a / b 2.6
Relational Expression p = (21 + 13) >= (40 - 37) TRUE
Logical Expression R = (10==9) and (7>5) FALSE
Bitwise Expression , ^, ~, <<, >>) a = 12; x = a >> 2; y = a << 1
Combinational
Expression a = 16; b = 12; c = a + (b >> 1) 22
List/Dict/Generator [x for x in range(5)],
Comp {x:x**2 ...} [1][2][3][4], ...
Conditional Expression x = "1" if True else "2" "1"
Type Conversions in Python
Type conversion means changing a value from one data type to another. Python supports
two main forms of type conversion: implicit and explicit.
1. Implicit Type Conversion
Performed automatically by Python when combining different
numeric types.
No user intervention is needed.
Designed to avoid loss of data (usually converts to the more
general type, like int to float).
Example:
x = 10 # int
y = 3.5 # float
z=x+y # x (int) converted to float before the addition
print(z) # Output: 13.5
print(type(z)) # Output: <class 'float'>
2. Explicit Type Conversion (Type Casting)
Performed manually by the user using built-in functions.
Useful when you want to force a value into a specific type.
Risk of data loss (e.g., converting float "3.7" to int gives 3).
Example:-
num_str = "45"
num_int = int(num_str) # Explicit conversion from str to int
print(num_int + 5) # Output: 50
# Float to string
value = str(3.14)
print(value) # Output: "3.14"
# List from a string
chars = list('hello')
print(chars) # Output: ['h', 'e', 'l', 'l', 'o']
Function Purpose Example Output
int('7'), 7,
int() Converts to integer int(3.8) 3
float('7.4'), 7.4,
float() Converts to float float(3) 3.0
str(57), "57"
str() Converts to string str(True) ,"True"
False,
bool() Converts to boolean bool(0), bool("abc") True
list() Converts iterable to list list("abc") ['a', 'b', 'c']
tuple() Converts iterable to tuple tuple([1][2][3]) (1, 2, 3)
set() Converts iterable to set set([1][2][2][3]) {1, 2, 3}
dict() Tuple of key-value to dict dict([('a',1), ('b',2)]) {'a': 1, 'b': 2}
complex() Converts to complex number complex(2,3) (2+3j)
Arrays
1. Defining Arrays in Python
An array is a data structure that stores multiple items (of the same type) in a
single variable.
Python doesn’t have a native array data structure, but you can use:
Lists (list) for flexible, array-like structures that allow mixed data types and have
more built-in operations.
1. Creating an array:
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5]) # 'i' = integer type code
2. Processing Arrays:
Access Elements: Use a[index].
Update Elements: Assign a[index] = value.
Slicing: Use a[start:stop] to get a sub-array.
Iteration: Use loops, e.g., for item in a: print(item).
Length: Use len(a) for array or list length.
Efficient Storage: array is optimized for large sequences of identical types.
3. Arrays Methods:
Method Description Example Use
append() Adds an element at the end a.append(4)
a.extend([5]
extend() Adds all items from another iterable [6])
insert() Adds an element at a particular index a.insert(1, 20)
remove(
) Removes the first occurrence of a specified value a.remove(20)
Removes and returns the element at a specified
pop() index a.pop(2)
clear() Removes all elements from the array or list a.clear()
index() Returns the index of the first specified value a.index(5)
count() Returns the number of occurrences of a value a.count(2)
reverse() Reverses the array or list in place a.reverse()
copy() Returns a shallow copy a.copy()
sort()
(*) Sorts the list (not available for array.array) a.sort()
HOME TEST
Day Order DATE Topics
Day-1: 22-08-2025 Variables - Identifiers - Keywords
Day :-2 23-08-2025 Literals - Built-in Data Types
Day -:3:- 24-08-2025 INPUT Statements
Day-4:- 25-08-2025 OUTPUT Statements
Day-5:- 26-08-2025 Indentation – Comments - Features of Python
Day -6:- 27-08-2025 Operators – Expressions
Day -7:- 28-08-2025 Type Conversions
Day-8:- 29-08-2025 Python Arrays: Defining and Processing Arrays – Array methods.
Day-9:- 30-08-2025 Revision Test-1 ( All Topics)
Day-10:- 31-08-2025 Revision Test-2 ( All Topics)
Day -11:- 01-09-2025 Unit I Slip Test-1 ( on Class Room)