西维蜀黍

【Python】Basics - Variables

Assignment statement

Assignment statement gives a value to a variable:

  • assignment token: =
  • equals: ==

Ask the interpreter to evaluate a variable

  ...


【Python】Basics - Exceptions

Using try-except Blocks

When you think an error may occur, you can write a try- except block to handle the exception that might be raised. You tell Python to try running some code, and you tell it what to do if the code results in a particular kind of exception.

Here’s what a try- except block for handling the ZeroDivisionError exception looks like:

try:
		print(5/0) 
except ZeroDivisionError:
		print("You can't divide by zero!")
  ...


【Python】IO - WriteFiles

Writing to an Empty File

To write text to a file, you need to call open() with a second argument telling Python that you want to write to the file. To see how this works, let’s write a simple message and store it in a file instead of printing it to the screen:

filename = 'programming.txt'

with open(filename, 'w') as file_object:
		file_object.write("I love programming.")

The second argument, ‘w’, tells Python that we want to open the file in write mode. You can open a file in read mode (‘r’), write mode (‘w’), append mode (‘a’), or a mode that allows you to read and write to the file (‘r+’). If you omit the mode argument, Python opens the file in read-only mode by default.

  ...


【Python】IO - ReadFiles

Reading an Entire File

To begin, we need a file with a few lines of text in it. Let’s start with a file that contains pi to 30 decimal places with 10 decimal places per line:

# pi_digits.txt
3.1415926535 
  8979323846 
  2643383279
  ...


【Python】Basics - Inheritance

Inheritance

You don’t always have to start from scratch when writing a class. If the class you’re writing is a specialized version of another class you wrote, you can use inheritance. When one class inherits from another, it automatically takes on all the attributes and methods of the first class. The original class is called the parent class, and the new class is the child class. The child class inherits every attribute and method from its parent class but is also free to define new attributes and methods of its own.

class Car():
		"""A simple attempt to represent a car."""
		
		def init(self, make, model, year):
				"""Initialize attributes to describe a car.""" 
				self.make = make 
        self.model = model 						
				self.year = year

		def get_descriptive_name(self):
				"""Return a neatly formatted descriptive name.""" 
				long_name = str(self.year) + ' ' + self.make + ' ' + self.model 
				return long_name.title()

class ElectricCar(Car):
		"""Represent aspects of a car, specific to electric vehicles."""
		def __init__(self, make, model, year):
      	"""Initialize attributes of the parent class.""" 
        super().__init__(make, model, year)

my_tesla = ElectricCar('tesla', 'model s', 2016) 
print(my_tesla.get_descriptive_name()) # 2016 Tesla Model S
  ...


【Python】Basics - Modules

Function

Importing an Entire Module

To start importing functions, we first need to create a module. A module is a file ending in .py that contains the code you want to import into your program. Let’s make a module that contains the function make_pizza(). To make this module, we’ll remove everything from the file pizza.py except the function make_pizza():

# pizza.py
def make_pizza(size, *toppings):
		"""Summarize the pizza we are about to make.""" 
		print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") 
		for topping in toppings:
			print("- " + topping)
  ...


【Python】Basics - Functions

defining a function

Here’s a simple function named greet_user() that prints a greeting:

def greet_user():
		"""Display a simple greeting."""
		print("Hello!")
		greet_user()
  ...


【Python】IO - User Input

input() function

The input() function pauses your program and waits for the user to enter some text. Once Python receives the user’s input, it stores it in a variable to make it convenient for you to work with.

For example, the following program asks the user to enter some text, then displays that message back to the user:

name = input("Please enter your name: ") 
print("Hello, " + name + "!")
  ...


【Python】Basics - Simple Data Types

Data Types

  • integer: 4
  • string: “Hello World!” - encloed in quotation marks (single quotes (’) or double quotes (""), or three of each (’’’ or “”"))

  • float: 3.2 - a number with decimal point
  • bool: True
  ...


【Linux】命令 - cut

cut命令

cut 命令对指定文件的内容的每一行进行截断,并将截断后的所有内容(或部分内容)输出到标准输出。

usage: cut -b list [-n] [file ...]
       cut -c list [file ...]
       cut -f list [-s] [-d delim] [file ...]

如果不指定 File,cut 命令将读取标准输入。必须指定 -b、-c 或 -f 标志之一。

  ...