Learn Python in 10 minutes
Python is a high-level, interpreted programming language known for its concise syntax and powerful features. This tutorial is based on the latest Python 3.13+ version, helping you quickly learn Python.
1. Writing Your First Python Program
Let’s start with a simple program. Create a file named hello.py
and enter the following code:
print("Hello, World!")
Save the file and run the following command in the terminal or command line:
python hello.py
The output will be:
Hello, World!
This simple program demonstrates Python’s basic output functionality. The print()
function is used to display text information in the console.
2. Basic Syntax
Python’s syntax is simple and easy to understand. Python uses indentation to define code blocks, unlike other languages that use curly braces {}
.
# This is a comment
print("Hello, World!")
Basic syntax rules in Python:
- Indentation: By default, 4 spaces are used to indicate a code block’s level. For example, code inside functions or loops must be indented.
- Comments: Single-line comments start with
#
, while multi-line comments use triple quotes"""
or'''
. - Statements: Typically one statement per line, no semicolon
;
is needed at the end. - Code Blocks: Defined by indentation, such as
if
,for
, or function bodies.
Example with multi-line comments:
"""
This is a multi-line comment,
spanning multiple lines.
"""
Indentation is a key feature of Python’s syntax, used to define the hierarchical structure of code blocks:
if True:
print("This line is indented")
print("This line is also indented")
print("This line is not indented")
3. Variables and Data Types
In Python, variables are containers for storing data. Python is a dynamically typed language, meaning you don’t need to declare a variable’s type in advance.
Basic variable naming rules:
- Variable names can only contain letters, numbers, and underscores.
- Variable names cannot start with a number.
- Variable names are case-sensitive.
- Python keywords cannot be used as variable names.
Variable types are determined by the assigned value. Python’s main basic data types are:
- Integer (int): e.g.,
42
or-10
, with no size limit. - Float (float): e.g.,
3.14
or2.5e3
(scientific notation). - String (str): e.g.,
"hello"
or'world'
, using single or double quotes. - Boolean (bool):
True
orFalse
. - NoneType (None): Represented by
None
, indicating null or no value.
Python supports type hints to improve code readability, used for static checking and IDE support, without affecting runtime behavior:
name: str = "Alice"
age: int = 25
3.1 Numeric Types (Number)
Python supports three numeric types: integer (int), float (float), and complex (complex).
# Integer
age = 25
population = 1000000
# Float
temperature = 36.5
pi = 3.14159
# Complex
complex_num = 3 + 4j
3.2 String (String)
Strings are sequences of characters, enclosed in single or double quotes.
single_quote = 'Single quote string'
double_quote = "Double quote string"
multiline = """This is a
multi-line string"""
String operations:
text = "Python programming"
print(len(text)) # String length
print(text.upper()) # Convert to uppercase
print(text.lower()) # Convert to lowercase
print(text[0]) # Access first character
print(text[2:6]) # String slicing
3.3 Boolean Type (Boolean)
Boolean type has two values: True
and False
.
is_active = True
is_complete = False
# Boolean operations
result1 = True and False # False
result2 = True or False # True
result3 = not True # False
3.4 None Type (None)
None
represents a null or no-value state.
value = None
if value is None:
print("Value is null")
4. Data Structures
Python provides several built-in data structures for storing and manipulating data. Below are the commonly used data structures and their usage.
4.1 List (List)
A list is an ordered and mutable collection. You can add, remove, or modify elements in a list. Lists are defined using square brackets []
.
numbers = [1, 2, 3, 4, 5]
numbers.append(6) # Add element
numbers.insert(0, 0) # Insert at specific position
numbers.remove(3) # Remove specific value
numbers[0] = 10 # Modify element
print(numbers) # [10, 2, 4, 5, 6]
List slicing to access sublists:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[-2:]) # Output: [40, 50]
List comprehension:
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
4.2 Tuple (Tuple)
A tuple is an ordered but immutable collection. Once created, its elements cannot be modified. Tuples are defined using parentheses ()
. Due to their immutability, tuples are generally faster than lists and can be used as dictionary keys.
point = (10, 20)
x, y = point # Unpacking
print(x, y) # Output: 10 20
Single-element tuples require a comma:
single_tuple = (42,)
4.3 Dictionary (Dict)
A dictionary is an unordered (ordered in Python 3.7+) collection of key-value pairs. Each key is unique and associated with a value. Dictionaries are defined using curly braces {}
.
student = {
"name": "John",
"age": 20,
"major": "Computer Science"
}
# Accessing and modifying dictionary
print(student["name"])
student["age"] = 21
student["gpa"] = 3.8
# Safe access
print(student.get("phone", "Not provided"))
# Iterating over dictionary
for key, value in student.items():
print(f"{key}: {value}")
Dictionary comprehension:
# Create a squares dictionary
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Conditional dictionary comprehension
even_squares_dict = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares_dict) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
4.4 Set (Set)
A set is an unordered collection with no duplicate elements. Defined using curly braces {}
or set()
.
# Creating a set
fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 3, 3, 4, 4, 5]) # Automatic deduplication
print(numbers) # {1, 2, 3, 4, 5}
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # Union: {1, 2, 3, 4, 5, 6}
print(set1 & set2) # Intersection: {3, 4}
print(set1 - set2) # Difference: {1, 2}
print(set1 ^ set2) # Symmetric difference: {1, 2, 5, 6}
5. Operations and Operators
Python provides a rich set of operators for various computations and comparisons, including arithmetic, comparison, logical, bitwise, and identity operators.
- Arithmetic Operators:
+
,-
,*
,/
,//
(integer division),%
(modulus),**
(exponentiation). - Comparison Operators:
==
,!=
,>
,<
,>=
,<=
. - Logical Operators:
and
,or
,not
. - Membership Operators:
in
,not in
. - Identity Operators:
is
,is not
.
5.1 Arithmetic Operators
Arithmetic operators are used for mathematical operations. Operator precedence follows mathematical rules (e.g., **
has higher precedence than +
or -
). Parentheses ()
can be used to change precedence.
a, b = 10, 3
print(f"Addition: {a + b}") # 13
print(f"Subtraction: {a - b}") # 7
print(f"Multiplication: {a * b}") # 30
print(f"Division: {a / b}") # 3.333...
print(f"Integer Division: {a // b}") # 3
print(f"Modulus: {a % b}") # 1
print(f"Exponentiation: {a ** b}") # 1000
5.2 Comparison Operators
Comparison operators compare two values and return a boolean (True
or False
).
x, y = 5, 10
print(f"Equal: {x == y}") # False
print(f"Not equal: {x != y}") # True
print(f"Greater than: {x > y}") # False
print(f"Less than: {x < y}") # True
print(f"Greater or equal: {x >= y}") # False
print(f"Less or equal: {x <= y}") # True
5.3 Logical Operators
Logical operators combine or manipulate boolean values (True
or False
), typically used in conditional statements.
a, b = True, False
print(f"AND operation: {a and b}") # False
print(f"OR operation: {a or b}") # True
print(f"NOT operation: {not a}") # False
5.4 Identity Operators
The is
operator compares the identity of two objects, checking if they refer to the same memory address (not just equal values). It differs from ==
, which compares content.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(f"list1 is list2: {list1 is list2}") # False
print(f"list1 is list3: {list1 is list3}") # True
print(f"list1 == list2: {list1 == list2}") # True
5.5 Membership Operators
Membership operators test if a value is a member of a sequence (e.g., list, tuple, string, set), returning a boolean.
fruits = ["apple", "banana", "orange"]
print(f"'apple' in fruits: {'apple' in fruits}") # True
print(f"'grape' not in fruits: {'grape' not in fruits}") # True
6. Control Flow
Python provides several control flow statements to manage the execution order of a program.
6.1 if Statements
The if
statement evaluates a condition and executes its block if the condition is True
. Use elif
and else
for complex conditions.
age = 20
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
6.2 for Loops
The for
loop iterates over an iterable object (e.g., list, tuple, string, or range).
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range() for looping
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
6.3 while Loops
The while
loop continues executing a block as long as its condition remains True
.
count = 0
while count < 5:
print(count)
count += 1
- break and continue:
break
exits the loop,continue
skips the current iteration.
for i in range(10):
if i == 5:
break
if i % 2 == 0:
continue
print(i) # Output: 1, 3
6.4 match Statements
Introduced in Python 3.10, the match
statement provides powerful structural pattern matching, acting as an advanced alternative to if/elif/else
chains.
http_status = 200
match http_status:
case 200 | 201:
print("Success")
case 404:
print("Not found")
case 500:
print("Server error")
case _: # Wildcard, matches any other case
print("Unknown status")
7. Input and Output
7.1 Basic Input and Output
Use the input()
function to get user input and the print()
function to output information.
# Getting user input
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
# Outputting information
print("Welcome", name)
print("You are", age, "years old")
7.2 Formatted Output (f-strings)
Introduced in Python 3.6+, f-strings (formatted string literals) are a convenient and powerful way to format strings. Prefix a string with f
or F
and embed variables or expressions in curly braces {}
.
user = "Alice"
items = 3
total_cost = 45.5
# Using f-string for formatted message
message = f"User {user} purchased {items} items for ${total_cost:.2f}."
print(message)
# Expressions in f-strings
print(f"2 + 3 equals {2 + 3}")
Expressions and function calls in f-strings:
width = 10
height = 5
# Using expressions in f-strings
area = f"Rectangle area: {width * height}"
print(area)
# Calling functions
text = "python"
formatted = f"Uppercase: {text.upper()}, Length: {len(text)}"
print(formatted)
Formatting options in f-strings:
pi = 3.14159265359
large_number = 1234567
# Number formatting
print(f"Pi (2 decimals): {pi:.2f}")
print(f"Pi (4 decimals): {pi:.4f}")
print(f"Large number (thousands): {large_number:,}")
print(f"Percentage: {0.85:.1%}")
# String alignment
name = "Python"
print(f"Left align: '{name:<10}'")
print(f"Right align: '{name:>10}'")
print(f"Center align: '{name:^10}'")
Date and time formatting with f-strings:
from datetime import datetime
now = datetime.now()
print(f"Current time: {now}")
print(f"Formatted time: {now:%Y-%m-%d %H:%M:%S}")
print(f"Date only: {now:%Y-%m-%d}")
9. Functions
Functions in Python are reusable code blocks for specific tasks, defined using the def
keyword, supporting default parameters, variable arguments, and keyword arguments.
Basic Function Definition:
def greet(name):
"""Greeting function"""
return f"Hello, {name}!"
# Calling the function
message = greet("John")
print(message)
Keyword Arguments:
Keyword arguments are passed using parameter_name=value
syntax.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
print(greet("Bob", "Hi")) # Output: Hi, Bob!
Variable Arguments:
Variable arguments allow functions to accept an arbitrary number of arguments, either positional (*args
) or keyword (**kwargs
).
# Positional variable arguments (*args)
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3, 4)) # Output: 10
# Keyword variable arguments (**kwargs)
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_kwargs(name="Alice", age=25, city="Beijing")
Function Annotations:
Function annotations add descriptive metadata to function parameters and return values, improving readability and documentation.
def calculate_area(length: float, width: float) -> float:
"""Calculate rectangle area"""
return length * width
def process_user(name: str, age: int, active: bool = True) -> dict:
"""Process user information"""
return {
"name": name,
"age": age,
"active": active
}
10. Lambda Expressions
Lambda expressions create anonymous functions, providing a concise way to define small functions.
square = lambda x: x ** 2
print(square(5)) # Output: 25
Commonly used with higher-order functions like map
or filter
:
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # Output: [1, 4, 9, 16]
11. Classes and Objects
Python supports object-oriented programming using the class
keyword:
class Person:
"""Person class"""
def __init__(self, name, age):
"""Constructor"""
self.name = name
self.age = age
def introduce(self):
"""Introduce method"""
return f"I am {self.name}, {self.age} years old"
def have_birthday(self):
"""Birthday method"""
self.age += 1
return f"{self.name} had a birthday, now {self.age} years old"
# Creating objects
person1 = Person("John", 25)
person2 = Person("Jane", 30)
print(person1.introduce())
print(person2.have_birthday())
11.1 Class and Instance Attributes
In Python, class attributes and instance attributes are two types of attributes for storing data in classes and objects.
- Class Attributes: Defined outside methods, belong to the class itself, and are shared across all instances.
- Instance Attributes: Defined in methods (usually
__init__
), bound to specific instances viaself
.
class Student:
# Class attributes
school = "Stanford University"
student_count = 0
def __init__(self, name, major):
# Instance attributes
self.name = name
self.major = major
Student.student_count += 1
@classmethod
def get_student_count(cls):
"""Class method"""
return cls.student_count
@staticmethod
def is_valid_age(age):
"""Static method"""
return 0 < age < 150
# Usage example
student1 = Student("John", "Computer Science")
student2 = Student("Jane", "Mathematics")
print(f"School: {Student.school}")
print(f"Total students: {Student.get_student_count()}")
print(f"Valid age: {Student.is_valid_age(20)}")
11.2 Class Inheritance
Inheritance allows a class (subclass) to inherit attributes and methods from another class (parent class), enabling code reuse and extension.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return f"{self.name} makes a sound"
def info(self):
return f"{self.name} is a {self.species}"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Dog")
self.breed = breed
def make_sound(self):
return f"{self.name} barks"
def fetch(self):
return f"{self.name} fetches the ball"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Cat")
self.color = color
def make_sound(self):
return f"{self.name} meows"
def climb(self):
return f"{self.name} climbs a tree"
# Using inheritance
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Mimi", "Orange")
print(dog.info())
print(dog.make_sound())
print(dog.fetch())
print(cat.info())
print(cat.make_sound())
print(cat.climb())
11.3 Special Methods (Magic Methods)
Special methods (or magic methods) are double-underscored methods that define specific behaviors, automatically called by Python in certain scenarios.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
"""String representation"""
return f"Rectangle({self.width}x{self.height})"
def __repr__(self):
"""Official string representation"""
return f"Rectangle(width={self.width}, height={self.height})"
def __eq__(self, other):
"""Equality comparison"""
if isinstance(other, Rectangle):
return self.width == other.width and self.height == other.height
return False
def __lt__(self, other):
"""Less than comparison (by area)"""
if isinstance(other, Rectangle):
return self.area() < other.area()
return NotImplemented
def __add__(self, other):
"""Addition operation"""
if isinstance(other, Rectangle):
return Rectangle(self.width + other.width, self.height + other.height)
return NotImplemented
def area(self):
"""Calculate area"""
return self.width * self.height
# Using special methods
rect1 = Rectangle(3, 4)
rect2 = Rectangle(5, 6)
rect3 = Rectangle(3, 4)
print(rect1) # Rectangle(3x4)
print(repr(rect1)) # Rectangle(width=3, height=4)
print(rect1 == rect3) # True
print(rect1 < rect2) # True
print(rect1 + rect2) # Rectangle(8x10)
12. Context Managers
Context managers ensure proper resource acquisition and release, commonly used with the with
statement for resource management, such as files or database connections.
12.1 Using Context Managers
File operations are a common use case for context managers:
with open("example.txt", "r") as file:
content = file.read()
print(content)
The with
statement ensures the file is automatically closed after operations.
12.2 Custom Context Managers
Create custom context managers by defining __enter__
and __exit__
methods:
class DatabaseConnection:
def __init__(self, database_name):
self.database_name = database_name
self.connection = None
def __enter__(self):
"""Called when entering context"""
print(f"Connecting to database: {self.database_name}")
self.connection = f"Connection to {self.database_name}"
return self.connection
def __exit__(self, exc_type, exc_value, traceback):
"""Called when exiting context"""
print(f"Closing database connection: {self.database_name}")
if exc_type:
print(f"Exception occurred: {exc_type.__name__}: {exc_value}")
self.connection = None
return False # Do not suppress exceptions
# Using custom context manager
with DatabaseConnection("user_database") as conn:
print(f"Using connection: {conn}")
print("Performing database operations...")
Using the contextlib
module to create context managers:
from contextlib import contextmanager
import time
@contextmanager
def timer(operation_name):
"""Timer context manager"""
print(f"Starting {operation_name}")
start_time = time.time()
try:
yield
finally:
end_time = time.time()
print(f"{operation_name} completed in {end_time - start_time:.2f} seconds")
# Using decorator-based context manager
with timer("data processing"):
# Simulate time-consuming operation
time.sleep(1)
print("Processing data...")
13. Exception Handling
Exception handling ensures program robustness, using try
, except
, else
, and finally
to manage exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful")
finally:
print("This always runs")
Output:
Cannot divide by zero!
This always runs
14. File Operations
Python provides simple methods for reading and writing files, typically used with context managers.
14.1 Reading Files
Reading text file content:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading line by line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
14.2 Writing Files
Writing to a text file:
with open("output.txt", "w") as file:
file.write("Hello, Python!\n")
Appending content:
with open("output.txt", "a") as file:
file.write("Appending new content.\n")
15. Modules and Packages
Modules are files containing Python code, and packages are directories containing multiple modules. Import modules using import
:
import math
print(math.sqrt(16)) # Output: 4.0
Custom module example (assume the file is named mymodule.py
):
# mymodule.py
def say_hello():
return "Hello from module!"
Importing and using:
import mymodule
print(mymodule.say_hello()) # Output: Hello from module!
16. Scope and Namespace
16.1 Scope
Scope defines the region where a variable is accessible. Python follows the LEGB rule for variable lookup:
- L (Local): Inside a function or class method.
- E (Enclosing): In the outer function of a nested function (closure).
- G (Global): At the module level.
- B (Built-in): Built-in functions and exceptions like
print()
orlen()
.
x = "global x"
def outer_func():
x = "enclosing x"
def inner_func():
x = "local x"
print(x) # Accesses local scope x
inner_func()
print(x) # Accesses enclosing scope x
outer_func()
print(x) # Accesses global scope x
Using global
or nonlocal
to modify scope variables:
x = "global"
def modify_global():
global x
x = "modified"
modify_global()
print(x) # Output: modified
16.2 Namespace
A namespace is a mapping from names to objects, like a dictionary where keys are variable names and values are the objects.
Each module, function, and class has its own namespace, preventing naming conflicts. Use globals()
and locals()
to inspect namespaces.
a_variable = 10
def some_function():
b_variable = 20
# locals() returns the current local namespace dictionary
print(f"Locals: {locals()}")
print(f"Globals: {globals().keys()}") # Prints keys of global namespace
some_function()
17. Generators
Generators are special iterators that generate values on demand, rather than creating all values at once, making them memory-efficient for large datasets.
Generators use the yield
keyword to return values lazily:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(5):
print(num) # Output: 0, 1, 1, 2, 3
18. Multithreading
Multithreading allows a program to perform multiple operations concurrently, useful for I/O-bound tasks like network requests or file operations.
Python’s threading
module provides tools for creating and managing threads. Due to the Global Interpreter Lock (GIL), multithreading doesn’t achieve true CPU parallelism in a single process, but it significantly improves performance for I/O-bound tasks.
import threading
import time
def worker(thread_name):
print(f"Thread {thread_name} starting...")
time.sleep(2) # Simulate time-consuming operation
print(f"Thread {thread_name} finished.")
# Create threads
thread1 = threading.Thread(target=worker, args=("A",))
thread2 = threading.Thread(target=worker, args=("B",))
# Start threads
thread1.start()
thread2.start()
# Wait for all threads to complete
thread1.join()
thread2.join()
print("All threads completed.")
19. Asynchronous Programming
Asynchronous programming is ideal for high I/O, high-concurrency scenarios, using an event loop to manage tasks instead of threads.
Python supports asynchronous programming via the asyncio
library and async/await
syntax.
async def
: Defines a coroutine.await
: Pauses coroutine execution, waiting for an awaitable object to complete.
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # Non-blocking sleep, simulating I/O
print("World")
async def main():
# Create and await a task
await asyncio.create_task(say_hello())
# Run the main coroutine
asyncio.run(main())
Output:
Hello
World