The Six Core Advantages of Learning Python
Simple and Easy-to-Learn SyntaxThe syntax of Python is close to English, and the code structure is clear. Code blocks can be defined through indentation, significantly lowering the learning threshold. For example, a “Hello World” program can be implemented in just one line of code, while other languages require more complex structures.
Cross-Domain Multi-Scenario ApplicationsFrom data processing to artificial intelligence, Python covers almost all technical fields. It can efficiently handle data, scrape information, or develop tools in finance, operations, and scientific research. In machine learning and web development, it can also quickly build complex systems through rich frameworks (such as TensorFlow and Django).
Rich Resource EcosystemPython has a large number of third-party libraries (such as NumPy and Pandas) and an active open-source community, providing ready-made solutions that significantly enhance development efficiency. When encountering problems, support can be quickly obtained through the community.
Efficient Development and AutomationIts simplicity allows developers to achieve complex functionalities with less code. For example, basic game development can be completed in two days. At the same time, Python excels at scripting, automating repetitive tasks (such as file management and testing processes).
Strong Career CompetitivenessPython is widely used in high-paying fields (such as data science and AI), and the demand for related skills in companies continues to grow. Mastering Python can bring job seekers more opportunities and salary advantages.
Cross-Platform and ScalabilityPython code can run seamlessly on systems like Windows and Linux and supports integration with languages like C and Java, meeting the needs of complex projects.
Continuation from the previous part: Essential Python Commands for Beginners (Part 1)Eleven, Exiting the Program
Use exit() to terminate the program:
print("Program starts")
exit() # The program stops here and will not execute subsequent code
print("This line of code will not be executed") # This line of code will not be executed
Use sys.exit() and pass a status code:
import sys
print("Attempting to exit normally...")
sys.exit(0) # Exit with status code 0, indicating normal termination [ty-reference](1)
Using sys.exit() in a function to handle error situations:
import sys
def divide(a, b):
if b == 0:
print("The divisor cannot be zero")
sys.exit(1) # Error exit, status code is 1 [ty-reference](1)
return a / b
result = divide(10, 0)
Using sys.exit() in conjunction with exception handling:
import sys
try:
raise ValueError("Trigger a value error")
except ValueError:
print("Exception caught, preparing to exit the program")
sys.exit(2) # Choose a different exit status code based on the exception type [ty-reference](1)
Using exit() in conditional statements:
user_input = input("Please enter 'y' to continue:")
if user_input != 'y':
print("User decided to exit")
exit() # If the user decides not to continue, exit the program
print("Continuing to execute the program...") # This will only execute if the user enters 'y'
Twelve, Mathematical Operators
Addition:
a = 5
b = 3
print(f"{a} + {b} = {a + b}") # Output: 5 + 3 = 8
Subtraction:
a = 10
b = 4
print(f"{a} - {b} = {a - b}") # Output: 10 - 4 = 6
Multiplication:
a = 7
b = 6
print(f"{a} * {b} = {a * b}") # Output: 7 * 6 = 42
Division:
a = 9
b = 2
print(f"{a} / {b} = {a / b}") # Output: 9 / 2 = 4.5
Integer Division and Modulus:
a = 11
b = 3
print(f"{a} // {b} = {a // b}, {a} % {b} = {a % b}") # Output: 11 // 3 = 3, 11 % 3 = 2
Thirteen, Logical Operators
Using and for conditional judgment:
age = 20
has_license = True
if age >= 18 and has_license:
print("Can legally drive") # This message outputs when age is 18 or older and has a license
Using or for conditional judgment:
is_student = False
has_discount_card = True
if is_student or has_discount_card:
print("Can enjoy discounts") # Students or those with discount cards can enjoy discounts
Using not to negate a boolean value:
raining = False
if not raining:
print("The weather is nice, suitable for going out") # If it is not raining, it is suitable for going out
Combining logical operators:
temperature = 22
humidity = 70
if temperature > 20 and humidity < 80:
print("Pleasant climate") # Pleasant climate when temperature is above 20 and humidity is below 80
Using logical operators in loops:
for i in range(1, 11):
if i % 2 == 0 and i % 3 == 0:
print(f"{i} is divisible by both 2 and 3") # Print numbers divisible by both 2 and 3
Fourteen, Identity Operators
Using is to check object identity:
x = ["apple", "banana"]
y = x
print(x is y) # Output: True, because x and y reference the same list object
Using is not to check different objects:
x = ["apple", "banana"]
z = ["apple", "banana"]
print(x is not z) # Output: True, although the contents are the same, they are two different objects
Combining id() function to verify identity operators:
x = [1, 2, 3]
y = x
print(id(x), id(y)) # Output the same memory address
print(x is y) # Output: True
Using identity operators in conditional judgments:
a = None
b = None
if a is b:
print("Both a and b are None, or reference the same object") # Output: Both a and b are None, or reference the same object
Comparing the difference between == and is:
x = [1, 2, 3]
y = list(x) # Create a new list with the same content as x
print(x == y) # Output: True, because their contents are equal
print(x is y) # Output: False, because they are not the same object
Fifteen, Membership Operators
Using in to check if an element is in a sequence:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the fruit list") # Output: Banana is in the fruit list
Using not in to check if an element is not in a sequence:
fruits = ["apple", "banana", "cherry"]
if "orange" not in fruits:
print("Orange is not in the fruit list") # Output: Orange is not in the fruit list
Using membership operators in loops:
for fruit in ["apple", "banana", "cherry"]:
if fruit in ["banana", "cherry"]:
print(f"{fruit} is one of my favorite fruits") # Output favorite fruits
Finding characters in strings:
sentence = "Hello, world!"
if "world" in sentence:
print("Found the word 'world'") # Output: Found the word 'world'
Checking key existence in a dictionary:
student_scores = {"Alice": 90, "Bob": 85}
if "Alice" in student_scores:
print(f"Alice's score is {student_scores['Alice']}") # Output: Alice's score is 90
Sixteen, Length Operations: len()
Calculating string length:
text = "Hello, World!"
print(f"The length of the string '{text}' is {len(text)}") # Output: The length of the string 'Hello, World!' is 13
Counting elements in a list:
numbers = [1, 2, 3, 4, 5]
print(f"The list {numbers} contains {len(numbers)} elements") # Output: The list [1, 2, 3, 4, 5] contains 5 elements
Tuple size:
fruits = ("apple", "banana", "cherry")
print(f"The size of the tuple {fruits} is {len(fruits)}") # Output: The size of the tuple ('apple', 'banana', 'cherry') is 3
Number of key-value pairs in a dictionary:
person = {"name": "Alice", "age": 25, "city": "New York"}
print(f"There are {len(person)} pairs of key-value in the dictionary") # Output: There are 3 pairs of key-value in the dictionary
Counting elements in a set:
unique_numbers = {1, 2, 2, 3, 4, 4, 5}
print(f"The set {unique_numbers} contains {len(unique_numbers)} unique elements") # Output: The set {1, 2, 3, 4, 5} contains 5 unique elements
Seventeen, Range Generator: range()
Printing numbers from 0 to 4:
for i in range(5):
print(i) # Output: 0 1 2 3 4
Printing even numbers from 1 to 10:
for i in range(2, 11, 2):
print(i) # Output: 2 4 6 8 10
Printing numbers from 9 to 0 in reverse:
for i in range(9, -1, -1):
print(i) # Output: 9 8 7 6 5 4 3 2 1 0
Creating a list using range():
numbers_list = list(range(1, 6))
print(f"The created list is {numbers_list}") # Output: The created list is [1, 2, 3, 4, 5]
Iterating a list using len() and range():
items = ["apple", "banana", "cherry"]
for i in range(len(items)):
print(f"The {i+1} item is {items[i]}") # Output: The 1 item is apple The 2 item is banana The 3 item is cherry
Eighteen, Slicing Operations
Extracting a part of a list:
my_list = [0, 1, 2, 3, 4, 5]
slice_of_list = my_list[1:4]
print(f"The sliced list is {slice_of_list}") # Output: The sliced list is [1, 2, 3]
Using negative indexing for slicing:
my_string = "Python"
reversed_slice = my_string[-3:]
print(f"The slicing result is {reversed_slice}") # Output: The slicing result is hon
Slicing with a step of 2:
my_tuple = (0, 1, 2, 3, 4, 5)
even_elements = my_tuple[::2]
print(f"The result extracted every other element is {even_elements}") # Output: The result extracted every other element is (0, 2, 4)
Completely reversing a sequence:
sequence = "abcdef"
reversed_sequence = sequence[::-1]
print(f"The reversed sequence is {reversed_sequence}") # Output: The reversed sequence is fedcba
Using slicing to update parts of a list:
letters = ['a', 'b', 'c', 'd', 'e']
letters[1:4] = ['B', 'C', 'D']
print(f"The updated list is {letters}") # Output: The updated list is ['a', 'B', 'C', 'D', 'e']
Nineteen, List Comprehensions
Creating a list of squares:
squares = [x**2 for x in range(1, 6)]
print(f"The list of squares is {squares}") # Output: The list of squares is [1, 4, 9, 16, 25]
Filtering even numbers:
even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print(f"The list of even numbers is {even_numbers}") # Output: The list of even numbers is [2, 4, 6, 8, 10]
Converting strings to uppercase:
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(f"The list of uppercase words is {upper_words}") # Output: The list of uppercase words is ['HELLO', 'WORLD', 'PYTHON']
Generating Cartesian products:
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
print(f"The list of Cartesian products is {pairs}") # Output: The list of Cartesian products is [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
Filtering and transforming based on conditions:
mixed_data = [0, "apple", 1, "banana", 2, None, 3, ""]
filtered_data = [item for item in mixed_data if isinstance(item, int) and item > 0]
print(f"The filtered and transformed data is {filtered_data}") # Output: The filtered and transformed data is [1, 2, 3]
Twenty, Tuple Definition
Defining a simple tuple:
simple_tuple = (1, 2, 3)
print(f"The simple tuple is {simple_tuple}") # Output: The simple tuple is (1, 2, 3)
Single-element tuples need a trailing comma:
single_element_tuple = (42,)
print(f"The single-element tuple is {single_element_tuple}") # Output: The single-element tuple is (42,)
Tuple unpacking:
coordinates = (10, 20)
x, y = coordinates
print(f"x coordinate is {x}, y coordinate is {y}") # Output: x coordinate is 10, y coordinate is 20
Immutability example:
immutable_tuple = (1, 2, 3)
try:
immutable_tuple[0] = 4 # Attempting to modify an element in the tuple will cause an error
except TypeError as e:
print(f"Error message: {e}") # Output: Error message: 'tuple' object does not support item assignment
Using tuples as dictionary keys:
student_scores = {(1, "Alice"): 90, (2, "Bob"): 85}
print(f"Alice's score is {student_scores[(1, 'Alice')]}") # Output: Alice's score is 90
Twenty-One, Dictionary Definition: Using curly braces {} to define key-value structure dictionaries
Creating a simple dictionary:
person = {"name": "Alice", "age": 25}
print(f"Dictionary content: {person}") # Output: Dictionary content: {'name': 'Alice', 'age': 25}
Using dict() constructor to create a dictionary:
book = dict(title="Python Programming", author="Zhang San")
print(f"Book information: {book}") # Output: Book information: {'title': 'Python Programming', 'author': 'Zhang San'}
Creating a dictionary with lists as values:
shopping_list = {"fruits": ["apple", "banana"], "vegetables": ["carrot", "lettuce"]}
print(f"Shopping list: {shopping_list}") # Output: Shopping list: {'fruits': ['apple', 'banana'], 'vegetables': ['carrot', 'lettuce']}
Creating an empty dictionary and dynamically adding key-value pairs:
empty_dict = {}
empty_dict["country"] = "China"
print(f"Country information: {empty_dict}") # Output: Country information: {'country': 'China'}
Creating a dictionary with the same values:
default_values = {}.fromkeys(['height', 'width'], 0)
print(f"Default dimensions: {default_values}") # Output: Default dimensions: {'height': 0, 'width': 0}
Twenty-Two, Dictionary Operations: Using methods like get(), pop(), update() to manipulate data in dictionaries
Using get() method to retrieve values from a dictionary:
user_info = {"name": "Li Si", "email": "[email protected]"}
email = user_info.get("email", "No email information")
print(f"User email: {email}") # Output: User email: [email protected]
Using pop() method to remove and return the value of a specified key:
scores = {"math": 90, "english": 85}
math_score = scores.pop("math")
print(f"Math score removed: {math_score}") # Output: Math score removed: 90
Using update() method to merge two dictionaries:
first_half = {"Q1": 100, "Q2": 200}
second_half = {"Q3": 300, "Q4": 400}
first_half.update(second_half)
print(f"Annual performance: {first_half}") # Output: Annual performance: {'Q1': 100, 'Q2': 200, 'Q3': 300, 'Q4': 400}
Clearing all entries in a dictionary:
inventory = {"apples": 30, "bananas": 45}
inventory.clear()
print(f"Inventory after clearing: {inventory}") # Output: Inventory after clearing: {}
Checking if a specific key exists in a dictionary:
settings = {"theme": "dark", "language": "en"}
has_theme = "theme" in settings
print(f"Is there a theme setting: {has_theme}") # Output: Is there a theme setting: True
Twenty-Three, File Operations: open(), read(), write() and other methods for handling file reading and writing
Opening a file and reading its content:
with open('example.txt', 'r') as file:
content = file.read()
print(f"File content: {content}")
Writing text to a file:
with open('output.txt', 'w') as file:
file.write("This is a test file.")
print("Write completed")
Appending text to the end of a file:
with open('output.txt', 'a') as file:
file.write("\nThis is the appended content.")
print("Append completed")
Reading file content line by line:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # Remove newline characters at the end of each line
Using with statement to open multiple files for reading and writing:
with open('source.txt', 'r') as src, open('destination.txt', 'w') as dest:
content = src.read()
dest.write(content)
print("Copy completed")
Twenty-Four, Exception Handling: Using try…except…finally structure to capture and handle exceptions
Handling file not found exceptions:
try:
with open('nonexistent_file.txt', 'r') as f:
content = f.read()
except FileNotFoundError as e:
print(f"Error: {e}")
finally:
print("This code will execute regardless of whether an exception occurs")
Handling numeric conversion errors:
try:
number = int("abc")
except ValueError as e:
print(f"Error: {e}")
Handling multiple exceptions:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Division by zero error: {e}")
except Exception as e:
print(f"Other error: {e}")
Using else clause to execute code when no exceptions occur:
try:
number = int("123")
except ValueError:
print("Input is not a valid integer")
else:
print(f"Successfully converted to integer: {number}")
Using exception handling in functions:
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("The divisor cannot be zero")
return None
result = divide(10, 0)
if result is not None:
print(f"Result is: {result}")
Twenty-Five, Module Importing: import or from … import … to import functionalities of other modules into the current script
Importing an entire module:
import math
print(f"Pi: {math.pi}") # Output: Pi: 3.141592653589793
Importing specific functionalities from a module:
from datetime import datetime
current_time = datetime.now()
print(f"Current time: {current_time}") # Output: Current time: 2025-02-06 14:16:00.123456
Simplifying module references using aliases:
import numpy as np
array = np.array([1, 2, 3])
print(f"Array: {array}") # Output: Array: [1 2 3]
Importing all functionalities from a module (not recommended):
from os.path import *
print(f"Current working directory: {getcwd()}") # Output: Current working directory: /path/to/current/working/directory
Dynamically importing modules:
import importlib
json_module = importlib.import_module('json')
data = json_module.dumps({"key": "value"})
print(f"JSON string: {data}") # Output: JSON string: {"key": "value"}
The Significance of Persevering in Learning
Learning Python is not only about mastering a tool but also embracing a future way of thinking. With the rapid development of artificial intelligence and big data technologies, Python will continue to be synonymous with innovation and efficiency. Through continuous practice on projects and participating in community exchanges, you will find a dual enhancement of programming skills and problem-solving perspectives. Just as code needs iterative optimization, the learning journey also requires perseverance – every line of code accumulated will ultimately forge a transformation from beginner to expert. Stay curious, keep exploring, and let Python be the key to unlocking infinite possibilities.
Essential Python Commands for Beginners (Part 1)
The first batch of testers using DeepSeek hit the jackpot! The missed test rate dropped by 83%, and efficiency soared by 5 times!
Super detailed, DeepSeek integrated with PyCharm for AI programming! (Supports local deployment of DeepSeek and official DeepSeek integration), recommended for collection!
All you need to know about common configuration file writing for Python, this comprehensive guide is a must-read!
Knowledge about redis that software testing engineers need to know…
ClaimFull-Stack Software Testing EngineerLearning MaterialsAdd the editor’s WeChat below with the note “Materials”
People who love sharing won’t have too much bad luck