Python Basic Syntax
本文一共:13495 个字,需要阅读:34 分钟,更新时间:2024年8 月17日,部分内容具有时效性,如有失效请留言,阅读量:66
Python Basics Tutorial
Introduction to Python
Python is an interpreted, high-level, general-purpose programming language developed by Guido van Rossum and first released in 1991. It is widely praised for its simplicity and readability, making it a popular choice for beginners and professionals alike, especially in fields such as data science, artificial intelligence, web development, and automation.
Python’s design philosophy includes:
- Simplicity: Clean and readable code that reduces development time.
- Ease of Learning: Very beginner-friendly.
- Rich Standard Library: Python’s standard library provides modules and functions for almost every programming task.
Installing Python
To use Python, you need to install the Python interpreter on your computer. You can download the installer from the Python official website. After installation, you can verify the installation by running the following command in your terminal:
python --version # Check the Python version
Setting Up Python Development Environment
You can write and run Python code in various environments. Here are some common ones:
- Command Line/Terminal: You can enter
python
in the terminal to start an interactive Python interpreter. - Text Editors: Editors like Visual Studio Code, Sublime Text, and Atom are great for writing and running Python scripts.
- Integrated Development Environment (IDE): PyCharm, Jupyter Notebook, and Thonny provide more tools and features for development.
Once your environment is set up, you can create a .py
file to write Python scripts and run them through the terminal.
Your First Python Program
Let’s start with the simplest Python program, which outputs “Hello, World!”:
print("Hello, World!")
Running this code will display Hello, World!
on the screen. This program demonstrates how Python uses the print()
function to output text.
Python Basic Syntax
Indentation
Python uses indentation to define code blocks. Typically, 4 spaces (or one Tab key) are used for indentation. The level of indentation determines the logical structure of the code.
if True:
print("This is indented")
if True:
print("This is further indented")
Variables
Variables are named locations used to store data. In Python, you don’t need to explicitly declare the type of a variable, as the interpreter infers the type from the assignment.
name = "Morax Cheng" # String
age = 15 # Integer
height = 1.75 # Float
is_student = True # Boolean
Variable names should be meaningful and are recommended to use lowercase letters and underscores for separation (e.g., user_name
).
Data Types
Python has the following common data types:
- Integer (int): Whole numbers of arbitrary size, such as
1
,100
,-5
- Float (float): Numbers with decimal points, such as
3.14
,-0.001
- String (str): Text data, such as
"Hello, World!"
- Boolean (bool): Logical values,
True
orFalse
- List (list): Ordered collections of elements, which can contain different types, such as
[1, "apple", True]
- Tuple (tuple): Ordered and immutable collections of elements, such as
(1, 2, 3)
- Set (set): Unordered and unique collections of elements, such as
{1, 2, 3}
- Dictionary (dict): Unordered collections of key-value pairs, such as
{"name": "Morax Cheng", "age": 15}
Operators
Python provides a variety of operators to perform different operations, including arithmetic, comparison, and logical operators.
Arithmetic Operators
Used to perform mathematical calculations.
x = 10
y = 3
print(x + y) # Addition, outputs 13
print(x - y) # Subtraction, outputs 7
print(x * y) # Multiplication, outputs 30
print(x / y) # Division, outputs 3.3333333333333335
print(x % y) # Modulus, outputs 1
print(x ** y) # Exponentiation, outputs 1000
print(x // y) # Floor division, outputs 3 (integer division, rounded down)
Comparison Operators
Used to compare two values, resulting in a boolean value (True
or False
).
print(x > y) # Greater than, outputs True
print(x < y) # Less than, outputs False
print(x == y) # Equal to, outputs False
print(x != y) # Not equal to, outputs True
print(x >= y) # Greater than or equal to, outputs True
print(x <= y) # Less than or equal to, outputs False
Logical Operators
Used to combine boolean values or expressions.
a = True
b = False
print(a and b) # Logical AND, outputs False
print(a or b) # Logical OR, outputs True
print(not a) # Logical NOT, outputs False
Assignment Operators
Used to assign values to variables.
x = 10
x += 5 # Equivalent to x = x + 5, x is now 15
x -= 3 # Equivalent to x = x - 3, x is now 12
x *= 2 # Equivalent to x = x * 2, x is now 24
x /= 4 # Equivalent to x = x / 4, x is now 6.0
x %= 2 # Equivalent to x = x % 2, x is now 0.0
x **= 3 # Equivalent to x = x ** 3, x is now 0.0
x //= 1 # Equivalent to x = x // 1, x is now 0.0
Bitwise Operators
Used to operate on binary representations of integers.
a = 60# Binary of 60 is 0011 1100
b = 13# Binary of 13 is 0000 1101
print(a & b) # Bitwise AND, outputs 12 (0000 1100)
print(a | b) # Bitwise OR, outputs 61 (0011 1101)
print(a ^ b) # Bitwise XOR, outputs 49 (0011 0001)
print(~a) # Bitwise NOT, outputs -61 (1100 0011)
print(a << 2) # Left shift, outputs 240 (1111 0000)
print(a >> 2) # Right shift, outputs 15 (0000 1111)
Membership Operators
Used to test if a value is in a sequence.
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # Outputs True
print("grape" in fruits) # Outputs False
print("grape" not in fruits) # Outputs True
Identity Operators
Used to compare the memory location of two objects.
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # Outputs True because z is a reference to x
print(x is y) # Outputs False because x and y have the same content but different memory locations
print(x == y) # Outputs True because x and y have the same content
Conditional Statements
Conditional statements are used to execute code blocks based on a condition.
if Statement
Executes the code block if the condition is True
.
age = 15
if age < 18:
print("You are a minor.")
if-else Statement
Executes the if
block if the condition is True
, otherwise executes the else
block.
age = 20
if age < 18:
print("You are a minor.")
else:
print("You are an adult.")
if-elif-else Statement
Checks multiple conditions and executes the corresponding block for the first True
condition.
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just turned adult!")
else:
print("You are an adult.")
Loops
Loops are used to repeat code blocks.
for Loop
The for
loop is used to iterate over a sequence (like a list, tuple, or string).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You can also use the range()
function to generate a sequence of numbers:
for i in range(5):
print(i) # Outputs 0 to 4
while Loop
The while
loop repeats a code block as long as the condition is True
.
count = 0
while count < 5:
print(count)
count += 1
Loop Control Statements
- break: Terminates the loop
- continue: Skips the current iteration and proceeds to the next one
- else: Used with loops, executes when the loop terminates normally
for i in range(10):
if i == 5:
break # Loop stops when i equals 5
print(i)
else:
print("Loop ended") # This won't execute because the loop was stopped by break
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
Functions
Functions are reusable blocks of code that can be called by name. They can take arguments and return results.
Defining Functions
Functions are defined using the def
keyword.
def greet(name):
return "Hello, " + name + "!"
Calling a function:
message = greet("Morax Cheng")
print(message) # Outputs "Hello, Morax Cheng!"
Function Parameters
Functions can accept multiple parameters, which can be positional or keyword arguments.
def add(x, y):
return x + y
print(add(3, 5)) # Outputs 8
print(add(y=5, x=3)) # Outputs 8, using keyword arguments
Default parameters:
def greet(name, greeting="Hello"):
return greeting + ", " + name + "!"
print(greet("Morax Cheng")) # Outputs "Hello, Morax Cheng!"
print(greet("Morax Cheng", "Hi")) # Outputs "Hi, Morax Cheng!"
Return Values
Functions can return a value using the return
statement.
def square(x):
return x * x
result = square(5)
print(result) # Outputs 25
Local and Global Variables
Local variables are defined and used within a function, while global variables are defined outside and can be accessed throughout the program.
x = 10 # Global variable
def example():
x = 5 # Local variable
print(x) # Outputs 5
example()
print(x) # Outputs 10
You can modify a global variable inside a function using the global
keyword.
def example():
global x
x = 5
example()
print(x) # Outputs 5
Anonymous Functions
Anonymous functions are defined using the lambda
keyword and are usually used for simple expressions.
square = lambda x: x * x
print(square(5)) # Outputs 25
add = lambda x, y: x + y
print(add(3, 5)) # Outputs 8
Data Structures
Python provides several common data structures for storing and organizing data.
Lists
A list is a mutable, ordered collection of elements.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Access the first element, outputs "apple"
print(fruits[-1]) # Access the last element, outputs "cherry"
fruits[1] = "blueberry" # Modify an element
print(fruits) # Outputs ["apple", "blueberry", "cherry"]
fruits.append("date") # Add an element
print(fruits) # Outputs ["apple", "blueberry", "cherry", "date"]
del fruits[2] # Delete an element
print(fruits) # Outputs ["apple", "blueberry", "date"]
Tuples
A tuple is an immutable, ordered collection of elements.
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Outputs "apple"
# Tuples are immutable, so you cannot modify their elements
# fruits[1] = "blueberry" # This line would cause an error
# But you can reassign the entire tuple
fruits = ("apple", "blueberry", "cherry")
print(fruits) # Outputs ("apple", "blueberry", "cherry")
Sets
A set is an unordered collection of unique elements.
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # Check if an element is in the set, outputs True
fruits.add("date") # Add an element
print(fruits) # Outputs {"apple", "banana", "cherry", "date"}
fruits.remove("banana") # Remove an element
print(fruits) # Outputs {"apple", "cherry", "date"}
Dictionaries
A dictionary is a collection of key-value pairs.
student = {
"name": "Morax Cheng",
"age": 15,
"is_student": True
}
print(student["name"]) # Access a value by its key, outputs "Morax Cheng"
student["age"] = 16 # Modify a value
print(student) # Outputs {"name": "Morax Cheng", "age": 16, "is_student": True}
student["grade"] = "8th" # Add a new key-value pair
print(student) # Outputs {"name": "Morax Cheng", "age": 16, "is_student": True, "grade": "8th"}
del student["is_student"] # Delete a key-value pair
print(student) # Outputs {"name": "Morax Cheng", "age": 16, "grade": "8th"}
File Handling
Python provides rich file handling capabilities.
Reading Files
Use the open()
function to open a file and the read()
method to read its contents.
with open("test.txt", "r") as file:
content = file.read()
print(content)
Writing Files
Use the open()
function in write mode to open a file and the write()
method to write contents.
with open("test.txt", "w") as file:
file.write("Hello, Morax Cheng!")
File Modes
"r"
: Read mode (default)."w"
: Write mode (overwrites the file)."a"
: Append mode (does not overwrite the file)."b"
: Binary mode (e.g.,"rb"
or"wb"
).
with open("test.txt", "a") as file:
file.write("\nThis is an additional line.")
Exception Handling
Python provides exception handling mechanisms to handle runtime errors and prevent program crashes.
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("That's not a valid number!")
except Exception as e:
print("An unexpected error occurred:", e)
else:
print("No errors occurred.")
finally:
print("This will run no matter what.")
Modules and Libraries
Python has a rich standard library that can be imported using the import
statement. Some common modules include:
import math
print(math.sqrt(16)) # Outputs 4.0
print(math.pi) # Outputs 3.141592653589793
Object-Oriented Programming
Python supports Object-Oriented Programming (OOP), which allows the definition of classes and the creation of objects.
Classes and Objects
A class is a blueprint for objects, and an object is an instance of a class.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"My name is {self.name} and I am {self.age} years old."
student = Student("Morax Cheng", 15)
print(student.introduce()) # Outputs "My name is Morax Cheng and I am 15 years old."
Class Attributes and Methods
Class attributes are variables of a class, and methods are functions within a class.
class Circle:
pi = 3.14159 # Class attribute
def __init__(self, radius):
self.radius = radius # Instance attribute
def area(self):
return Circle.pi * self.radius ** 2 # Instance method
circle = Circle(5)
print(circle.area()) # Outputs 78.53975
Inheritance
Inheritance allows one class to inherit the attributes and methods of another class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
dog = Dog("Buddy")
print(dog.speak()) # Outputs "Buddy says Woof!"
Polymorphism
Polymorphism allows different classes to call the same method, resulting in different behaviors.
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
animals = [Dog("Buddy"), Cat("Kitty")]
for animal in animals:
print(animal.speak())
Encapsulation
Encapsulation refers to hiding data and methods within a class, preventing direct access from outside.
class Account:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")
def get_balance(self):
return self.__balance
account = Account(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # Outputs 1300
Common Standard Libraries
Python’s standard library covers a wide range of functionalities. Here are some commonly used libraries:
os
: Operating system interfacesys
: System-specific parameters and functionsdatetime
: Date and time manipulationrandom
: Random number generationre
: Regular expression operationsjson
: JSON data parsing and generationhttp
: HTTP protocol handling
Example: Using the os
Library
import os
current_directory = os.getcwd() # Get the current working directory
print("Current Directory:", current_directory)
files = os.listdir(current_directory) # List files and directories
print("Files:", files)
os.mkdir("new_folder") # Create a new directory
print("Created 'new_folder'")
Example: Using the datetime
Library
import datetime
now = datetime.datetime.now() # Get the current time
print("Current Time:", now)
birthday = datetime.datetime(2008, 12, 4) # Create a date object
print("Birthday:", birthday)
days_lived = (now - birthday).days # Calculate the difference between dates
print(f"You have lived for {days_lived} days.")
Further Learning Resources
To dive deeper into Python, you can refer to the following resources:
- Python Official Documentation: https://docs.python.org/3/
- Codecademy Python Course: https://www.codecademy.com/learn/learn-python-3
- LeetCode: https://leetcode.com/ - Improve your Python programming skills by solving coding challenges.
- Python for Data Science Handbook - A great book covering Python applications in data science.
Conclusion
This tutorial covers the basics of Python programming, providing a comprehensive introduction for beginners. Through practice and exploration, you can master Python and apply it to solve a wide range of practical problems. I hope this tutorial helps you build a solid foundation and start your programming journey!
If you have more programming needs or questions, feel free to continue discussing them.