西维蜀黍

【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 + "!")
  ...