Python Basics: Syntax, Data Types, Control Flow, Functions, Modules, I/O, and Common Libraries
This comprehensive guide introduces Python fundamentals, covering file encoding declarations, shebang usage, quicksort implementation, script entry checks with __name__, printing differences between Python 2 and 3, pretty‑printing, module and package structures, control flow statements, data types, string operations, regular expressions, collections, dictionary handling, functional tools, generators, decorators, class definitions, property management, exception handling, unit testing, file and path manipulation, JSON/XML processing, Excel interaction, file system utilities, network requests, and MySQL database access.
Python is a high‑level, dynamically typed, multi‑paradigm language. When creating a script you often start by declaring the file encoding:
# 指定脚本调用方式
#!/usr/bin/env python
# 配置 utf-8 编码
# -*- coding: utf-8 -*-
# 配置其他编码
# -*- coding: <encoding-name> -*-
# Vim 中还可以使用如下方式
# vim:fileencoding=<encoding-name>A concise quicksort implementation demonstrates Python's expressive syntax compared to Java:
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) / 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print quicksort([3,6,8,10,1,2,1])
# Prints "[1, 1, 2, 3, 6, 8, 10]"Use the __name__ variable to distinguish direct script execution from import, and the fire library to turn a class into a command‑line tool:
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
# python calculator.py double 10 # 20
# python calculator.py double --number=15 # 30Printing is a statement in Python 2 and a function in Python 3; to use the function form in Python 2 import it from __future__ :
from __future__ import print_functionThe pprint module can format console output nicely:
import pprint
stuff = ['spam','eggs','lumberjack','knights','ni']
pprint.pprint(stuff)
pp = pprint.PrettyPrinter(depth=6)
tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',('parrot', ('fresh fruit',)))))))
pp.pprint(tup)Modules are plain .py files; packages are directories containing an __init__.py file. Example directory layout and import styles:
# 文件目录
someDir/
main.py
siblingModule.py
# siblingModule.py
def siblingModuleFun():
print('Hello from siblingModuleFun')
def siblingModuleFunTwo():
print('Hello from siblingModuleFunTwo')
import siblingModule
import siblingModule as sibMod
sibMod.siblingModuleFun()
from siblingModule import siblingModuleFun
siblingModuleFun()
try:
import someModuleA # Windows‑only
except ImportError:
try:
import someModuleB # Linux‑only
except ImportError:
passControl flow uses if , elif , else and supports the ternary operator:
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
else:
print('More')
a if condition else bLooping constructs include for over iterables, range , and enumeration for index access:
words = ['cat','window','defenestrate']
for w in words:
print(w, len(w))
for i in range(len(a)):
print(i, a[i])
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx+1, animal))Basic data types include integers, floats, booleans, and strings. Type conversion functions are int() , float() , and str() . String slicing, formatting, and common methods are demonstrated:
x = 3
print(type(x)) # <type 'int'>
print(x + 1) # 4
y = 2.5
print(type(y)) # <type 'float'>
print(y * 2) # 5.0
t = True
f = False
print(t and f) # False
print(t or f) # True
print(not t) # False
var1 = 'Hello World!'
print('var1[0]:', var1[0])
print('var2[1:5]:', var2[1:5])
print('My name is %s and weight is %d kg!' % ('Zara', 21))Regular expressions are handled with the re module for matching, substitution, and compilation:
import re
re.match(r'^[aeiou]', string)
re.sub(r'^[aeiou]', '?', string)
expr = re.compile(r'^...$')
expr.match(...)Collections include lists, sets, frozensets, and dictionaries. List creation, appending, extending, slicing, and removal are shown, as well as dictionary creation, merging, and safe access with get :
l = []
l = list()
str.split('.')
list1 = ['1','2','3']
str1 = ''.join(list1)
x = [1,2,3]
x.append([4,5])
x.extend([4,5])
myList.pop(1)
myList.pop()
myList[2:4] = [8,9]
d = {'cat':'cute','dog':'furry'}
print(d['cat'])
print(d.get('monkey','N/A'))
z = {**x, **y} # Python 3.5 dict mergeFunctional tools such as map , reduce , and filter are illustrated, along with generator functions and the yield keyword:
items = [1,2,3,4,5]
squared = list(map(lambda x: x**2, items))
from functools import reduce
product = reduce(lambda x,y: x*y, [1,2,3,4])
number_list = range(-5,5)
less_than_zero = list(filter(lambda x: x<0, number_list))
def simple_generator_function():
yield 1
yield 2
yield 3Decorators are demonstrated with and without arguments, preserving function metadata using functools.wraps :
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('wrap function')
return func(*args, **kwargs)
return wrapper
@decorator
def example(*a, **kw):
passClass definitions include constructors, instance methods, class methods, static methods, properties, and error‑checking setters:
class Greeter(object):
def __init__(self, name):
self.name = name
def greet(self, loud=False):
if loud:
print('HELLO, %s!' % self.name.upper())
else:
print('Hello, %s' % self.name)
g = Greeter('Fred')
g.greet()
g.greet(loud=True)
class Example(object):
def __init__(self, value):
self._val = value
@property
def val(self):
return self._val
@val.setter
def val(self, value):
if not isinstance(value, int):
raise TypeError('Expected int')
self._val = valueException handling uses try/except blocks, and unit testing is performed with the unittest framework:
try:
1/0
except ZeroDivisionError as e:
print(e)
import unittest
class TestFib(unittest.TestCase):
def setUp(self):
self.n = 10
def test_fib(self):
self.assertEqual(fib(self.n), 55)
if __name__ == '__main__':
unittest.main()File I/O uses the with statement for automatic resource management, and path handling relies on os.path utilities:
with open('file.dat','w') as f:
f.write('data')
dir = os.path.dirname(__file__)
abs_path = os.path.abspath(os.path.dirname(__file__))JSON serialization is done with the json module, while XML parsing and manipulation use lxml.etree with XPath support:
import json
with open('data.json','w') as f:
json.dump(data, f)
with open('data.json','r') as f:
data = json.load(f)
from lxml import etree
root = etree.fromstring('<a xmlns="test"><b/></a>')
for tag in root.iter():
print(tag.tag, tag.text)Excel files can be read with xlrd and written with xlsxwriter :
sh.cell(rx, col).value
workbook = xlsxwriter.Workbook('out.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write(row, col, data)
workbook.close()High‑level file operations use shutil , network requests are performed with the requests library, and MySQL access is demonstrated via pymysql :
import shutil
shutil.rmtree('appName')
import requests
r = requests.get('https://api.github.com/events')
print(r.status_code)
import pymysql.cursors
connection = pymysql.connect(host='localhost',user='user',password='passwd',db='db',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`email`,`password`) VALUES (%s,%s)"
cursor.execute(sql, ('[email protected]','very-secret'))
connection.commit()Overall, this material provides a thorough introduction to Python programming fundamentals and common libraries for everyday development tasks.
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.