用户输入
- 函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python可将其存储在一个变量中,以方便使用。使用函数input()时,Python将用户输入解读为字符串
message = input("Tell me something, and I will repeat it back to you: ") print(message) >>>Tell me something, and I will repeat it back to you: Hello everyone!Hello everyone! prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? " name = input(prompt)
- 函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示
函数
- 调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。
def describe_pet(animal_type, pet_name): """显示宠物的信息""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet('hamster', 'harry') describe_pet('dog', 'willie')
- 关键字实参是传递给函数的名称—值对。你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆(不会得到名为Hamster的harry这样的结果)。关键字实参让你无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。
def describe_pet(animal_type, pet_name): """显示宠物的信息""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet(animal_type='hamster', pet_name='harry')
- 默认值
def describe_pet(pet_name, animal_type='dog'): """显示宠物的信息""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet(pet_name='willie')
- 返回值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。在函数中,可使用return语句将值返回到调用函数的代码行。 - 传递列表
def greet_users(names): """向列表中的每位用户都发出简单的问候""" for name in names: msg = "Hello, " + name.title() + "!" print(msg) usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)
类
- 根据类来创建对象被称为实例化
定义了一个名为Dog的类。根据约定,在Python中,首字母大写的名称指的是类。这个类定义中的括号是空的,因为我们要从空白创建这个类。在处,我们编写了一个文档字符串,对这个类的功能作了描述。
```python
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name和age"""
self.name = name
self.age = age
```
- 方法__init__()
类中的函数称为方法;每当你根据Dog类创建新实例时,Python都会自动运行它;上述方法__init__()定义成了包含三个形参:self、name和age。在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面。
形参self的作用
Python调用这个__init__()方法来创建Dog实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法
self.name = name获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例 - 类的调用
class Dog(): --snip-- my_dog = Dog('willie', 6) my_dog.sit() my_dog.roll_over()
- 继承
创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值。为此,子类的方法__init__()需要父类施以援手。
(1)创建子类时,父类必须包含在当前文件中,且位于子类前面
(2)我们定义了子类ElectricCar。定义子类时,必须在括号内指定父类的名称
(3)方法__init__()接受创建Car实例所需的信息
(4)super()是一个特殊函数,帮助Python将父类和子类关联起来。这行代码让Python调用ElectricCar的父类的方法__init__(),让ElectricCar实例包含父类的所有属性。父类也称为超类(superclass),名称super因此而得名 - 重写父类的方法
有一个名为fill_gas_tank()的方法.Python将忽略Car类中的方法fill_gas_tank(),转而运行上述代码。使用继承时,可让子类保留从父类那里继承而来的精华,并剔除不需要的糟粕。
文件和异常
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
Python方法rstrip()删除(剥除)字符串末尾的空白
with open('text_files/filename.txt') as file_object:
逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)