Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 01

Python Introduction

7 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Python is a high-level, interpreted, general-purpose programming language.

It is famous for clean syntax that reads almost like English.

This chapter explains what Python is, its features, advantages, history, applications, your first Hello World program and how to install Python.

Python is the first language in many colleges and the most requested skill in data science, automation and AI.

A strong start makes every later chapter easy.

Web backends, data analysis, machine learning, automation scripts, testing tools, scientific computing and teaching.

1

What is Python

Python is a high-level, interpreted, dynamically typed, object-oriented and general-purpose programming language created by Guido van Rossum. Python source code is first compiled to bytecode and then executed by the Python Virtual Machine (PVM).

In short: Python is a language you use to tell the computer what to do. Its rules are simple. The code is short and easy to read.

Python code → Interpreter → Output

Think about it

Programmers needed a language that was quick to write and easy to read. Python removes boilerplate such as semicolons, braces and type declarations, so you focus on the problem. A task that needs 10 lines in some languages often needs 3 lines in Python. Instagram, YouTube backends, Netflix tools and NASA scripts use Python.

Python is "high-level" because you do not manage memory or hardware by hand.

It is "interpreted" because you can run code line by line in the REPL or run a whole .

py file without a separate compile step by you.

Internally CPython (the standard implementation) compiles your code to bytecode (.

pyc files in __pycache__) and the PVM runs that bytecode.

Python is "dynamically typed": a variable gets its type from the value it holds, so you never write int x.

It supports procedural, object-oriented and functional styles.

Other implementations exist: PyPy (fast JIT), Jython (JVM) and IronPython (.

NET).

Key points

  • Interpreter: Program that reads and runs Python code.
  • Bytecode: Low-level instructions produced after compiling source code.
  • PVM: Python Virtual Machine that executes bytecode.
  • CPython: The default Python implementation written in C.
  • Dynamic typing: Types are checked at run time, not declared in advance.
  • Python files end with the .py extension.
  • Python is case-sensitive. name and Name are different.
  • Python 3 is the current version. Python 2 is no longer supported.
  • Indentation (spaces) defines blocks, not curly braces.

Example

Code
first look at Python:
# A tiny Python program: total price with tax
price = 250
tax_rate = 0.18
total = price + price * tax_rate
print("Total payable:", total)

# Python decides the type from the value
x = 10          # int
x = "ten"       # now str, no error
print(type(x))  # <class 'str'>
2

Python Features

Python features are the built-in qualities that make the language simple, portable and powerful: easy syntax, interpreted execution, dynamic typing, object orientation, a huge standard library, portability, extensibility and automatic memory management.

In short: Features are the strong points of Python. They make coding faster and less painful.

Think about it

These features explain why Python teams ship products faster than in many other languages. A student can parse a CSV file with the built-in csv module in five lines, without installing anything.

1) Easy to learn: few keywords, clean syntax.

2) Interpreted: run code instantly, great for testing ideas.

3) Dynamically typed: no type declarations.

4) Object-oriented: classes, inheritance, polymorphism.

Everything in Python is an object.

5) Free and open source: anyone can download, use and improve it.

6) Portable: the same code runs on Windows, Linux and macOS.

7) Extensible and embeddable: you can write parts in C/C++ or embed Python inside other applications.

8) Large standard library ("batteries included"): math, os, json, datetime, random, csv and more.

9) Automatic memory management: reference counting plus a garbage collector.

10) Supports multiple paradigms: procedural, object-oriented and functional.

Key points

  • Portable: Same program runs on different operating systems.
  • Open source: Source code is public and free to use.
  • Standard library: Ready-made modules shipped with Python.
  • Garbage collector: Frees memory of objects that are no longer used.
  • "Everything is an object" means numbers, strings, functions and classes are all objects.
  • Dynamic typing gives flexibility but type mistakes show up only when the code runs.
  • Python is slower than C for heavy loops, but libraries like NumPy use C inside.

Example

Code
library support and objects:
import math, json, datetime

print(math.sqrt(81))                         # 9.0  (standard library)
print(json.dumps({"lang": "Python"}))        # {"lang": "Python"}
print(datetime.date(2024, 1, 1).year)        # 2024

# everything is an object
print((5).bit_length())        # 3
print("abc".upper())           # ABC
print(len.__name__)            # len  (functions are objects too)
3

Advantages of Python

The advantages of Python are the practical benefits a developer gets by choosing it: shorter code, faster development, wide community support, rich libraries, cross-platform use and high demand in the job market.

In short: Python saves time. You write less code, find help easily and get jobs in many fields.

Think about it

Knowing both the advantages and limitations helps you pick the right tool and answer interview questions honestly. A company automates daily report generation with a 30-line Python script instead of a manual two-hour task.

Advantages: (1) Readable syntax reduces bugs and training time.

(2) Rapid prototyping: an idea becomes a working script in minutes.

(3) Huge ecosystem: PyPI hosts hundreds of thousands of packages such as NumPy, pandas, Django, Flask, TensorFlow and PyTorch.

(4) Strong community: tutorials, forums and open-source help.

(5) Cross-platform and free.

(6) Great integration: calls C libraries, talks to databases and REST APIs.

(7) Good for automation of boring jobs like renaming files or sending emails.

(8) High demand in data science, AI and backend roles.

Limitations to remember: slower raw speed than compiled languages, higher memory use, weak native mobile development, and the Global Interpreter Lock (GIL) limits CPU-bound threads in CPython.

Key points

  • PyPI: Python Package Index, the online store of Python packages.
  • pip: Tool that installs packages from PyPI.
  • Prototype: Quick first version of a program to test an idea.
  • GIL: Lock in CPython that lets one thread run Python bytecode at a time.
  • Python is not the best for mobile apps or very low-level system code.
  • For speed use libraries (NumPy), multiprocessing, or write hot parts in C/Cython.

Example

Code
short code, big result:
# Same task, very little code: count word frequency
text = "to be or not to be"
freq = {}
for w in text.split():
    freq[w] = freq.get(w, 0) + 1
print(freq)   # {'to': 2, 'be': 2, 'or': 1, 'not': 1}

# or use the library
from collections import Counter
print(Counter(text.split()))
4

History of Python

Python was created by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. He started it in December 1989, released version 0.9.0 in February 1991, Python 2.0 in 2000 and Python 3.0 in December 2008.

In short: One programmer, Guido van Rossum, built Python as a hobby project. It grew into one of the most used languages in the world.

Python timeline (simple view)

Think about it

Interviewers often ask who created Python, when, and why Python 3 is not compatible with Python 2. Old scripts that use print "hello" (Python 2) fail in Python 3 and must be updated to print("hello").

Timeline: 1989 — development starts as a successor to the ABC language.

1991 — first public release (0.9.

0) with classes, exceptions and core data types.

1994 — Python 1.0 adds functional tools such as lambda, map, filter.

2000 — Python 2.0 adds list comprehensions and garbage collection.

2008 — Python 3.0 cleans up the language and is not fully backward compatible (print became a function, true division with /, Unicode strings by default).

2020 — Python 2 reached end of life (1 January 2020).

Today the Python Software Foundation (PSF) manages the language and a new minor version arrives roughly every year.

The name comes from the British comedy group Monty Python, not from the snake.

Key points

  • Guido van Rossum: Creator of Python, once called the BDFL.
  • BDFL: Benevolent Dictator For Life, a title given to Guido for guiding Python.
  • PSF: Python Software Foundation, the non-profit that owns Python rights.
  • PEP: Python Enhancement Proposal, a design document for changes.
  • Python is named after Monty Python's Flying Circus.
  • PEP 8 is the official style guide. PEP 20 is "The Zen of Python".
  • Python 2 and Python 3 code are not fully compatible.

Example

Code
check the Python version in code:
import sys
print(sys.version)               # full version text
print(sys.version_info.major)    # 3
print(sys.version_info >= (3, 8))  # True on modern installs

import this   # prints The Zen of Python (try it in the REPL)
5

Python Applications

Python applications are the real-world areas where Python is used: web development, data science, machine learning, automation, scientific computing, game prototypes, cyber security, desktop tools, embedded scripting and education.

In short: Python is used almost everywhere: websites, AI, data, automation and learning to code.

Where Python is used

Think about it

Applications show where your Python skill turns into a career path. Spotify uses Python for data analysis, Dropbox started as a Python desktop client, and ISRO/NASA teams use Python for data processing.

Web: Django, Flask, FastAPI.

Data science and analytics: NumPy, pandas, Matplotlib.

Machine learning and AI: scikit-learn, TensorFlow, PyTorch.

Automation and scripting: files, Excel, emails, web scraping with requests and BeautifulSoup.

Testing: pytest, Selenium.

DevOps and cloud: Ansible, AWS boto3 scripts.

Scientific work: SciPy, Biopython, astronomy software.

Games: Pygame for small games.

Desktop GUI: Tkinter, PyQt.

Cyber security: network tools and penetration testing scripts.

Education: Python is the most common first language.

Each area uses third-party packages installed with pip.

Key points

  • Django: Full-featured Python web framework.
  • NumPy: Library for fast numeric arrays.
  • pandas: Library for tables and data analysis.
  • Automation: Letting a script do repetitive work.
  • Python is mostly used in data science, AI, web backend and automation.
  • Each area depends on libraries. Learn core Python first.

Example

Code
scripting and data in two lines:
# Automation example: rename file names to lowercase
files = ["Report.TXT", "Notes.PDF", "DATA.csv"]
renamed = [f.lower() for f in files]
print(renamed)   # ['report.txt', 'notes.pdf', 'data.csv']

# Data example: average of marks
marks = [72, 85, 90, 64]
print("Average:", sum(marks) / len(marks))   # 77.75
6

Hello World Program in Python

The Hello World program is the first program that prints the message "Hello, World!" on the screen. In Python it is written with a single call to the built-in print() function.

In short: print("Hello, World!") shows text on screen. That is your first program.

Think about it

Hello World checks that your installation works and teaches the save-and-run cycle. Every developer runs a Hello World first when learning a new language or tool.

Steps

(1) Open any editor (IDLE, VS Code, PyCharm or Notepad).

(2) Type print("Hello, World!

").

(3) Save the file as hello.

py.

(4) Open a terminal in that folder.

(5) Run python hello.

py (or py hello.

py on Windows, python3 hello.

py on Linux/macOS).

print() accepts several values separated by commas, adds a space between them (sep) and a new line at the end (end).

Strings can use single or double quotes.

In the interactive REPL (>>>) you can type a line and see the result immediately.

A missing bracket or quote gives SyntaxError.

In Python 2 print was a statement; in Python 3 it is a function and brackets are required.

Key points

  • print(): Built-in function that writes values to the screen.
  • sep: Text placed between printed values (default a space).
  • end: Text placed after printing (default a new line).
  • REPL: Read-Eval-Print Loop, the interactive Python prompt.
  • Use print("text") with brackets in Python 3.
  • Run a file with python filename.py.
  • Strings must start and end with the same kind of quote.

Example

Code
Hello World and print options:
# hello.py
print("Hello, World!")

print("Hello", "Python", 3)              # Hello Python 3
print("A", "B", "C", sep="-")            # A-B-C
print("loading", end="...")
print("done")                            # loading...done
print('She said "hi"')                   # quotes inside quotes
print("Line1\nLine2")                    # \n makes a new line
7

How to Install Python

Installing Python means downloading the official installer from python.org, running it, adding Python to the system PATH and verifying the setup with python --version. pip is installed along with it.

In short: Download Python, tick "Add Python to PATH", click install, then check the version in a terminal.

Think about it

A correct install avoids the most common beginner error: "python is not recognized as a command". Teams use one virtual environment per project so package versions never clash.

Windows: (1) Go to python.

org/downloads and download the latest Python 3 installer.

(2) Run it and tick "Add python.

exe to PATH".

(3) Click Install Now.

(4) Open Command Prompt and type python --version.

macOS: use the python.

org installer or Homebrew (brew install python).

Linux: Python is often pre-installed; otherwise use the package manager, for example sudo apt install python3 python3-pip.

After installing, check pip with pip --version.

Create a virtual environment for each project: python -m venv venv, activate it (venv\Scripts\activate on Windows, source venv/bin/activate on Linux/macOS) and install packages with pip install package-name.

You can also use Anaconda for data science work.

If the command is not found, PATH was not set; re-run the installer or add the folder to PATH.

Key points

  • PATH: List of folders where the OS looks for commands.
  • pip: Package installer for Python.
  • venv: Built-in module to create an isolated project environment.
  • IDLE: Simple editor that comes with Python.
  • Tick "Add Python to PATH" on Windows.
  • Check with python --version and pip --version.
  • Use a virtual environment for every project.

Example

Code
verify the setup:
# Run these in a terminal (not inside Python):
#   python --version
#   pip --version
#   python -m venv venv
#   pip install requests

# Inside Python you can check the install:
import sys, platform
print(sys.executable)          # path of the python program in use
print(platform.python_version())

# Is pip usable from Python?
import importlib.util
print(importlib.util.find_spec("pip") is not None)   # True

Solved examples

Example 01 · Basic

Write a program that prints your name and course on two lines.

Given Data:
    Required To Find:

    Two-line output using print()

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Call print() once for the name
    Step 2: Call print() again for the course
    Step 3: Each print() ends with a new line
    Final Answer: print("Name: Asha") print("Course: Python")

    Approach note: One print() call equals one output line unless you change end.

    Example 02 · Basic

    Print 10, 20, 30 on one line separated by a comma and a space.

    Given Data:
      Required To Find:

      Output: 10, 20, 30

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Pass the three numbers to print()
      Step 2: Set sep=", " to change the separator
      Final Answer: print(10, 20, 30, sep=", ") # 10, 20, 30

      Approach note: Use sep for the gap between values and end for what comes after.

      Example 03 · Intermediate

      Write a program that shows the installed Python major version and warns if it is below 3.

      Given Data:
        Required To Find:

        Version check message

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Import sys
        Step 2: Read sys.version_info.major
        Step 3: Compare with 3 using if/else
        Final Answer: import sys if sys.version_info.major >= 3: print("Python 3 detected") else: print("Please upgrade to Python 3")

        Approach note: Compare tuples like sys.version_info >= (3, 8) for minor versions.

        Example 04 · Basic

        Write a one-liner that prints Hello followed by a name stored in variable name = "Riya".

        Given Data:
          Required To Find:

          Single print with variable

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Store the name in a variable
          Step 2: Pass a string and the variable to print()
          Step 3: Default sep is a space so Hello and Riya appear separated
          Final Answer: name = "Riya" print("Hello", name) # Hello Riya

          Approach note: print() accepts any mix of strings and variables.

          Real-world applications

          Python

          Using Python Introduction in real projects

          Web backends, data analysis, machine learning, automation scripts, testing tools, scientific computing and teaching.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Python is named after the snake.

          Why this is wrong: The creator named it after the comedy show Monty Python's Flying Circus.

          ✅ Verified Truth: The snake logo came later.

          ⚠️ Exam Tip: A common one-line viva question.

          ❌ Myth: Python is only interpreted and never compiled.

          Why this is wrong: CPython compiles source code to bytecode before the PVM runs it.

          ✅ Verified Truth: Python is compiled to bytecode and then interpreted.

          ⚠️ Exam Tip: Say "compiled to bytecode, executed by the PVM".

          ❌ Myth: Python 2 code runs unchanged on Python 3.

          Why this is wrong: Python 3 changed print, integer division, strings and more.

          ✅ Verified Truth: Python 3 is not fully backward compatible with Python 2.

          ⚠️ Exam Tip: Mention print() and the / operator as examples.

          ❌ Myth: Python is too slow to be useful.

          Why this is wrong: Heavy work is done by C-based libraries such as NumPy.

          ✅ Verified Truth: Python is slower for raw loops but fast enough for most tasks.

          ⚠️ Exam Tip: State the trade-off: development speed vs run speed.

          Revision notes

          Python is a high-level, interpreted, general-purpose programming language. It is famous for clean syntax that reads almost like English. This chapter explains what Python is, its features, advantages, history, applications, your first Hello World program and how to install Python.

          High-Yield Quick Revision Points

          1. Python = high-level, interpreted, dynamically typed, object-oriented language by Guido van Rossum.
          2. Development began in 1989; first release 1991; Python 3.0 in 2008; Python 2 ended 2020.
          3. Source → bytecode → PVM executes it.
          4. Features: simple, portable, open source, huge library, OOP, automatic memory management.
          5. Advantages: short code, fast development, big community, many fields; limitation: slower than C.
          6. Applications: web, data science, AI/ML, automation, testing, scientific computing.
          7. Hello World: print("Hello, World!"); run with python hello.py.
          8. Install from python.org, tick Add to PATH, verify with python --version and pip --version.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Who created Python?

          Question 2 · MCQ (Interview / semester)

          Which extension is used for Python source files?

          Question 3 · MCQ (Interview / semester)

          What is the output of print("Hi", "there", sep="-")?

          Question 4 · MCQ (Interview / semester)

          Python source code is first converted to:

          Question 5 · MCQ (Interview / semester)

          Which is NOT a feature of Python?

          Question 6 · MCQ (Interview / semester)

          Python 2 officially reached end of life in: