Docsity

Python programming complete notes and exercise, Study Guides, Projects, Research of Computer science

Toggle sidebar
bg1
PYTHON PROGRAMMING
Complete Study Notes: Beginner to Intermediate
Concepts • Syntax • Examples • Practice Questions
A learning and revision guide for Python 3
Python Programming Notes • Page 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Python programming complete notes and exercise and more Study Guides, Projects, Research Computer science in PDF only on Docsity!

PYTHON PROGRAMMING

Complete Study Notes: Beginner to Intermediate

Concepts • Syntax • Examples • Practice Questions

A learning and revision guide for Python 3

How to Use These Notes

These notes cover core Python from the first program through commonly used intermediate

concepts. Type each example into a Python 3 interpreter, run it, change the values, and observe

the result. Programming is learned by practising, testing and improving code.

 Start with the early chapters if you are new to programming.

 Practise every code example rather than only reading it.

 Use the questions and exercises near the end for revision.

 Python has many specialist areas; this guide focuses on core language features and selected

standard-library tools.

Contents

1. Introduction to Python

2. Installing and running Python

3. Syntax, comments and indentation

4. Variables and data types

5. Input, output and type conversion

6. Operators

7. Conditional statements

8. Loops

9. Strings

10. Lists, tuples, sets and dictionaries

11. Functions

12. Modules and packages

13. File handling

14. Exceptions and error handling

15. Object-oriented programming

16. Comprehensions, iterators and generators

17. Useful built-in functions

18. Standard library essentials

19. Virtual environments and pip

20. Debugging, testing and good practices

21. Common algorithms and examples

22. Practice questions and quick revision

Comments

This is a comment

print("Learn Python") # comment after code

Comments explain code and are ignored by the interpreter. Triple-quoted strings are often used

as docstrings to document modules, classes and functions.

Identifiers and naming

 Names can contain letters, digits and underscores, but cannot start with a digit.

 Names are case-sensitive: score and Score are different.

 Do not use keywords such as if, class or for as variable names.

 Prefer descriptive names such as total_marks instead of unclear names such as x1.

4. Variables and Data Types

A variable is a name that refers to a value. Assignment uses =.

student = "Mina" age = 16 marks = 87. is_present = True nothing = None

Type Meaning Example

int Whole number 12, -4, 0

float Decimal number 3.14, -0.

str Text "Python"

bool Logical value True, False

NoneType No value None

list Ordered, mutable collection [2, 4, 6]

tuple Ordered, immutable collection (2, 4, 6)

set Unique items {2, 4, 6}

dict Key-value mapping {"name": "Mina"}

x = 10 print(type(x)) x = "ten" print(type(x))

Python is dynamically typed. Type annotations can document intended types, but they do not

normally enforce types at runtime.

age: int = 16 name: str = "Mina"

5. Input, Output and Type Conversion Output and f-strings name = "Ravi" print("Hello", name) print(f"Hello, {name}!")

An f-string allows expressions inside curly braces, making formatted output convenient.

Input name = input("Enter your name: ") print("Welcome,", name)

input() returns a string, even if the user types digits.

Type conversion age = int(input("Enter age: ")) height = float("1.65") text = str(25)

 int(value) converts suitable values to integers.

 float(value) converts suitable values to floating-point numbers.

 str(value) creates a string representation.

 bool(value) follows truth-value rules: an empty string is false, but the non-empty string "False"

is true.

 Invalid conversions can raise ValueError.

6. Operators

Category Operators Purpose

Arithmetic + - * / // % ** Calculations, division,

remainder and powers

Comparison == != > < >= <= Compare values

Logical and, or, not Combine or reverse conditions

Assignment = += -= *= /= Assign or update a variable

Membership in, not in Check membership in a

collection

Identity is, is not Check whether references

point to the same object

a = 7 b = 2 print(a + b) # 9 print(a / b) # 3. print(a // b) # 3 print(a % b) # 1 print(a ** b) # 49 print(a > b) # True

break print(n) Nested loops for row in range(1, 4): for col in range(1, 4): print(row, col)

9. Strings

A string is a sequence of characters. Strings are immutable, so individual characters cannot be

changed in place.

message = "Python Programming" print(message[0]) print(message[-1]) print(message[0:6]) print(len(message))

Indexing starts at 0. Slicing uses sequence[start:stop:step], and stop is excluded.

Method Purpose Example

lower() Lowercase copy "HELLO".lower()

upper() Uppercase copy "hello".upper()

strip() Remove surrounding

whitespace

" hi ".strip()

replace(a,b) Replace text "cat".replace("c","b")

split() Split into a list "a b".split()

join(items) Join strings "-".join(["a","b"])

find(sub) Find a substring position "banana".find("na")

startswith(x) Check beginning "Python".startswith("Py")

name = "Asha" score = 91 print(f"{name} scored {score} marks.") print("Pi: {:.2f}".format(3.14159))

10. Lists, Tuples, Sets and Dictionaries Lists

Lists are ordered, mutable collections that can contain values of different types.

numbers = [10, 20, 30] numbers.append(40) numbers.insert(1, 15) numbers.remove(20) last = numbers.pop() print(numbers, last)

 Indexing: values[0]

 Slicing: values[1:3]

 Length: len(values)

 Sort a list in place: values.sort()

 Create a sorted copy: sorted(values)

Tuples

Tuples are ordered collections that cannot be changed after creation.

point = (3, 5) x, y = point single_item = (7,) Sets

Sets store unique hashable values and are useful for removing duplicates and performing set

operations.

a = {1, 2, 3} b = {3, 4, 5} print(a | b) # union print(a & b) # intersection print(a - b) # difference unique = set([1, 1, 2, 3])

Use set() for an empty set; {} creates an empty dictionary.

Dictionaries

Dictionaries map keys to values. Keys are commonly strings or numbers.

student = {"name": "Asha", "age": 16} print(student["name"]) student["grade"] = 11 print(student.get("city", "Not provided")) for key, value in student.items(): print(key, value)

Use get() when a key may be missing. Direct indexing with a missing key raises KeyError.

11. Functions

A function is a reusable block of code. Define it with def and use return to send a result back to

the caller.

def greet(name): return f"Hello, {name}!" print(greet("Sita")) Parameters, defaults and keyword arguments def area(length, width=1): return length * width print(area(5, 3)) print(area(length=5, width=3)) print(area(5))

Mode Meaning

r Read; file should exist

w Write; creates or overwrites

a Append; creates if needed

x Create new file; fail if it exists

b Binary mode modifier, such as rb

+ Read/write mode modifier

Paths and JSON from pathlib import Path path = Path("data") / "example.txt" print(path.exists()) import json data = {"name": "Asha", "score": 90} text_data = json.dumps(data) restored = json.loads(text_data)

Use pathlib for portable path handling. CSV is useful for tables, while JSON stores structured data.

Be careful with files from unknown sources.

14. Exceptions and Error Handling

An exception interrupts normal program flow. try and except let the program handle expected

errors.

try: number = int(input("Enter a whole number: ")) print(100 / number) except ValueError: print("Please enter a valid integer.") except ZeroDivisionError: print("The number must not be zero.") else: print("Calculation completed.") finally: print("This part always runs.")

 try: code that may raise an exception.

 except: handles a matching exception.

 else: runs if no exception occurred in try.

 finally: runs whether or not an exception occurred.

 raise: deliberately raises an exception.

Catch specific exceptions rather than using a bare except, which can hide unexpected problems.

15. Object-Oriented Programming

Object-oriented programming (OOP) organises code around classes and objects. A class defines

data and behaviour; an object is an instance of a class.

class Student: def init(self, name, marks): self.name = name self.marks = marks def introduce(self): return f"I am {self.name} and I scored {self.marks}." student = Student("Asha", 92) print(student.introduce()) Core concepts

 Class: a blueprint for objects.

 Object: an instance of a class.

 Attribute: data associated with an object or class.

 Method: a function defined in a class.

 Encapsulation: grouping data and behaviour behind a clear interface.

 Inheritance: a class can extend another class.

 Polymorphism: different types can provide compatible behaviour through the same interface.

 Composition: building a class using objects of other classes.

Inheritance example class Animal: def speak(self): return "Some sound" class Dog(Animal): def speak(self): return "Woof" pet = Dog() print(pet.speak())

A leading underscore, such as _value, signals that a name is intended for internal use by

convention; it does not make the attribute truly private.

16. Comprehensions, Iterators and Generators Comprehensions squares = [n * n for n in range(1, 6)] evens = [n for n in range(10) if n % 2 == 0] lookup = {n: n*n for n in range(4)} unique_lengths = {len(word) for word in ["cat", "bird", "dog"]}

Comprehensions create collections concisely. Use them when the logic remains easy to read.

Iterators and generators

An iterable can be looped over, such as a list or string. An iterator supplies values one at a time. A

generator function uses yield to produce values gradually.

print(random.randint(1, 10)) print(random.choice(["red", "blue", "green"]))

The random module is useful for games and simulations, but not for security-sensitive tokens or

passwords.

Dates and times from datetime import date, datetime print(date.today()) print(datetime.now()) CSV and JSON import csv with open("people.csv", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: print(row) import json record = {"subject": "Python", "level": "beginner"} with open("record.json", "w", encoding="utf-8") as f: json.dump(record, f, indent=2)

19. Virtual Environments and pip

A package is reusable code that can be installed into a Python environment. pip is Python’s

standard package installer.

python -m venv .venv python -m pip install package-name python -m pip list

Activate the virtual environment using the command appropriate for your operating system and

shell. Virtual environments keep each project’s dependencies separate. Install packages only from

sources you trust.

20. Debugging, Testing and Good Practices

Error Meaning Possible cause

SyntaxError Code breaks grammar rules Missing colon after if

NameError Name is not defined Misspelled variable

TypeError Operation unsupported for

types

Incompatible operands

ValueError Value is unsuitable int("hello")

IndexError Sequence index out of range Invalid list index

KeyError Dictionary key missing Using a missing key

ZeroDivisionError Division by zero 10 / 0

FileNotFoundError File cannot be found Opening a missing file

Debugging tips

 Read the final line of a traceback, then inspect the mentioned line.

 Print intermediate values to see what the program is doing.

 Test one small part at a time.

 Check spelling, indentation, data types and boundary cases.

 Use a debugger or logging for more complex programs.

Testing with assert def add(a, b): return a + b assert add(2, 3) == 5 assert add(-1, 1) == 0 Good practices

 Use descriptive names and keep functions focused.

 Avoid repeating logic unnecessarily.

 Follow PEP 8 style guidance where practical.

 Do not store passwords or API keys directly in source code.

 Validate input and handle errors thoughtfully.

 Do not run code from unknown sources without understanding the risks.

21. Common Algorithms and Examples Even or odd number = int(input("Enter a number: ")) if number % 2 == 0: print("Even") else: print("Odd") Largest of three numbers a, b, c = 12, 7, 19 print("Largest:", max(a, b, c)) Sum from 1 to n n = int(input("Enter n: ")) total = sum(range(1, n + 1)) print(total) Factorial using a loop n = int(input("Enter a non-negative integer: ")) if n < 0: print("Factorial is not defined for negative integers.") else: result = 1 for number in range(2, n + 1): result *= number print(result)

41. What does yield do in a generator?

42. Mention five good programming practices.

Programming exercises

43. Ask for a name and print a greeting.

44. Ask for two numbers and print their sum, difference, product and quotient; handle division by

zero.

45. Print a multiplication table from 1 to 10.

46. Find the sum of all even numbers from 1 to 100.

47. Count the words in a sentence.

48. Create a list of five marks and calculate the average.

49. Create a student dictionary and print each key and value.

50. Write a function that returns the square of a number.

51. Read a text file and count its lines.

52. Create a Student class with a name attribute and a greeting method.

Quick revision sheet

Task Syntax / reminder

Display output print(value)

Read input input("Prompt: ")

Convert to integer int(value)

Conditions if / elif / else

Loop for item in iterable; while condition

Function def name(parameters): ... return value

List [item1, item2]

Tuple (item1, item2)

Set {item1, item2}

Dictionary {"key": "value"}

Handle errors try / except / else / finally

Import module import module_name

Open file safely with open(path, mode, encoding="utf-8") as

file:

Class class ClassName:

Virtual environment python -m venv .venv

Final Advice

Python is a broad language, and no single document can cover every library or professional

application. These notes provide a foundation in core Python. Build confidence by creating small

projects such as a calculator, quiz, to-do list, file organiser or simple data report.

Further learning: Official Python documentation — https://docs.python.org/3/