10 Classic Python Operations: Variables, Type Conversion, Strings, Lists, Loops, Conditionals, Functions, Exceptions, File I/O, and Modules
This article introduces ten essential Python techniques—including variable assignment and swapping, data type conversion, string manipulation, list handling, loop constructs, conditional statements, function definition, exception handling, file operations, and module imports—providing clear explanations and code examples to help beginners strengthen their programming foundation.
Python is a concise and powerful language widely used for data processing, AI, and web development; this tutorial presents ten classic operations to enhance your coding skills.
1. Variable Assignment and Swapping
Assign values with the = operator and swap two variables in a single line using tuple unpacking.
a = 5
b = "Hello, Python!" a = 3
b = 4
a, b = b, a
print(a) # 4
print(b) # 32. Data Type Conversion
Convert between common types using built‑in functions such as int() , float() , str() , and list() .
num_str = "123"
num_int = int(num_str)
print(num_int) # 123 num = 5
num_float = float(num)
print(num_float) # 5.0 num = 42
num_str = str(num)
print(num_str) # "42" string = "python"
string_list = list(string)
print(string_list) # ['p', 'y', 't', 'h', 'o', 'n']3. String Operations
Concatenate strings with + or join() , and format them using format() or f‑strings.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # "Hello World" words = ["Python", "is", "awesome"]
result = " ".join(words)
print(result) # "Python is awesome" name = "Alice"
age = 25
message = "My name is {} and I'm {} years old.".format(name, age)
print(message) name = "Bob"
age = 30
message = f"My name is {name} and I'm {age} years old."
print(message)4. List Operations
Use append() , extend() , indexing, assignment, and slicing to manipulate lists.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # [1, 2, 3, 4] list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
print(list1) # [1, 2, 3, 4] my_list = ["apple", "banana", "cherry"]
print(my_list[1]) # "banana"
my_list[2] = "date"
print(my_list) # ["apple", "banana", "date"] my_list = [1, 2, 3, 4, 5]
sub_list = my_list[1:3]
print(sub_list) # [2, 3]
sub_list = my_list[::2]
print(sub_list) # [1, 3, 5]5. Loop Constructs
Iterate with for loops over iterables or a range, and repeat with while loops.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) for i in range(5):
print(i) count = 0
while count < 3:
print(count)
count += 16. Conditional Statements
Use if‑elif‑else to branch logic, including nested conditions.
num = 10
if num > 0:
print("正数")
elif num == 0:
print("零")
else:
print("负数") age = 18
has_id = True
if age >= 18:
if has_id:
print("可以进入酒吧")
else:
print("请出示身份证")
else:
print("未满18岁,禁止入内")7. Function Definition and Invocation
Define reusable code blocks with def and call them with arguments.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # 88. Exception Handling
Protect code with try‑except to catch runtime errors such as division by zero.
try:
num1 = 10
num2 = 0
result = num1 / num2
except ZeroDivisionError:
print("除数不能为零")9. File Operations
Read and write files using open() with context managers.
try:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到") with open('output.txt', 'w') as file:
file.write("Hello, this is a new line.") with open('output.txt', 'a') as file:
file.write("\nThis is an appended line.")10. Module Import
Leverage standard and third‑party libraries by importing them.
import math
result = math.sqrt(16)
print(result) # 4.0 from datetime import datetime
now = datetime.now()
print(now)By mastering these ten classic Python operations, you lay a solid foundation for more advanced programming tasks and can confidently apply these techniques to solve real‑world problems.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.