Python is a simple, powerful programming language that is suitable for both beginners and professional developers. This tutorial will introduce the basic concepts of Python.
1. Introduction to Python
Python is a high-level, interpreted, general-purpose programming language, first released by Guido van Rossum in 1991. It has the following features:
Simple and readable syntax
Cross-platform compatibility
Rich standard library
Supports multiple programming paradigms (object-oriented, functional, procedural)
Large community support
2. Installing Python
1. Visit the official Python website
2. Download the version suitable for your operating system
3. Run the installer and check the “Add Python to PATH” option
4. Complete the installation
5. Verify the installation:
python --version# or python3 --version
3. Your First Python Program
Create a file named hello.py with the following content:
print("Hello World!")
Run the program:
python hello.py
4. Basic Syntax
1. Comments
# This is a single-line comment"""This is a multi-line comment"""
2. Indentation
Python uses indentation to indicate code blocks (usually 4 spaces)
if 5 > 2: print("Five is greater than two!")
3. Variables and Data Types
Variables
x = 5 # Integer
y = "Hello" # String
z = 3.14 # Float
Basic Data Types
Integer (int): 5, -3, 0
Float (float): 3.14, -0.001
String (str): “hello”, ‘world’
Boolean (bool): True, False
NoneType: None
4. Type Conversion
x = str(3) # "3"
y = int("5") # 5
z = float(3) # 3.0
5. Operators
Arithmetic Operators
+ # Addition
- # Subtraction
* # Multiplication
/ # Division
% # Modulus
** # Exponentiation
// # Floor Division
Comparison Operators
== # Equal
!= # Not equal
> # Greater than
< # Less than
>= # Greater than or equal to
<= # Less than or equal to
Logical Operators
and # And
or # Or
not # Not
6. Control Flow
If Statement
x = 10
if x > 0: print("Positive")
elif x == 0: print("Zero")
else: print("Negative")
For Loop
for i in range(5): # 0 to 4 print(i)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: print(fruit)
While Loop
count = 0
while count < 5: print(count) count += 1
7. Functions
Defining Functions
def greet(name): """This is a greeting function""" return f"Hello, {name}!"
print(greet("Alice"))
Parameters and Return Values
def add(a, b=1): # b has a default value of 1 return a + b
result = add(3, 4) # 7
result2 = add(3) # 4
8. Data Structures
1. List
my_list = [1, 2, 3, "apple", True]
my_list.append("banana") # Add element
print(my_list[0]) # Access the first element
2. Tuple
my_tuple = (1, 2, "apple") # Immutable
print(my_tuple[2])
3. Dictionary
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # "Alice"
my_dict["city"] = "New York" # Add key-value pair
4. Set
my_set = {1, 2, 3, 3} # {1, 2, 3} - Automatically removes duplicates
my_set.add(4)
9. File Operations
1. Reading Files
with open("example.txt", "r") as file: content = file.read() print(content)
2. Writing Files
with open("output.txt", "w") as file: file.write("Hello, File!")
10. Exception Handling
try: x = 1 / 0
except ZeroDivisionError: print("Cannot divide by zero!")
except Exception as e: print(f"An error occurred: {e}")
finally: print("This always executes")