You are viewing a preview of this lesson. Sign in to start learning
Back to Python Programming

Python Introduction

Understanding Python's history, features, and use cases

Python Introduction

Python is one of the most popular programming languages in the world, perfect for beginners and professionals alike. Master Python basics with free flashcards and spaced repetition practice to reinforce your learning. This lesson covers Python's history and philosophy, installation and setup, the interactive interpreter, and writing your first Python programsโ€”essential concepts for anyone starting their programming journey.

Welcome to Python! ๐Ÿ

Welcome to the exciting world of Python programming! Whether you're completely new to coding or transitioning from another language, Python offers an incredible learning experience. Its clean, readable syntax makes it feel almost like writing in plain English, while its powerful capabilities enable you to build everything from simple scripts to complex web applications, data science pipelines, and artificial intelligence systems.

๐Ÿ’ก Did you know? Python is named after the British comedy series "Monty Python's Flying Circus," not the snake! Creator Guido van Rossum wanted a name that was short, unique, and slightly mysterious.

Core Concepts

What is Python? ๐Ÿ’ป

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability and simplicity, allowing programmers to express concepts in fewer lines of code than languages like C++ or Java.

Key characteristics of Python:

  • Interpreted: Code runs line-by-line without needing compilation
  • Dynamically typed: Variables don't need explicit type declarations
  • Object-oriented: Supports classes and objects for organizing code
  • High-level: Abstracts away low-level details like memory management
  • Cross-platform: Runs on Windows, macOS, Linux, and more

๐ŸŒ Real-world analogy: Think of Python as a universal translator. Just as a translator helps people speaking different languages communicate, Python translates human-readable code into instructions computers can executeโ€”and it does so with remarkable clarity and simplicity.

The Zen of Python ๐Ÿง˜

Python has a design philosophy captured in "The Zen of Python" (try typing import this in Python!). Here are some key principles:

  • Readability counts: Code is read more often than written
  • Simple is better than complex: Choose clarity over cleverness
  • Explicit is better than implicit: Make your intentions clear
  • There should be one obvious way to do it: Python favors consistency

๐Ÿง  Memory device: Remember "RISE" for Python's core values:

  • Readability
  • Intuitiveness
  • Simplicity
  • Explicitness

Python Versions: Python 2 vs Python 3 ๐Ÿ“Š

Python has two major versions, and it's crucial to understand the difference:

Feature Python 2.x Python 3.x
Status โ›” Deprecated (since 2020) โœ… Current standard
Print print "Hello" print("Hello")
Division 5/2 = 2 (integer) 5/2 = 2.5 (float)
Unicode ASCII by default Unicode by default
Use case Legacy systems only All new projects

โš ๏ธ Important: Always use Python 3.x for new projects. Python 2 is no longer maintained and lacks security updates.

Installing Python ๐Ÿ”ง

Getting Python on your system is straightforward:

Windows:

  1. Visit python.org/downloads
  2. Download the latest Python 3.x installer
  3. โš ๏ธ Critical: Check "Add Python to PATH" during installation
  4. Complete the installation wizard

macOS:

  1. macOS comes with Python 2.7 (outdated)
  2. Install Python 3 via python.org or use Homebrew: brew install python3
  3. Use python3 command to ensure you're using Python 3

Linux:

# Most distributions include Python 3
sudo apt-get update
sudo apt-get install python3 python3-pip

๐Ÿ”ง Try this: After installation, open your terminal or command prompt and type:

python --version

You should see something like Python 3.11.2 (your version number may vary).

The Python Interpreter ๐ŸŽฎ

The Python interpreter is an interactive environment where you can execute Python code immediately and see results. It's perfect for experimentation and learning!

Starting the interpreter:

python
# or on some systems
python3

You'll see the interactive prompt:

Python 3.11.2 (main, Feb  7 2023, 12:45:23)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> is where you type Python commands:

>>> 2 + 2
4
>>> print("Hello, World!")
Hello, World!
>>> name = "Alice"
>>> print(f"Hello, {name}!")
Hello, Alice!

๐Ÿ’ก Tip: The interpreter is like a Python calculator that can do much more than mathโ€”it's your playground for testing ideas!

To exit the interpreter:

>>> exit()
# or press Ctrl+D (Linux/Mac) or Ctrl+Z then Enter (Windows)

Python Scripts: Writing Your First Program ๐Ÿ“

While the interpreter is great for quick tests, you'll typically write Python code in script files with the .py extension.

Creating a Python script:

  1. Open a text editor (VS Code, Sublime Text, Notepad++, or even basic Notepad)
  2. Write your Python code
  3. Save with a .py extension (e.g., hello.py)
  4. Run from terminal: python hello.py

Anatomy of a Python file:

# This is a comment - Python ignores this line
# Comments explain code to humans

# Variables store data
name = "World"
number = 42

# Functions perform actions
print(f"Hello, {name}!")
print(f"The answer is {number}")

# Python executes from top to bottom

Basic Python Syntax Rules ๐Ÿ“‹

Indentation matters! Unlike many languages that use curly braces {}, Python uses indentation to define code blocks:

# Correct
if True:
    print("This is indented")
    print("Same level of indentation")

# Wrong - will cause IndentationError
if True:
print("Not indented")
  print("Inconsistent indentation")

Other syntax rules:

  • Case-sensitive: Variable and variable are different
  • No semicolons needed: Line breaks separate statements
  • Statements: Complete instructions (usually one per line)
  • Comments: Start with # for single-line, or """ ... """ for multi-line
Element Syntax Example
Comment # text # This is a comment
Variable assignment name = value age = 25
Print output print(value) print("Hi")
String "text" or 'text' message = "Hello"
Number No quotes count = 100

Python Use Cases ๐Ÿš€

Python's versatility makes it suitable for virtually any programming task:

PYTHON APPLICATION DOMAINS

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ๐ŸŒ Web Development                     โ”‚
โ”‚  Django, Flask, FastAPI                 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ๐Ÿ“Š Data Science & Analytics            โ”‚
โ”‚  Pandas, NumPy, Matplotlib              โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ๐Ÿค– Machine Learning & AI               โ”‚
โ”‚  TensorFlow, PyTorch, scikit-learn      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ๐Ÿ”ฌ Scientific Computing                โ”‚
โ”‚  SciPy, Jupyter, Biopython              โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  โš™๏ธ Automation & Scripting              โ”‚
โ”‚  File operations, task automation       โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ๐ŸŽฎ Game Development                    โ”‚
โ”‚  Pygame, Panda3D                        โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ๐Ÿ” Cybersecurity                       โ”‚
โ”‚  Penetration testing, security tools    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Detailed Examples

Example 1: Hello World - Your First Python Program ๐Ÿ‘‹

Every programming journey begins with "Hello, World!" - a tradition dating back to the 1970s.

The code:

print("Hello, World!")

Explanation:

  • print() is a built-in function that displays output
  • "Hello, World!" is a string (text data) enclosed in quotes
  • No semicolons or complex syntax needed!

Running it:

  1. Save as hello.py
  2. Run: python hello.py
  3. Output: Hello, World!

Variations:

# Using single quotes (equivalent)
print('Hello, World!')

# Multiple print statements
print("Hello, World!")
print("Welcome to Python!")

# Printing numbers (no quotes needed)
print(42)
print(3.14)

# Printing multiple items
print("The answer is", 42)

๐Ÿค” Did you know? The first "Hello, World!" program appeared in Brian Kernighan's 1972 tutorial for the B programming language, predecessor to C.

Example 2: Variables and Basic Operations ๐Ÿ”ข

Variables are containers that store data. Python makes working with variables incredibly simple.

The code:

# Variable assignment
name = "Alice"
age = 28
height = 1.65
is_student = True

# Using variables
print("Name:", name)
print("Age:", age)
print("Height:", height, "meters")

# Basic arithmetic
x = 10
y = 3

print("Addition:", x + y)        # 13
print("Subtraction:", x - y)     # 7
print("Multiplication:", x * y)  # 30
print("Division:", x / y)        # 3.333...
print("Integer division:", x // y)  # 3
print("Remainder:", x % y)       # 1
print("Power:", x ** y)          # 1000

Explanation:

  • No type declarations needed: Python automatically detects that name is a string, age is an integer, etc.
  • Dynamic typing: You can reassign variables to different types
  • Operator symbols: +, -, *, / work as expected
  • Special operators: // (integer division), % (modulo/remainder), ** (exponentiation)

Variable naming rules:

  • Start with letter or underscore: _valid, name2 โœ…
  • Cannot start with number: 2name โŒ
  • Case-sensitive: Age โ‰  age
  • Use snake_case convention: user_name, total_count
  • Avoid Python keywords: if, for, class, etc.

๐Ÿ’ก Tip: Choose descriptive variable names! user_age is better than x or ua.

Example 3: User Input and F-Strings ๐Ÿ’ฌ

Interactive programs that respond to user input are more engaging and useful.

The code:

# Getting user input
name = input("What is your name? ")
age = input("How old are you? ")

# F-strings for formatted output (Python 3.6+)
print(f"Hello, {name}!")
print(f"You are {age} years old.")

# Calculating with input (convert string to number)
age_num = int(age)
years_to_100 = 100 - age_num
print(f"You have {years_to_100} years until you turn 100!")

# Multiple variables in f-strings
first_name = "Bob"
last_name = "Smith"
full_name = f"{first_name} {last_name}"
print(f"Full name: {full_name}")

# F-strings with expressions
width = 5
height = 3
print(f"The area of a {width}x{height} rectangle is {width * height}")

Explanation:

  • input() displays a prompt and waits for user to type something
  • โš ๏ธ Important: input() always returns a string, even if user types a number
  • Use int(), float(), etc. to convert strings to numbers
  • F-strings (formatted string literals) start with f and use {} for variables
  • You can put expressions inside {} like {width * height}

Other string formatting methods:

# Older .format() method
print("{} is {} years old".format(name, age))

# Oldest % formatting (avoid in new code)
print("%s is %s years old" % (name, age))

# F-strings are preferred - cleaner and faster!

Example 4: Working with the REPL (Interactive Mode) ๐ŸŽฏ

The REPL (Read-Eval-Print Loop) is Python's interactive interpreterโ€”perfect for experimentation!

Session example:

>>> # Simple calculations
>>> 15 + 27
42

>>> # Variables persist in session
>>> pi = 3.14159
>>> radius = 5
>>> area = pi * radius ** 2
>>> area
78.53975

>>> # Testing string methods
>>> text = "python programming"
>>> text.upper()
'PYTHON PROGRAMMING'
>>> text.title()
'Python Programming'

>>> # Quick function testing
>>> def greet(name):
...     return f"Hello, {name}!"
...
>>> greet("World")
'Hello, World!'

>>> # Exploring built-ins
>>> len("Python")
6
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>

>>> # Getting help
>>> help(print)
# (displays documentation)

Explanation:

  • >>> is the primary prompt (ready for a statement)
  • ... is the secondary prompt (continuation of a block)
  • Results display immediately without print()
  • Variables and functions remain available throughout the session
  • Use help(object) to see documentation
  • Use dir(object) to see available methods

๐Ÿ”ง Try this: Open Python's REPL and type import this to see the Zen of Python!

REPL workflow diagram:

     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
     โ”‚  Python REPL Loop               โ”‚
     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                  โ”‚
                  โ–ผ
      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
      โ”‚  1. READ: Get input  โ”‚
      โ”‚     from user        โ”‚
      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ–ผ
      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
      โ”‚  2. EVAL: Execute    โ”‚
      โ”‚     the code         โ”‚
      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ–ผ
      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
      โ”‚  3. PRINT: Show      โ”‚
      โ”‚     the result       โ”‚
      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ–ผ
      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
      โ”‚  4. LOOP: Return     โ”‚
      โ”‚     to step 1        โ”‚
      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
                 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                           โ”‚
     (Continues until exit())

Common Mistakes โš ๏ธ

Avoiding these pitfalls will save you hours of debugging:

1. Forgetting to Install Python or Add to PATH

โŒ Wrong:

$ python hello.py
bash: python: command not found

โœ… Right:

  • Install Python from python.org
  • โš ๏ธ Check "Add Python to PATH" during Windows installation
  • Use python3 on systems with both Python 2 and 3

2. Indentation Errors

โŒ Wrong:

if True:
print("No indentation!")
  print("Inconsistent indentation!")

โœ… Right:

if True:
    print("Consistent indentation")
    print("All at same level")

๐Ÿ’ก Tip: Use 4 spaces per indentation level (Python convention). Configure your editor to convert tabs to spaces.

3. Treating input() as Numbers

โŒ Wrong:

age = input("Age: ")  # Returns string "25"
years = 100 - age     # TypeError: unsupported operand type(s)

โœ… Right:

age = int(input("Age: "))  # Convert to integer
years = 100 - age          # Now works!

4. Using Python 2 Syntax in Python 3

โŒ Wrong (Python 2):

print "Hello"  # SyntaxError in Python 3

โœ… Right (Python 3):

print("Hello")  # print is a function

5. Not Using F-Strings for Formatting

โŒ Less readable:

print("Hello, " + name + "! You are " + str(age) + " years old.")

โœ… Right:

print(f"Hello, {name}! You are {age} years old.")

6. Confusing = (Assignment) with == (Comparison)

โŒ Wrong:

if x = 5:  # SyntaxError: can't use assignment in conditional
    print("x is 5")

โœ… Right:

if x == 5:  # Use == for comparison
    print("x is 5")

7. Case Sensitivity Issues

โŒ Wrong:

Name = "Alice"
print(name)  # NameError: name 'name' is not defined

โœ… Right:

name = "Alice"
print(name)  # Match the case exactly

Key Takeaways ๐ŸŽฏ

โœ… Python is beginner-friendly with clean, readable syntax

โœ… Always use Python 3.x - Python 2 is deprecated

โœ… The interpreter (REPL) is perfect for testing and learning

โœ… Indentation matters - it defines code structure

โœ… Variables are dynamically typed - no declarations needed

โœ… F-strings are the modern way to format text

โœ… input() returns strings - convert with int() or float()

โœ… Comments start with # - document your code!

โœ… Python is versatile - web dev, data science, automation, AI, and more

โœ… Practice in the REPL - experiment freely without files

๐Ÿ“š Further Study

  1. Official Python Tutorial: https://docs.python.org/3/tutorial/ - Comprehensive guide from Python's creators
  2. Real Python: https://realpython.com/ - High-quality tutorials and articles for all skill levels
  3. Python Package Index (PyPI): https://pypi.org/ - Explore thousands of Python libraries

๐Ÿ“‹ Quick Reference Card: Python Basics

ConceptSyntaxExample
Print outputprint(value)print("Hi")
Variablename = valueage = 25
Comment# text# This is a note
User inputinput(prompt)name = input("Name: ")
F-stringf"text {var}"f"Hi {name}"
String to intint(string)age = int("25")
Run scriptpython file.pypython hello.py
Start REPLpythonInteractive interpreter
Check versionpython --versionShows Python version
Get helphelp(object)help(print)

๐Ÿง  Remember "RISE" for Python's philosophy:

  • Readability - Code should be easy to understand
  • Intuitiveness - Solutions should be obvious
  • Simplicity - Simple is better than complex
  • Explicitness - Be clear about what you mean

Practice Questions

Test your understanding with these questions:

Q1: Write a Python script that asks the user for their name and age, then prints a message saying "Hello [name], you are [age] years old" using an f-string.
A: !AI