Programming Languages / Python

Python Introduction - Getting Started with Python Programming

Complete introduction to Python programming. Learn what Python is, why it's popular, how to install it, write your first program, and understand Python syntax basics.

Beginner
⏱️ 20 minutes

Introduction

What You'll Learn

  • What Python is and why it's one of the most popular programming languages
  • Real-world applications of Python (Web, Data Science, AI, Automation)
  • How to install Python on Windows, Mac, and Linux
  • Setting up Python development environment (VS Code, PyCharm, Jupyter)
  • Writing and running your first Python program
  • Understanding Python syntax, indentation, and code structure
  • Python keywords, identifiers, and naming conventions
  • Comments and code documentation best practices

Why This Topic is Important

Python is consistently ranked as one of the top programming languages worldwide. Its simple syntax makes it perfect for beginners, while its powerful libraries make it essential for professionals in web development, data science, artificial intelligence, automation, and more. Learning Python opens doors to numerous career opportunities.

Real-World Applications

  • Web Development: Django, Flask frameworks for building websites
  • Data Science: NumPy, Pandas for data analysis and visualization
  • Machine Learning & AI: TensorFlow, PyTorch for building intelligent systems
  • Automation: Scripting tasks, web scraping, file processing
  • Game Development: Pygame for creating games
  • Desktop Applications: Tkinter, PyQt for GUI applications
  • API Development: Building RESTful APIs and microservices
  • DevOps: Automation scripts, infrastructure management

Learning Objectives

  • Understand what Python is and its advantages
  • Install Python on your operating system
  • Set up a Python development environment
  • Write and execute your first Python program
  • Master Python syntax and indentation rules
  • Use comments effectively in code
  • Understand Python keywords and identifiers
  • Follow Python coding best practices

What is Python?

Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. The name "Python" comes from the British comedy group Monty Python, not the snake!

Python is designed with code readability in mind. Its syntax is clean and intuitive, making it one of the easiest languages to learn. Python emphasizes simplicity and allows programmers to express concepts in fewer lines of code compared to languages like C++ or Java.

  • **Interpreted Language**: Code is executed line by line, no compilation needed
  • **Dynamically Typed**: Variable types are determined at runtime
  • **Object-Oriented**: Supports OOP principles (classes, inheritance, polymorphism)
  • **Cross-Platform**: Runs on Windows, macOS, Linux, and more
  • **Extensive Libraries**: Huge standard library and third-party packages
  • **Community Support**: Large, active community with excellent documentation

💡 Tip

Python 3 is the current version and what you should learn. Python 2 reached end-of-life in 2020. Always use Python 3.x for new projects.

Why Learn Python?

Python's popularity has skyrocketed in recent years. Here's why it's an excellent choice for both beginners and professionals:

📊 Diagram:

Python Advantages Diagram: A central circle labeled "Python" with 6 branches: 1) Easy to Learn - Simple syntax, 2) Versatile - Web, Data, AI, 3) High Demand - Top job market, 4) Great Libraries - Rich ecosystem, 5) Community - Large support, 6) Fast Development - Rapid prototyping. Each branch has an icon and brief description.

Alt text: Python advantages and benefits

  • **Beginner-Friendly**: Simple syntax, easy to read and write
  • **Versatile**: Used in web development, data science, AI, automation, and more
  • **High Demand**: Consistently ranked in top 3 most in-demand programming languages
  • **Excellent Libraries**: NumPy, Pandas, Django, Flask, TensorFlow, and thousands more
  • **Great Community**: Active community, extensive documentation, many tutorials
  • **Fast Development**: Write code faster than many other languages
  • **Career Opportunities**: High-paying jobs in data science, AI, web development

Installing Python

Windows Installation

  • Visit python.org/downloads
  • Download the latest Python 3.x version (e.g., Python 3.11 or 3.12)
  • Run the installer executable
  • **IMPORTANT**: Check the box "Add Python to PATH"
  • Click "Install Now"
  • Verify installation: Open Command Prompt and type `python --version`
BASH
# Verify Python installation
python --version
# Should display: Python 3.11.x or similar

# Check if pip is installed
pip --version
# Should display: pip 23.x.x

After installation, verify Python and pip (package installer) are working correctly.

macOS Installation

  • Python 3 is pre-installed on macOS, but it might be an older version
  • Download latest version from python.org/downloads
  • Or use Homebrew: `brew install python3`
  • Verify: Open Terminal and type `python3 --version`

Linux Installation

BASH
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip

# Fedora
sudo dnf install python3 python3-pip

# Verify
python3 --version
pip3 --version

Linux distributions usually have Python pre-installed. Use package manager to install or update.

Python IDE Options

An IDE (Integrated Development Environment) makes coding easier. Here are popular options:

  • **VS Code**: Free, lightweight, excellent Python extension
  • **PyCharm**: Professional IDE by JetBrains, free Community edition available
  • **Jupyter Notebook**: Great for data science, interactive coding
  • **IDLE**: Comes with Python, simple but functional
  • **Sublime Text**: Lightweight text editor with Python support
  • **Atom**: Free, customizable text editor

Best practice

For beginners, VS Code with the Python extension is highly recommended. It's free, easy to use, and has excellent features like syntax highlighting, debugging, and IntelliSense.

Your First Python Program: "Hello, World!"

Let's write the traditional first program that every programmer writes when learning a new language:

PYTHON
# My first Python program
print("Hello, World!")

# Save this as hello.py and run it

The simplest Python program. The `print()` function displays text on the screen. Save this in a file with `.py` extension.

Running Python Code

There are two ways to run Python code:

1. Interactive Mode (REPL)

BASH
# Open Python interactive mode
python
# or python3 on Mac/Linux

# You'll see: >>>
# Type your code directly
>>> print("Hello, World!")
Hello, World!
>>> exit()

Interactive mode lets you type and execute code line by line. Great for testing and learning.

2. Script Mode

BASH
# Create a file: hello.py
# Add: print("Hello, World!")

# Run from command line
python hello.py
# Output: Hello, World!

Script mode runs entire Python files. This is how you'll write most programs.

Python Syntax Basics

Indentation: Python's Unique Feature

Python uses indentation (whitespace) to define code blocks, unlike languages like C++ or Java that use curly braces `{}`.

PYTHON
# Correct indentation
if True:
    print("This is indented")
    print("This too")
print("This is not indented")

# Wrong indentation (will cause error)
if True:
print("This will cause IndentationError")

Indentation matters in Python! Use 4 spaces (or 1 tab) for each indentation level. Be consistent throughout your code.

⚠️ Warning

Never mix tabs and spaces for indentation. Choose one and stick with it. Most Python style guides recommend 4 spaces. Most editors can be configured to insert spaces when you press Tab.

Comments

PYTHON
# This is a single-line comment

# Comments explain what code does
print("Hello")  # Inline comment

"""
This is a multi-line comment
or docstring
It can span multiple lines
"""

# Multi-line comment using #
# This is another way
# to write multi-line comments

Comments help document your code. Single-line comments use `#`. Multi-line comments use triple quotes `"""` or multiple `#` lines.

Python Keywords

Keywords are reserved words in Python that have special meaning. You cannot use them as variable names.

PYTHON
# Some Python keywords
# if, else, elif, for, while, def, class, import, return, True, False, None, and, or, not, in, is, etc.

# This will cause an error:
# if = 5  # SyntaxError: invalid syntax

# Check all keywords
import keyword
print(keyword.kwlist)

Python has about 35 keywords. You cannot use them as variable names. Use `keyword.kwlist` to see all keywords.

Identifiers and Naming Rules

  • Can contain letters (a-z, A-Z), digits (0-9), and underscore (_)
  • Must start with a letter or underscore (not a digit)
  • Case-sensitive: `name` and `Name` are different
  • Cannot be a Python keyword
  • Use descriptive names: `user_age` not `ua`
PYTHON
# Valid identifiers
name = "Alice"
user_name = "bob123"
_age = 25
total_count = 100

# Invalid identifiers
# 2name = "Error"      # Cannot start with digit
# user-name = "Error"   # Cannot use hyphen
# class = "Error"       # Cannot use keyword

Follow Python naming conventions for valid identifiers. Use snake_case for variables and functions.

📊 Comparison:

Good vs Bad Variable Names: Left side "Good" shows: user_name, total_count, is_active, calculate_total. Right side "Bad" shows: un, tc, flag, calc. Green checkmarks on good names, red X on bad names.

Alt text: Python variable naming conventions

Python Code Structure Best Practices

  • Use 4 spaces for indentation (PEP 8 standard)
  • Maximum line length: 79 characters (PEP 8)
  • Use blank lines to separate logical sections
  • Import statements at the top
  • Use meaningful variable names
  • Add comments to explain complex logic
  • Follow PEP 8 style guide
PYTHON
# Good code structure
# Import statements
import math
import os

# Constants
PI = 3.14159
MAX_SIZE = 100

# Main code
def calculate_area(radius):
    """Calculate area of circle."""
    return PI * radius ** 2

# Program entry point
if __name__ == "__main__":
    result = calculate_area(5)
    print(f"Area: {result}")

Well-structured Python code follows conventions: imports first, constants, functions, then main code.

Best practice

Follow PEP 8 (Python Enhancement Proposal 8) - the official Python style guide. It makes your code more readable and professional. Tools like `autopep8` can automatically format your code to PEP 8 standards.

Practical Examples

Example 1: Hello World Program

print("Hello, World!")
print("Welcome to Python!")

The simplest Python program demonstrating the print() function.

Expected Output:

Hello, World! Welcome to Python!

Example 2: Multiple Print Statements

print("Python")
print("is")
print("awesome!")

Each print() statement outputs on a new line by default.

Expected Output:

Python is awesome!

Example 3: Print with Custom Separator

print("Python", "is", "awesome", sep="-")
print("Hello", "World", end="!")

Using sep and end parameters to customize print output.

Expected Output:

Python-is-awesome Hello World!

Example 4: Comments Example

# This program calculates the sum
# Author: Your Name
# Date: 2024

# Calculate sum
result = 10 + 20  # Adding two numbers
print(f"Sum: {result}")  # Display result

Demonstrating different types of comments in Python code.

Expected Output:

Sum: 30

Example 5: Proper Code Structure

# Import section
import math

# Constants
GRAVITY = 9.8

# Function definition
def calculate_force(mass):
    """Calculate force using F = ma."""
    return mass * GRAVITY

# Main program
if __name__ == "__main__":
    force = calculate_force(10)
    print(f"Force: {force}N")

Example of well-structured Python code following best practices.

Expected Output:

Force: 98.0N

Quiz: Test Your Knowledge

1. What is Python primarily known for?

2. What does Python use to define code blocks?

3. Which version of Python should you learn?

4. What is the recommended indentation in Python?

5. Which of these is a valid Python identifier?

Practice Exercises

Exercise 1: Print Your Introduction

Write a Python program that prints your name, age, and a hobby. Use multiple print statements.

Show Hints
  • Use print() function
  • Print name, age, and hobby separately
  • You can use strings directly
Show Solution
print("Name: Alice")
print("Age: 25")
print("Hobby: Reading")

Exercise 2: Create a Welcome Message

Write a program that prints a welcome message with your name using a single print statement.

Show Hints
  • Use f-strings or string concatenation
  • Format: "Welcome, [Your Name]!"
Show Solution
name = "Alice"
print(f"Welcome, {name}!")

Exercise 3: Print a Pattern

Print the following pattern using print statements: * ** *** ****

Show Hints
  • Use multiple print statements
  • Each line has one more asterisk
Show Solution
print("*")
print("**")
print("***")
print("****")

Exercise 4: Add Comments to Code

Write a program that calculates 10 + 20 and prints the result. Add appropriate comments explaining each step.

Show Hints
  • Use # for single-line comments
  • Comment what the code does
  • Add comments before operations
Show Solution
# This program calculates the sum of two numbers
# First number
num1 = 10

# Second number
num2 = 20

# Calculate sum
result = num1 + num2

# Display result
print(f"Sum: {result}")

Exercise 5: Print with Formatting

Print "Python Programming" with a custom separator between words (use "-" as separator).

Show Hints
  • Use print() with sep parameter
  • Pass multiple strings to print()
  • Set sep="-"
Show Solution
print("Python", "Programming", sep="-")

Exercise 6: Create a Multi-line Comment

Write a program with a multi-line comment (docstring) explaining what the program does, then print "Hello, Python!".

Show Hints
  • Use triple quotes """ for multi-line comments
  • Add description of the program
  • Then add print statement
Show Solution
"""
This is my first Python program.
It demonstrates multi-line comments.
Author: Your Name
"""

print("Hello, Python!")

Exercise 7: Print Special Characters

Print a message that includes quotes: "Python is 'awesome'!"

Show Hints
  • Use escape characters
  • Use \" for double quotes or \' for single quotes
  • Or use different quote types
Show Solution
print("Python is 'awesome'!")
# or
print('Python is "awesome"!')

Exercise 8: Print on Same Line

Print "Hello" and "World" on the same line separated by a space.

Show Hints
  • Use end parameter in print()
  • Or print multiple values in one print()
  • Default separator is space
Show Solution
print("Hello", "World")
# or
print("Hello", end=" ")
print("World")

Exercise 9: Create a Program Header

Write a program with a header comment block containing program name, author, and date, then print "Program started".

Show Hints
  • Use comments for header
  • Include program name, author, date
  • Then print message
Show Solution
# Program: My First Python Program
# Author: Your Name
# Date: 2024-01-01

print("Program started")

Exercise 10: Print Mathematical Expression

Print the result of 5 * 3 + 2 in a formatted way: "Result: 17"

Show Hints
  • Calculate the expression
  • Use f-string for formatting
  • Print with label
Show Solution
result = 5 * 3 + 2
print(f"Result: {result}")