Docsity

Python Programming Notes for Beginners – Complete Guide with Examples, Practice Questions, Study notes of Computer science

Partial preview of the text

Download Python Programming Notes for Beginners – Complete Guide with Examples, Practice Questions and more Study notes Computer science in PDF only on Docsity!

PYTHON PROGRAMMING

NOTES FOR BEGINNERS

Concepts • Syntax • Examples • Practice • Mini Projects

A practical, beginner-friendly study guide

How to Use These Notes

  • Read one chapter at a time and type each code example into a Python editor.
  • Predict output before running code, then compare your prediction with the result.
  • Change values to see how the program behaves.
  • Try practice questions before checking the answer key.
  • Use the mini projects to combine several concepts.

Contents

1. 1. Getting Started with Python

2. 2. Variables and Data Types

3. 3. Input, Output, and Comments

4. 4. Operators

5. 5. Conditions

6. 6. Loops

7. 7. Strings

8. 8. Lists and Tuples

9. 9. Dictionaries and Sets

10. 10. Functions

11. 11. Modules, Errors, and Files

12. 12. Object-Oriented Programming

13. 13. Algorithms and Problem Solving

14. 14. Mini Projects

15. 15. Practice Set, Answers, and Glossary

Arithmetic

print(7 + 3) # 10 print(7 - 3) # 4 print(7 * 3) # 21 print(7 / 2) # 3. print(7 // 2) # 3 print(7 % 2) # 1 print(2 ** 3) # 8

+ adds, - subtracts, * multiplies, / divides, // performs floor division, % gives the remainder, and ** raises a power.

Comparison

== equal; != not equal; > greater; < less; >= greater than or equal; <= less than or equal. Comparisons return True or False.

Logical operators

and is true when both conditions are true; or is true when at least one is true; not reverses a Boolean value.

Assignment shortcuts

x += 1 means x = x + 1. Similar operators include -=, *=, and /=. Use parentheses to make complicated expressions clearer.

5. Conditions

if and else

marks = 72 if marks >= 33: print("Pass") else: print("Try again")

The colon is required. The indented lines form the block controlled by the condition.

if-elif-else

marks = 85 if marks >= 90: grade = "A+" elif marks >= 75: grade = "A" elif marks >= 60: grade = "B" else: grade = "C" print(grade)

Conditions are checked from top to bottom. Put higher thresholds first when ranges overlap.

Common mistakes

Remember the colon, use consistent indentation, and use == to compare values. A single = assigns a value.

6. Loops

for loop and range()

for number in range(1, 6): print(number)

range(1, 6) produces 1, 2, 3, 4, 5. The stop value is excluded. range(5) produces 0 through 4.

while loop

count = 1 while count <= 5: print(count) count += 1

A while loop repeats while its condition is true. Update the relevant variable so the loop can finish.

break and continue

for n in range(1, 8): if n == 5: break print(n)

break exits the loop. continue skips the rest of the current iteration. The example prints 1, 2, 3, and 4.

Avoid infinite loops

An infinite loop can occur if a while-loop condition never becomes false. Test loops with small examples and check how their

variables change.

7. Strings

Indexing and slicing

word = "PYTHON" print(word[0]) # P print(word[-1]) # N print(word[1:4]) # YTH

Indexes start at zero. In a slice, the start is included and the stop is excluded.

Useful methods

message = " hello Python " print(message.strip()) print(message.upper()) print(message.lower()) print(message.replace("Python", "coding"))

Common methods include strip(), upper(), lower(), replace(), and split(). They return results rather than changing the original

string.

f-strings

name = "Asha" marks = 91 print(f"{name} scored {marks} marks.")

An f-string begins with f and allows values or expressions inside curly braces.

Strings are immutable

A string cannot be modified in place. Create a new string or assign the result of a method if you want to keep the changed text.

8. Lists and Tuples

Lists

subjects = ["Maths", "Physics", "Chemistry"] subjects.append("English") print(subjects[0]) print(len(subjects))

Lists are ordered and mutable. append() adds an item; len() returns the number of items.

Useful list methods

append(x) adds an item; insert(i, x) inserts at a position; remove(x) removes a matching value; pop() removes and returns an

item; sort() sorts the list in place.

Loop through a list

subjects = ["Maths", "Physics", "Chemistry"] for subject in subjects: print(subject)

Tuples

point = (4, 7) print(point[0])

Tuples are ordered but immutable. Lists use square brackets; tuples usually use parentheses.

Copying lists

new_list = old_list.copy() makes a shallow copy. Writing new_list = old_list only creates another reference to the same list.

9. Dictionaries and Sets

Dictionaries

student = {"name": "Asha", "marks": 91} print(student["name"]) student["grade"] = "A"

A dictionary stores key-value pairs. Keys are unique.

Safe lookup and looping

Common errors

SyntaxError: invalid syntax. NameError: a name is not defined. TypeError: an operation is used with an incompatible type.

IndexError: a sequence index is out of range. ZeroDivisionError: division by zero.

Exception handling

try: number = int(input("Enter a whole number: ")) print(100 / number) except ValueError: print("Please enter a valid whole number.") except ZeroDivisionError: print("Number must not be zero.")

Use try-except to handle expected runtime problems without abruptly stopping the program.

Read a file

with open("notes.txt", "r", encoding="utf-8") as file: content = file.read() print(content)

The with statement closes the file automatically. Common modes: r read, w write/replace, a append, x create a new file.

Write a file

with open("result.txt", "w", encoding="utf-8") as file: file.write("Practice makes progress.\n")

Be careful: write mode replaces existing content.

12. Object-Oriented Programming

Class and object

class Student: def init(self, name, marks): self.name = name self.marks = marks

def introduce(self): print(f"I am {self.name}.")

student = Student("Asha", 91) student.introduce()

A class defines a type of object. An object is an instance of a class. init initialises the object, and self refers to the current

instance.

Encapsulation

Encapsulation keeps related data and behaviour together. A leading underscore in an attribute name is a convention that signals

it is intended for internal use.

Inheritance

Inheritance lets a class reuse or extend another class. Use it when there is a genuine 'is-a' relationship; simple functions may be

clearer for small tasks.

When to use OOP

OOP can be useful when a program models entities with both state and behaviour, such as students, books, or bank accounts.

13. Algorithms and Problem Solving

A useful method

1. Understand the task. 2. Identify inputs and outputs. 3. Break it into steps. 4. Write pseudocode. 5. Code the solution. 6. Test

normal and unusual cases. 7. Improve readability.

Find the largest number

numbers = [12, 27, 19] print(max(numbers))

Count vowels

text = "programming" vowels = "aeiou" count = 0

for character in text.lower(): if character in vowels: count += 1 print(count)

Linear search

items = [7, 4, 9, 2] target = 9 found = False for item in items: if item == target: found = True break print(found)

Linear search checks values one by one. Its running time grows roughly in proportion to the number of items.

Efficiency

Time complexity describes how running time grows as input grows. Space complexity describes how memory use grows.

Beginners should first prioritise correctness and clarity.

14. Mini Projects

Project A: Calculator

a = float(input("First number: ")) operator = input("Choose +, -, , or /: ") b = float(input("Second number: ")) if operator == "+": print(a + b) elif operator == "-": print(a - b) elif operator == "": print(a * b) elif operator == "/": if b != 0: print(a / b) else: print("Cannot divide by zero.") else: print("Unknown operator.")

Project B: Number guessing

import random secret = random.randint(1, 20) guess = None while guess != secret: guess = int(input("Guess a number from 1 to 20: ")) if guess < secret: print("Too low") elif guess > secret: print("Too high") print("Correct!")

Improvement challenge: count attempts and handle non-numeric input.

Project C: Marks summary

marks = [78, 85, 91, 67, 88] print("Subjects:", len(marks)) print("Total:", sum(marks)) print("Average:", sum(marks) / len(marks)) print("Highest:", max(marks))

Improvement challenge: take marks from the user and validate that they are in a sensible range.

15. Practice Set, Answers, and Glossary

Short questions

1. What does print() do? 2. Difference between = and ==? 3. Name four basic data types. 4. Why does indentation matter? 5.

What does range(1, 5) produce? 6. What is a function? 7. Difference between list and tuple? 8. What does a dictionary store? 9.

Why use try-except? 10. What is debugging?

Predict the output

A. print(3 ** 2) B. print("PYTHON"[1:4]) C. for n in range(3):