Python速记(语法总结)

Python是一门简单的编程语言,基本上看过一遍语法就能轻松上手。但是任何语言长时间不用都会忘记,本文是笔者在重拾Python Crash Course时对Python关键语法规则的快速笔记,适合Python入门或者有意重启Python的其他语言常用者。

Contents

Python之禅
字符串 Strings
数字 Numbers (integers and floats)
列表 Lists
if statements
字典 Dictionaries
用户输入和while循环 User input and while loops
函数 Functions
类 Classes
文件 Files
异常 Exceptions

Python代码风格指南 PEP 8 – Style Guide for Python Code

Python之禅

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

字符串 Strings

  1. 字符串就是一系列字符。在Python中,用引号括起的都是字符串,可以是单引号,也可以是双引号( single or double quotes)
  2. 使用方法修改字符串的大小写 Changing Case in a String with Methods
name = "ada lovelace"

# emthods
print(name.title())
print(name.lower())
print(name.upper())
print(name)

# output (value of name is not actually changed by these methods)
Ada Lovelace
ada lovelace
ADA LOVELACE
ada lovelace
  1. 通过加号合并或拼接字符串 Combining or Concatenating Strings by “+” operation
  2. 使用制表符或换行符来添加空白 Adding Whitespace to Strings with Tabs(“\t”) or Newlines(“\n”)
>>>print("Python")
Python 

>>>print("\tPython")
 Python 

>>>print("Languages:\nPython\nC\nJavaScript") 
Languages: 
Python
C 
JavaScript
  1. 删除空白 Stripping Whitespace by methods “rstrip()” for the right side or “lstrip()” for the left side or “strip()” for both sides
  2. Use str() to convert integer to string

数字 Numbers (integers and floats)

  1. For python2 you have to explicitly use float type as one of the operands to get the float type of output.
>>>3/2
1.5 # python3 output
1 # python2 output

>>>3.0/2
1.5 # same output for python3 and python2 

列表 Lists

By accessing index -1 to get the last item in a list.
Method append() for appending elements to the end of a list.
Method insert() for insert elements into a list.
Statement del for removing an item.
Method pop() for removing an item. pop() 默认弹出列表的最后一个元素, pop(index)弹出指定index的元素(且可以用一个新的变量接住这个元素)
Method remove() for removing an item by value.
Method sort() for sorting a list permanently.
Function sorted() for sorting a list temporarily.
Method reverse() for reversing the order of a list permanently.
Function len() for find the length of a list.

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles) #output: ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0]) #output: trek
print(bicycles[0].title()) #output: Trek
print(bicycles[3]) #output: specialized
print(bicycles[-1]) #output: specialized

# Modifying Elements in a List
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles) #output: ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles) #output: ['ducati', 'yamaha', 'suzuki']

# Appending Elements to the End of a List
motorcycles = [] 
motorcycles.append('honda') 
motorcycles.append('yamaha') 
motorcycles.append('suzuki') 
print(motorcycles) #output: ['honda', 'yamaha', 'suzuki']

# Inserting Elements into a List
motorcycles = ['honda', 'yamaha', 'suzuki'] 
motorcycles.insert(0, 'ducati')
print(motorcycles) #output: ['ducati', 'honda', 'yamaha', 'suzuki']

# Removing an Item Using the del Statement
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[1] 
print(motorcycles) #output: ['honda', 'suzuki']

# Removing an Item Using the pop() Method
motorcycles = ['honda', 'yamaha', 'suzuki']
popped_motorcycle = motorcycles.pop() 
print(motorcycles) #output: ['honda', 'yamaha']
print(popped_motorcycle) #output: suzuki
first_owned = motorcycles.pop(0) # = honda

# Removing an Item by Value
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
motorcycles.remove('ducati')
print(motorcycles) #output: ['honda', 'yamaha', 'suzuki']

# Sorting a List Permanently with the sort() Method
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars) #output: ['audi', 'bmw', 'subaru', 'toyota']

# Sorting a List Temporarily with the sorted() Function
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars) #output: ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars)) #output: ['audi', 'bmw', 'subaru', 'toyota']
print(cars) #output: ['bmw', 'audi', 'toyota', 'subaru']

# Printing a List in Reverse Order
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars) #output: ['subaru', 'toyota', 'audi', 'bmw']

# Finding the Length of a List
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars) #output: 4

操作列表

  1. for循环: Looping Through an Entire List by “for” statement
  • 避免缩进错误:Python uses indentation to determine when one line of code is connected to the line above it. So do not forget to indent, and do not indent unnecessarily. (PEP 8 recommends that you use four spaces per indentation level. https://python.org/dev/peps/pep-0008/)
  • 勿漏冒号: do not forget colon
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
	print(magician)

# output
alice 
david 
carolina
  1. Making Numerical Lists by range() function
for value in range(1,5):
 print(value)

# output
1
2
3
4

# Using range() to Make a List of Numbers
numbers = list(range(1,6))
print(numbers)

#output
[1, 2, 3, 4, 5]
  1. min(), max(), sum() functions
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
  1. 列表解析 List Comprehensions
squares = [value**2 for value in range(1,11)]
print(squares)

#output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  1. 切片 Slicing a List: To make a slice, you specify the index of the first and last elements you want to work with. The last index is not included.
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[0:3]) #output: ['charles', 'martina', 'michael']
print(players[:3]) #output: ['charles', 'martina', 'michael']
print(players[:]) #output: ['charles', 'martina', 'michael', 'florence', 'eli'] 

#Looping Through a Slice
for player in players[:3]
   print(player)
   
#Copying a List
copied_players = players[:]

#below both variables point to the same list: player
copied_players = players
  1. 元组 Tuple:
  • An immutable(cannot change) list is called a tuple A tuple looks just like a list except you use parentheses instead of square brackets.
  • 复写一个元组变量 Writing over a Tuple: Although you can’t modify a tuple, you can assign a new value to a variable
    that holds a tuple
dimensions = (200, 50)
print(dimensions[0]) #output: 200
print(dimensions[1]) #output: 50

#looping an tuple
for dimension in dimensions:
   print(dimension)

#Writing over a Tuple
dimensions = (200, 50)
dimensions = (400, 100)
for dimension in dimensions:
   print(dimension)

#output
400 
100

if statements

  • keywords:
    if,
    and, or,
    in, not in,
    ==, !=
    True, False
    if-else
    if-elif-else

  • Check if a list is empty or not by checking the list name

if statement :
	# do something

if statement1 and statement2 :
	# do something

if statement1 or statement2 :
	# do something

# Checking Whether a Value Is in a List (in, not in)
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
	print(user.title() + ", you can post a response if you wish.")
if user in banned_users:
	print(user.title() + ", you cannot post a response.")

# Boolean Expressions (True, False)
game_active = True
can_edit = False

# if-else statements
age = 17
if age >= 18:
	print("You are old enough to vote!")
	print("Have you registered to vote yet?")
else:
	print("Sorry, you are too young to vote.")
	print("Please register to vote as soon as you turn 18!")

# if-elif-else chain
age = 12
if age < 4:
	print("Your admission cost is $0.")
elif age < 18:
	print("Your admission cost is $5.")
else:
	print("Your admission cost is $10.")

# Check if a list is empty or not by checking the list name
requested_toppings = []
if requested_toppings:
	for requested_topping in requested_toppings:
		print("Adding " + requested_topping + ".")
		print("\nFinished making your pizza!")
else:
	print("Are you sure you want a plain pizza?")

字典 Dictionaries

  1. 字典是一系列键—值对。A dictionary in Python is a collection of key-value pairs
  2. 字典用大括号{}。In Python, a dictionary is wrapped in braces, {}
  3. 回顾:列表list用中括号[], 元组Tuple用小括号(), 字典用大括号{}.
  4. Removing key-value pairs by del statement
  5. 遍历所有的键值对 Looping through all key-value pairs: for k,v in dictionary.item()
  6. 遍历所有的键 Looping through all the keys: for k in dictionary.keys()
  7. 遍历所有的键 Looping through all the values: for v in dictionary.values()
  8. 列表与字典之间的嵌套,Nesting:you can create a list of dictionaries, a dictionary with a list or lists inside, or a dictionary with a dictionary or dictionaries inside.
# Accessing Values in a Dictionary
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])

# Adding New Key-Value Pairs
alien_0 = {'color': 'green', 'points': 5}
print(alien_0) #output: {'color': 'green', 'points': 5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0) #output: {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

# Starting with an Empty Dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5

# Modifying Values in a Dictionary
alien_0 = {'color': 'green'}
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".") #output: The alien is now yellow.

# Removing Key-Value Pairs
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0) #output: {'color': 'green'}

# Looping Through All Key-Value Pairs
user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'fermi',
	}
for key, value in user_0.items():
	print("\nKey: " + key)
	print("Value: " + value)
#output

Key: last
Value: fermi

Key: first
Value: enrico

Key: username
Value: efermi

# Looping through all the keys
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}
for name in favorite_languages.keys():
	print(name.title())
#output
Jen
Sarah
Phil
Edward

# Looping Through All Values in a Dictionary
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}
for language in favorite_languages.values():
	print(language.title())
#output
Python 
C 
Python 
Ruby


# A Dictionary in a Dictionary
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },
    }
for username, user_info in users.items():
    print(f"\nUsername: {username}")
    full_name = f"{user_info['first']} {user_info['last']}"
    location = user_info['location']
    print(f"\tFull name: {full_name.title()}")
    print(f"\tLocation: {location.title()}")

#output
Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton

Username: mcurie
        Full name: Marie Curie
        Location: Paris

用户输入和while循环 User input and while loops

  1. The input() function pauses your program and waits for the user to enter some text.
  2. When you use the input() function, Python interprets everything the user enters as a string.
  3. The int() function converts a string representation of a number to a numerical representation.
  4. while loops (break and continue statements can be used in while loops)
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

#output:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

函数 Functions

  1. Define a function by def statement. return statement is also supported
  2. Modifying a List in a Function. When you pass a list to a function, the function can modify the list. Any changes made to the list inside the function’s body are permanent.
  3. Preventing a Function from Modifying a List by passing in a copy of a list (saying list[:]) to a function. (For the sake of saving time and memory, you should avoid using the cpoy of a list as the function input)
  4. 传递任意数量的实参 Passing an Arbitrary Number of Arguments by defining the function with the form of argument: *argument (Python will create an empty tuple). If you want a function to accept several different kinds of arguments, the parameter that accepts an arbitrary number of arguments must be placed last in the function definition.
  5. Storing Your Functions in Modules. Define function(s) in separate file(s) and import the file(s) or called module(s) by Python import statement. And then you can use below syntax to use the function of that module: module_name.function_name()
  6. You can also import specific funtions by syntax: from module_name import function_name. Thereafter you can use that function without using module_name.
  7. Using as to Give a Function an Alias. from module_name import function_name as fn
  8. Importing All Functions in a Module. from module_name import *. Better not to do this to avoid unexpected results like same name issue.
# def describe_pet(pet_name, animal_type):
# define a function with default values for each parameter
def describe_pet(pet_name, animal_type='dog'):
    """Display information about a pet."""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(pet_name='willie')
# use keyword arguments( name-value pairs) when calling the func
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

#output:

I have a dog.
My dog's name is Willie.

I have a hamster.
My hamster's name is Harry.

I have a hamster.
My hamster's name is Harry.

# Passing an Arbitrary Number of Arguments
def make_pizza(size, *toppings):
    """Summarize the pizza we are about to make."""
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

# output:

Storing the functions in modules

# e.g. if there is pizza.py module containing make_pizza() function
# import module_name
import pizza
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

# from module_name import function_name
from pizza import make_pizza
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

# from module_name import function_name as fn
from pizza import make_pizza as mp
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

# Importing All Functions in a Module
from pizza import *
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

类 Classes

# define a class
class Dog():
"""A simple attempt to model a dog.""" 
 
def __init__(self, name, age):
"""Initialize name and age attributes."""
	self.name = name # attribute
	self.age = age # attribute
 
def sit(self):
 """Simulate a dog sitting in response to a command."""
 	print(self.name.title() + " is now sitting.")
 	
 def roll_over(self):
 """Simulate rolling over in response to a command."""
 	print(self.name.title() + " rolled over!")

# making an instance from a class, accessing attributes, and call the methods
my_dog = Dog('willie', 6)
print(my_dog.name)
my_dog.sit()
my_dog.roll_over()
  1. self. The self parameter is required in the method definition and must come first before the other parameters. When Python calls this __init__() method later (to create an instance of Dog), the method call will automatically pass the self argument. Every method call associated with a class automatically passes self, which is a reference(引用) to the instance(实例) itself; it gives the individual instance access to the attributes and methods in the class.
  2. 属性 Variables that are accessible through instances like this are called attributes.
  3. You can also setting a default value for an attribute.
  4. Modifying the value of attributes by method (is much safer).
  5. 类的继承 Inheritance. class ChildClassname(ParentClassname):
  6. The super() function is a special function that helps Python make connections between the parent and child class. It tells Python to call the __init__() method from parent class, which gives an instance of child class all the attributes of its parent class. The name super comes from a convention of calling the parent class a superclass(超类) and the child class a subclass.
  7. Class的编码风格:Class names should be written in CamelCaps(驼峰命名法). To do this, capitalize the first letter of each word(大驼峰命名法) in the name, and don’t use underscores. Instance and module names should be written in lowercase with underscores between
    words.
# define a superclass Car
 class Car():
 """A simple attempt to represent a car."""
 def __init__(self, make, model, year):
	self.make = make
	self.model = model
	self.year = year
	self.odometer_reading = 0
 
 def get_descriptive_name(self):
	long_name = str(self.year) + ' ' + self.make + ' ' + self.model
	return long_name.title()
 
 def update_odometer(self, mileage):
	if mileage >= self.odometer_reading:
		self.odometer_reading = mileage
	else:
		print("You can't roll back an odometer!")
 
 def increment_odometer(self, miles):
 	self.odometer_reading += miles
 	
def fill_gas_tank():
	print("The gas tank is full now!")

# define a subclass ElectricCar which inherits class Car
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):

"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
	self.battery_size = 70

def describe_battery(self):
"""Print a statement describing the battery size."""
	print("This car has a " + str(self.battery_size) + "-kWh battery.")

# Overriding Methods from the Parent Class
def fill_gas_tank():
	print("This car doesn't need a gas tank!")
	
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

Files

Reading from a file

  • Open a file in the directory of current executed program by function open()
  • Open a file in read mode ‘r’, write mode ‘w’, append mode ‘a’. By default Python opens a file in read-only mode if you omit the mode argument. open(filename), open(filename, mode)
  • Read the entire contents of the file by method read()
  • Open a file by relative paths or absolute paths
  • Reading line by line
  • Making a list of lines from a file by method readlines()
# Open a file in the directory of current executed program
"""
# 'test_file.txt', the argument of open() function
# open() function opens file 'test_file.txt' and returns an object representing 'test_file.txt'
# keyword with is to close the file once no need to access it.
"""
with open() as file_object:
    contents = file_object.read()
    print(contents)

# Open a file by relative paths or absolute paths
# Linux and OOS X
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
# Windows
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:

# Reading line by line
filename = 'pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:
		print(line)

# Making a list of lines from a file by method readlines()
filename = 'pi_digits.txt'
with open(filename) as file_object:
	list_of_lines = file_object.readlines()
for line in list_of_lines:
	print(line.rstrip())

Writing to a file

  • open() a file with write mode or append mode and invoke write() method
  • Python can only write strings to a txt file. If you want to store numerical data in a txt file, you will have to convert the data to string format first using the str() function.
# if 'programming.txt' originally has content 'File version0, no topic'
filename = 'programming.txt'
with open(filename) as file_object:
	print(file_object.read())
"""
# file contents after executing above program
File version0, no topic
"""

with open(filename, 'w') as file_object:
	file_object.write("File version1, fruit topic. I love apple.\n")
	file_object.write("File version1, fruit topic. I love banana.\n")
"""
# file contents after executing above program
File version1, fruit topic. I love apple.
File version1, fruit topic. I love banana.
"""

with open(filename, 'a') as file_object:
	file_object.write("File version2, animal topic. I love cat.\n")
"""
# file contents after executing above program
File version1, fruit topic. I love apple.
File version1, fruit topic. I love banana.
File version2, animal topic. I love cat.
"""

Storing data by json (JavaScript Object Notation) module

  • json.dump() to store the data
  • json.load() to load the data
from pathlib import Path
import json


def get_stored_username(path):
    """Get stored username if available."""
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        return username
    else:
        return None

def get_new_username(path):
    """Prompt for a new username."""
    username = input("What is your name? ")
    contents = json.dumps(username)
    path.write_text(contents)
    return username

def greet_user():
    """Greet the user by name."""
    path = Path('username.json')
    username = get_stored_username(path)
    if username:
        print(f"Welcome back, {username}!")
    else:
        username = get_new_username(path)
        print(f"We'll remember you when you come back, {username}!")

greet_user()

Exceptions

  • Python uses special objects called exceptions to manage errors that arise during a program’s execution. Whenever an error occurs that makes Python unsure what to do next, it creates an exception object. If you write code that handles the exception, the program will continue running. If you don’t handle the exception, the program will halt and show a traceback, which includes a report of the exception that was raised. But this is not user friendly.
  • Exceptions are handled with try-except blocks. Use exceptions to prevent crashes.
  • try-except-else block. Any code that depends on the successful execution of try block should go in the else block.

The try-except-else block works like this: Python attempts to run the code in the try statement. The only code that should go in a try statement is code that might cause an exception to be raised. Sometimes you’ll have additional code that should run only if the try block was successful; this code goes in the else block. The except block tells Python what to do in case a certain exception arises when it tries to run the code in the try statement.

Table: Assert Methods Available from the unittest Module
在这里插入图片描述

References
Python Crash Course - A Hands-On, Project-Based Introduction to Programming (English version以及中文版本)
  • 28
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值