0% found this document useful (0 votes)
0 views11 pages

Python_Programming_Exam_Notes

This document provides comprehensive notes on Python programming, covering fundamental concepts such as data types, control structures, functions, and object-oriented programming. It includes details on numbers, strings, lists, dictionaries, classes, and error handling, along with examples for clarity. Additionally, it highlights the use of modules, command-line arguments, and the Python standard library.

Uploaded by

archanas190704
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)
0 views11 pages

Python_Programming_Exam_Notes

This document provides comprehensive notes on Python programming, covering fundamental concepts such as data types, control structures, functions, and object-oriented programming. It includes details on numbers, strings, lists, dictionaries, classes, and error handling, along with examples for clarity. Additionally, it highlights the use of modules, command-line arguments, and the Python standard library.

Uploaded by

archanas190704
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 — Exam Notes

Unit I & Unit II

UNIT I — Python Basics and Code Structures

1. Numbers
• Store numerical values. Types: int (whole numbers), float (decimals), complex (real + imaginary).
• Arithmetic operators: + - * / // % ** (floor division, modulus, power).
x = 25
y = 10.5
z = 3 + 4j

2. Strings
• A sequence of characters in single or double quotes.
• Common methods: upper(), lower(), strip(), replace(), split().
name = "Archana"
message = "Hello Python"
print([Link]())
print(message[0:5])

3. Variables
• A name used to store a value; Python auto-detects the data type.
• Rules: letters, numbers, underscore allowed; can't start with a number; can't be a keyword;
case-sensitive.
name = "Anu"
age = 20
mark = 85.5
print(type(age))

4. Lists
• Ordered, mutable collection. Allows duplicates and mixed data types.
numbers = [10, 20, 30, 40]
[Link](50)
[Link](20)
[Link](1, 15)
print(numbers)

5. Tuples
• Ordered, immutable collection, written with ().
• List vs Tuple: List is mutable & uses [ ]; Tuple is immutable & uses ( ).
numbers = (10, 20, 30, 40)
print(numbers[0])

6. Dictionaries
• Stores data as key-value pairs.
• Useful methods: keys(), values(), items(), get(), pop().
student = {"name": "Anu", "age": 20, "mark": 85}
print(student["name"])
student["course"] = "MSc CS"

7. Sets
• Unordered collection of unique elements — duplicates removed.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference

8. Comparison Operators
Operator Meaning

== Equal

!= Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

a = 10
b = 20
print(a < b) # True

9. if, elif, else


Conditional statements used to make decisions.
mark = 75
if mark >= 90:
print("A+")
elif mark >= 60:
print("A")
else:
print("B")

10. while Loop


Repeats a block of code while a condition is true.
i = 1
while i <= 5:
print(i)
i += 1

11. for Loop


Used to iterate through a sequence.
for i in range(1, 6):
print(i)
12. Comprehensions
A short way to create collections.
numbers = [i * 2 for i in range(1, 6)]
even = [i for i in range(10) if i % 2 == 0]
13. Functions
• A reusable block of code that performs a specific task.
• Advantages: code reusability, less repetition, easier debugging, better organization.
def add(a, b):
return a + b

result = add(10, 20)


print(result)

14. Generators
A special function that produces values one at a time using yield. Saves memory.
def numbers():
for i in range(1, 4):
yield i

for n in numbers():
print(n)

15. Decorators
Modifies or extends a function's behavior without changing its original code.
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper

@decorator
def hello():
print("Hello")

hello()

16. Namespace and Scope


• A namespace keeps names and their objects. Scope determines where a variable can be accessed.
• Types: Local, Global, Built-in. Python follows the LEGB rule: Local → Enclosing → Global → Built-in.
x = 10 # Global
def test():
y = 20 # Local
print(x)
print(y)

test()

17. Handling Errors — try and except


• Exceptions are errors during execution; try/except handle them.
• The finally block executes whether an exception occurs or not.
try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")

18. User-Defined Exceptions


A custom exception can be created using a class derived from Exception.
class AgeError(Exception):
pass

age = 15
try:
if age < 18:
raise AgeError("Age must be 18 or above")
except AgeError as e:
print(e)
UNIT II — Modules, Programs, Objects and Classes

19. Standalone Programs


A program that can be executed directly. The __name__ == '__main__' condition makes code run only
when the file is executed directly.
def main():
print("Hello")

if __name__ == "__main__":
main()

20. Command-Line Arguments


Values passed to a program while running it, via the sys module.
import sys
print([Link])

For python [Link] Hello 20: [Link][0] is [Link], [Link][1] is Hello, [Link][2] is 20.

21. Modules
• A Python file containing functions, variables or classes that can be reused.
• Types: user-defined modules, standard library modules, third-party modules.
import math
print([Link](25))

22. import Statement


Used to access functions/classes from another module.
import math
print([Link](25))

from math import sqrt


print(sqrt(25))

import math as m
print([Link](25))

23. Python Standard Library


Module Purpose

math Mathematical operations

random Random numbers

datetime Date and time

os Operating system operations

sys System-related operations

json JSON data

re Regular expressions

statistics Statistical calculations


24. Objects and Classes
A class is a blueprint for creating objects. An object is an instance of a class.
class Student:
pass

s1 = Student()

Student is the class and s1 is the object.


25. Define a Class
Defined using the class keyword. __init__() runs automatically when an object is created.
class Student:
def __init__(self, name, mark):
[Link] = name
[Link] = mark

def display(self):
print([Link], [Link])

s1 = Student("Anu", 90)
[Link]()

26. Inheritance
Allows one class to acquire properties and methods from another. Animal = parent/base class, Dog =
child/derived class.
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
pass

d = Dog()
[Link]()

27. Override a Method


Occurs when a child class provides its own version of a parent method.
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self):
print("Dog barks")

d = Dog()
[Link]()

28. Add a Method


A child class can have extra methods not present in the parent class.
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def run(self):
print("Dog runs")

d = Dog()
[Link]()
[Link]()
29. Get/Set Attributes with Properties
Properties give controlled access to attributes, supporting validation and encapsulation.
class Student:
def __init__(self, name):
self._name = name

@property
def name(self):
return self._name

@[Link]
def name(self, value):
self._name = value

s = Student("Anu")
print([Link])
[Link] = "Riya"
print([Link])
30. Method Types
• Instance method: uses self.
• Class method: uses cls and @classmethod.
• Static method: uses neither self nor cls; uses @staticmethod.
class Student:
school = "ABC"

def display(self):
print("Student")

@classmethod
def show(cls):
print([Link])

@staticmethod
def add(a, b):
return a + b

s = Student()
[Link]()
[Link]()
print([Link](10, 20))

31. Special Methods


Also called dunder methods (double underscores). Examples: __init__(), __str__(), __len__(),
__add__().
class Student:
def __init__(self, name):
[Link] = name

def __str__(self):
return [Link]

s = Student("Anu")
print(s)

Quick Memory Guide


Concept Remember

List Changeable

Tuple Unchangeable

Set Unique values

Dictionary Key + Value

Function Reusable code

Generator yield, one value at a time

Decorator Modifies a function


Class Blueprint

Object Instance of class

Inheritance Reuse parent class

Overriding Child changes parent method

Property Controlled attribute access

Exception Runtime error

You might also like