0% found this document useful (0 votes)
61 views17 pages

Python Basic To Advanced

Uploaded by

ThE CrOXon
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)
61 views17 pages

Python Basic To Advanced

Uploaded by

ThE CrOXon
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
You are on page 1/ 17

Python Basic to Advanced with Practice Exercises

Python Basic to Advanced

2025-09-26

1
Python Basic to Advanced with Practice Exercises

Contents

1 Introduction to Python 3

1.1 Python Installation and Environment Setup . . . . . . . . . . . . . . . 3

1.2 Running Python Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Basic Syntax and Data Types . . . . . . . . . . . . . . . . . . . . . . . . 4

1.4 Practice Exercise 1: Hello Python . . . . . . . . . . . . . . . . . . . . . . 4

2 Control Flow 5

2.1 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.3 Practice Exercise 2: Even or Odd . . . . . . . . . . . . . . . . . . . . . . 5

3 Functions and Modules 6

3.1 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

3.2 Modules and Importing . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

3.3 Practice Exercise 3: Factorial Function . . . . . . . . . . . . . . . . . . 7

4 Data Structures 7

4.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4.2 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4.3 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4.4 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4.5 Practice Exercise 4: Frequency Counter . . . . . . . . . . . . . . . . . . 8

2
Python Basic to Advanced with Practice Exercises

5 File Handling 9

5.1 Opening Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

5.2 Reading and Writing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

5.3 Practice Exercise 5: File Word Count . . . . . . . . . . . . . . . . . . . 10

6 Object-Oriented Programming 10

6.1 Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

6.2 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

6.3 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

6.4 Practice Exercise 6: Bank Account . . . . . . . . . . . . . . . . . . . . . 11

7 Advanced Topics 12

7.1 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

7.2 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

7.3 List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

7.4 Context Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

7.5 Practice Exercise 7: Fibonacci Generator . . . . . . . . . . . . . . . . . 13

8 Practice Projects 13

8.1 Project 1: To-Do List App . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

8.2 Project 2: Simple Calculator . . . . . . . . . . . . . . . . . . . . . . . . . 14

8.3 Project 3: Contact Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

8.4 Project 4: Web Scraper . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3
Python Basic to Advanced with Practice Exercises

9 Summary and Recommendations 14

4
Python Basic to Advanced with Practice Exercises

1 Introduction to Python

Python is a versatile and widely-used programming language known for its


simplicity and readability. Originating in the late 1980s and introduced by Guido
van Rossum in 1991, Python emphasizes code clarity and developer productivity.
Its dynamic typing and high-level data structures make it a favorite for beginners
and professionals alike.

This chapter covers essential concepts to get started with Python program-
ming. We will explore Python’s installation, running scripts, basic syntax, and
fundamental data types. By mastering these building blocks, you will be well-
prepared to advance into more complex programming topics.

1.1 Python Installation and Environment Setup

Installing Python is straightforward, with packages available for all major


operating systems. The official website https://www.python.org/downloads/ pro-
vides the latest stable releases. For development, integrated development envi-
ronments (IDEs) like PyCharm, VS Code, or Jupyter Notebook enhance produc-
tivity.

1.2 Running Python Code

You can execute Python code in several ways:

• Interactive mode using the Python shell.

• Script mode by writing code in .py files and running them via command
line.

5
Python Basic to Advanced with Practice Exercises

• Using Jupyter Notebooks for an interactive environment combining code,


text, and multimedia.

1.3 Basic Syntax and Data Types

Python uses indentation to define code blocks, which enforces readability.


Fundamental data types include:

• Integers and floats for numeric operations.

• Strings for text manipulation.

• Booleans representing True or False.

• Lists, tuples, sets, and dictionaries for collections.

Understanding these types is critical as they form the core of Python pro-
gramming.

1.4 Practice Exercise 1: Hello Python

Write a Python program that prints ”Hello, Python!” to the screen.

Solution:

print(”Hello, Python!”)

6
Python Basic to Advanced with Practice Exercises

2 Control Flow

Control flow statements steer the execution path of a program based on con-
ditions or loops. Mastery of control flow enables you to write complex, respon-
sive code.

2.1 Conditional Statements

Python uses if, elif, and else to perform decisions:

if condition:
# code if true
elif another_condition:
# code if another condition is true
else:
# code if none above is true

2.2 Loops

Loops help repeat code blocks efficiently.

• for loops iterate over sequences.

• while loops run as long as a condition holds.

2.3 Practice Exercise 2: Even or Odd

Write a program that asks the user to input a number and prints whether it
is even or odd.

7
Python Basic to Advanced with Practice Exercises

Sample solution:

num = int(input(”Enter a number: ”))


if num % 2 == 0:
print(”Even”)
else:
print(”Odd”)

3 Functions and Modules

Functions are reusable blocks of code that perform a specific task. Modules
organize related functions and variables, enabling modular programming.

3.1 Defining Functions

Use the def keyword:

def greet(name):
return ”Hello, ” + name

Functions improve code readability and maintainability.

3.2 Modules and Importing

Python’s rich standard library provides numerous modules. You can import
built-in or custom modules:

8
Python Basic to Advanced with Practice Exercises

import math
print(math.sqrt(16))

3.3 Practice Exercise 3: Factorial Function

Write a function that returns the factorial of a given number using recursion.

Solution:

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)

4 Data Structures

Python provides versatile data structures to store and manipulate collections


efficiently.

4.1 Lists

Mutable ordered collections:

• Creation: lst = [1, 2, 3]

• Methods: append(), pop(), sort(), etc.

9
Python Basic to Advanced with Practice Exercises

4.2 Tuples

Immutable ordered collections:

• Created with parentheses: t = (1, 2, 3)

• Used for fixed data groups.

4.3 Dictionaries

Key-value mappings:

• Created with braces: d = { ”key”: ”value” }

• Efficient for lookups.

4.4 Sets

Unordered collections of unique elements:

• Created with set() or braces.

• Useful for membership tests and eliminating duplicates.

4.5 Practice Exercise 4: Frequency Counter

Create a program that counts the frequency of each character in a given


string using a dictionary.

Example solution:

10
Python Basic to Advanced with Practice Exercises

def char_frequency(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
return freq

5 File Handling

Reading from and writing to files is essential for data persistence.

5.1 Opening Files

Use the open() function with modes such as:

• ’r’ –read (default)

• ’w’ –write (overwrites)

• ’a’ –append

• ’b’ –binary mode

5.2 Reading and Writing

• read(), readline(), readlines() for reading.

• write(), writelines() for writing.

Always close files explicitly or use with statement for automatic closing.

11
Python Basic to Advanced with Practice Exercises

5.3 Practice Exercise 5: File Word Count

Write a program that reads a text file and counts the total number of words.

Example:

def count_words(filename):
with open(filename, ’r’) as f:
text = f.read()
words = text.split()
return len(words)

6 Object-Oriented Programming

OOP enables modeling real-world entities with classes and objects.

6.1 Classes and Objects

A class defines a blueprint; an object is an instance.

class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + ” says woof!”)

12
Python Basic to Advanced with Practice Exercises

6.2 Inheritance

Classes can inherit properties and methods from parent classes.

6.3 Encapsulation

Controlling access to data using private and public members.

6.4 Practice Exercise 6: Bank Account

Implement a BankAccount class with deposit, withdraw, and balance in-


quiry methods.

Sample solution:

class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance

def deposit(self, amount):


self.balance += amount

def withdraw(self, amount):


if amount <= self.balance:
self.balance -= amount
else:
print(”Insufficient funds”)

13
Python Basic to Advanced with Practice Exercises

def get_balance(self):
return self.balance

7 Advanced Topics

Explore more sophisticated Python features that increase power and flexi-
bility.

7.1 Decorators

Higher-order functions modifying behavior of other functions:

def decorator_func(func):
def wrapper():
print(”Before call”)
func()
print(”After call”)
return wrapper

7.2 Generators

Functions that yield sequences lazily, improving memory efficiency.

7.3 List Comprehensions

Concise syntax for generating lists:

14
Python Basic to Advanced with Practice Exercises

squares = [x**2 for x in range(10)]

7.4 Context Managers

Using with to manage resources reliably.

7.5 Practice Exercise 7: Fibonacci Generator

Implement a generator to produce Fibonacci numbers up to a limit.

Solution:

def fib_generator(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b

8 Practice Projects

Applying knowledge to real-world projects reinforces learning deeply.

8.1 Project 1: To-Do List App

Create a command-line application that lets users add, remove, and display
tasks saved persistently in a file.

15
Python Basic to Advanced with Practice Exercises

8.2 Project 2: Simple Calculator

Develop a program performing basic arithmetic operations with input vali-


dation.

8.3 Project 3: Contact Book

Manage contacts with add, search, and delete functionalities using dictionar-
ies.

8.4 Project 4: Web Scraper

Using requests and BeautifulSoup libraries to extract information from


web pages (installation needed).

9 Summary and Recommendations

This document traversed Python’s journey from basics to advanced topics


enriched with exercises and projects. To master Python, continuous hands-on
practice is essential. Leveraging community resources and documentation ac-
celerates growth.

Focus on writing clean, readable code, and explore Python’


s expansive ecosys-
tem. Remember, every expert was once a beginner; persistence and curiosity
forge mastery.

16
Python Basic to Advanced with Practice Exercises

References

• Python Official Documentation: https://docs.python.org/3/

• Automate the Boring Stuff with Python, Al Sweigart

• Fluent Python, Luciano Ramalho

• Real Python Tutorials: https://realpython.com/

17

You might also like