Python编程入门到实践(二)

1.用户输入和while循环

python2.7使用raw_input()来提示用户输入与python3中的input()一样,也将解读为字符串。

name=input("please enter your name: ")
print("Hello, "+name+"!")
please enter your name: Eric
Hello, Eric!

  

2.函数

(1)传递任意数量的实参

def make_pizza(*toppings):
    print(toppings)
    
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将所有收到的值封装到这个元组中。

(2)使用任意数量的关键字实参

def build_profile(first,last,**user_info):
    profile={}
    profile['first_name']=first
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile
    
user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
{'first_name': 'albert', 'location': 'princeton', 'field': 'physics', 'last_name': 'einstein'}

形参**user_info中的两个星号让Python创建了一个名为user_info的空字典,接受任意数量的关键字实参。

(3)继承

class 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 read_odometer(self):
        print("This car has "+str(self.odometer_reading)+" miles on it.")
        
    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.ofometer_reading+=miles
        
class Battery():
    def __init__(self,battery_size=70):
        self.battery_size=battery_size
        
    def describe_battery(self):
        print("This car has a "+str(self.battery_size)+"-kWh battery.")
        
class ElectricCar(Car):
    def __init__(self,make,model,year):
     '''
        初始化父类的属性,再初始化电动汽车特有的属性,这里创建一个新的Battery实例,并将该实例存储在属性self.battery中
     '''
        super().__init__(make,model,year)
        self.battery=Battery()
        
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
2016 Tesla Model S
This car has a 70-kWh battery.

  

(4)类编码风格

  • 类名应采用驼峰命名法,即将类名中的每个单词的首字母都大写,而不使用下划线。实例名和模块名都采用小写格式,并在单词之间加上下划线。
  • 对于每个类,都应紧跟在类定义后面包含一个文档字符串,这种文档字符串简要地描述类的功能,并遵循编写函数的文档字符串时采用的格式约定。
  • 每个模块也都应包含一个文档字符串,对其中的类可用于做什么进行描述。
  • 模块中可用两个空行来分割类
  • 需要同时导入标准库的模块和自己编写的模块时,先编写导入标准库模块的import语句,再添加一个空行,然后编写导入你自己编写的模块的import语句

3.文件读写

(1)从文件读取

filename='/home/shawnee/Geany_work/pcc-master/chapter_10/pi_million_digits.txt'

with open(filename) as file_object:
    lines=file_object.readlines()

pi_string=''
for line in lines:
    pi_string+=line.strip()
    
print(pi_string[:52]+'...')
print(len(pi_string))
3.14159265358979323846264338327950288419716939937510...
1000002

使用关键字with时,open()返回的文件对象只在with代码块内可用。

如果要在with代码块外访问文件的内容,可在代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表,可以立即处理也可推迟处理。

(2)写入空文件

filename='programming.txt'

with open(filename,'w') as file_object:
    file_object.write("I love programming.
")
    file_object.write("number input test: "+str(12345)+"
")

'w'模式下:文件不存在,open()将自动创建它;文件存在,python将在返回文件对象前清空该文件。

(3)附加到文件

打开文件方式指定附加模式(‘a’).

filename='programming.txt'

with open(filename,'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.
")
    file_object.write("I love creating apps that can run in a browser.
")

原文地址:https://www.cnblogs.com/exciting/p/8978369.html