2020-11-29

把之前学的python入门也放上来,这样自己在外面看得见。

一、变量和简单数据类型
1.使用方法修改字符串的大小写:

motobike = 'kang '
print(motobike.upper())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
KANG

输出的是字符串所有字母的大写

motobike = 'kang '
print(motobike.title())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Kang 

输出的是字符串首字母的大写

motobike = 'KAng '
print(motobike.lower())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
kang 

输出的是字符串所有字母的小写

2.合并直接用 + 号

first_name = 'cool'
last_name = 'boy'
total_name = first_name + " " + last_name
print("Your name is : " + total_name.title() + " ! ")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Your name is : Cool Boy !

3.换行?或者叫留空格?
\n是换行输出,\t是首行缩进几个空格。

print("Language:\n\tc++\n\tpython\n\tjava")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Language:
	c++
	python
	java

\n换行 \t缩进空白

4.删除字符串的空白:

name_1 = ' dididi  '
print(name_1.lstrip() + '!')
name_2 = ' didi '
print(name_2.strip() + '!')
name_3 = '     di '
print(name_3.rstrip() + '!')

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
dididi  !
didi!
     di!

\ rstrip()删除尾部空白,lstrip()删除前部空白,strip()删除字符串两端空白。

5.使用str()避免类型错误:

age = 23
message = "Happy " + str(age) + "rd Birthday ! "
print(message)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Happy 23rd Birthday ! 

如若不使用str(),python可能将age默认为是一个字符串导致无法调用。

6.注释:

向大家问好

print(“Hello World !”)

二、列表简介(list[]):
1.列表及其元素:

bicycle = ['kangkang','michale','jane']
print(bicycle[0])

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
kangkang

注意在列表当中,索引是从0开始的。

2.修改、添加和删除元素:

bicycle = ['kangkang','michale','jane']
print(bicycle)
bicycle[0] = 'kang'
print(bicycle)
bicycle.append('momo')
print(bicycle)
bicycle.insert(1,'doudou')
print(bicycle)
del bicycle[1]
print(bicycle)
bicy = bicycle.pop()
print(bicycle)
print("弹出的元素是: " + bicy + " !")
bicycle.remove('kang')
print(bicycle)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
['kangkang', 'michale', 'jane']
['kang', 'michale', 'jane']
['kang', 'michale', 'jane', 'momo']
['kang', 'doudou', 'michale', 'jane', 'momo']
['kang', 'michale', 'jane', 'momo']
['kang', 'michale', 'jane']
弹出的元素是: momo !
['michale', 'jane']

修改元素直接用索引进行修改其中的某一个元素。
添加元素的话append()是将元素添加到列表的末尾当中;insert()可以将元素插入到列表的任一位置。
使用del可删除任何位置处的列表元素,条件是知道其索引,但删除后无法再次访问它。而pop()删除列表的元素后可以接着使用该元素,如()内无指定索引,则自动删除末尾元素,也可以指定具体索引位置的元素。如果你不知道要从列表删除的元素的索引,但你知道该元素,你可以使用remove()。

3.组织列表:
使用sort()函数对列表进行永久性排序,且按照字母表的顺序对元素的首字母进行排序。若想按相反顺序排,则使用sort(reverse=True)。

bicycle = ['kangkang','zichale','jane','aa']
print(bicycle)
bicycle.sort()
print(bicycle)
bicycle.sort(reverse=True)
print(bicycle)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
['kangkang', 'zichale', 'jane', 'aa']
['aa', 'jane', 'kangkang', 'zichale']
['zichale', 'kangkang', 'jane', 'aa']

可以使用sorted()对列表进行临时排序:

bicycle = ['kangkang','zichale','jane','aa']
print("Here is the original list : ")
print(bicycle)
print("\nHere is the sorted list : ")
print(sorted(bicycle))
print("\nHere is the original list again : ")
print(bicycle)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Here is the original list : 
['kangkang', 'zichale', 'jane', 'aa']

Here is the sorted list : 
['aa', 'jane', 'kangkang', 'zichale']

Here is the original list again : 
['kangkang', 'zichale', 'jane', 'aa']

倒着打印列表可以用reverse()。
确定列表的长度用len()

bicycle = ['kangkang','zichale','jane','aa']
print("Here is the original list : ")
print(bicycle)
bicycle.reverse()
print("\nHere is the reverse list : ")
print(bicycle)
print("\n列表的长度为: ")
print(len(bicycle))

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Here is the original list : 
['kangkang', 'zichale', 'jane', 'aa']

Here is the reverse list : 
['aa', 'jane', 'zichale', 'kangkang'] 

列表的长度为:
4

三、操作列表
1.关于for循环:

magicians = ['alice','dujiang','songjiang']
for magician in magicians:
    print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was a great show!")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

Dujiang, that was a great trick!
I can't wait to see your next trick, Dujiang.

Songjiang, that was a great trick!
I can't wait to see your next trick, Songjiang.

Thank you, everyone. That was a great show!

2.range()函数可以生成一系列数字,若想要将这些数字转化为列表,可以使用list(range())。

for value in range(1,4):
    print(value)
numbers = list(range(1,5))
print(numbers)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
1
2
3
[1, 2, 3, 4]

squares = []
for value in range(1,9):
    squares.append(value**2)

print(squares)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
[1, 4, 9, 16, 25, 36, 49, 64]

3.切片的使用:

bicycles = ['22','33','dd','kk','mm']
print(bicycles[0:3])
print(bicycles[2:4])
print(bicycles[:2])
print(bicycles[1:])
for bicycle in bicycles[:3]:
    print(bicycle)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
['22', '33', 'dd']
['dd', 'kk']
['22', '33']
['33', 'dd', 'kk', 'mm'] 
22
33
dd

注意0:3指的是从索引0到2,不包括3.
其中可以复制列表简化下面的代码或者~。

bicycles = ['22','33','dd','kk','mm']
bicycless = bicycles[:]
bicycles.append('ff')
print(bicycles)
bicycless.append('ll')
print(bicycless)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
['22', '33', 'dd', 'kk', 'mm', 'ff']
['22', '33', 'dd', 'kk', 'mm', 'll']

4.元组:
Python将不能修改的值称为不可变的,而不可变的列表被称为元组。元组用()括起来。
虽然不能修改元组的元素,但可以给存储的变量赋值。

bicycles = ('22','33','dd','kk','mm')
print("original: ")
for bicycle in bicycles:
    print(bicycle)
bicycles = ('44','jj')
print("latest: ")
for bicycle in bicycles:
    print(bicycle)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
original: 
22
33
dd
kk
mm
latest: 
44
jj

四、if语句:
1.简单的if语句,if语句的关键在于判断True或者是False。

cars = ['kangkang','mike','jane','momo']

for car in cars:
    if car == 'momo':
        print(car.upper())
    elif car == 'jane':
        print(car.title())
    else:
        print(car)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
kangkang
mike
Jane
MOMO

2.在python中检查是否相等是区分大小写的,但你可以将其转化为同一小写进行比较。
使用 “!=”判断两个变量是否不相等。
用and连接检查多个条件,且每个条件都成立才可以为True。
用or连接检查多个条件,仅需一个条件成立便可以为True。
用(bicycle = ‘~’)if bicycle not in bicycles:判断元素是否在列表当中。

available_toppings = ['mushrooms','olives','green peppers'
                      'pepperoni','pineapple','extra cheese']

requested_toppings = ['mushroom','french fries','extra cheese']

for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding " + requested_topping + '.')
    else:
        print("Sorry, we don't have " + requested_topping + ".")

print("\nFinished making your pizza!")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Sorry, we don't have mushroom.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!

五、字典(dict):
1.字典是一系列键—值对,每个都与一个值相关联,与键相关联的值可以是数字、字符串、列表乃至字典。

alien_0 = {'color':'green', 'points':5}

new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
You just earned 5 points!
添加键-值对:
alien_0 = {'color':'green', 'points':5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 5
print(alien_0)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 5}

使用字典来存储用户提供的数据或在编写能自动生成大量键-值对的代码时,通常都需要先定义一个空字典。

2.修改或删除字典中的值:

alien_0 = {'x_position': 0, 'y_position': 25, 'speed':'medium'}
print(alien_0)
del alien_0['y_position']
print(alien_0)
print("Original x_position: " + str(alien_0['x_position']))
#向右移动外星人
#据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3
#新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment

print("New x_position: " + str(alien_0['x_position']))

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
{'x_position': 0, 'y_position': 25, 'speed': 'medium'}
{'x_position': 0, 'speed': 'medium'}
Original x_position: 0
New x_position: 2

3.遍历字典(方法items()返回一个键-值对列表、方法keys()遍历字典的每一个键、方法values()遍历字典的每一个值):

user_0 = {
    'username' : 'efemi',
    'first' : 'enrico',
    'last' : 'femi'
    }

for key,value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

Key: username
Value: efemi

Key: first
Value: enrico

Key: last
Value: femi
(简单的items()使用方法。)

favorite_number = {
    'kangkang' : 3,
    'jane' : 5,
    'dudu' : 7
}

for name,number in favorite_number.items():
    print(name.title() + "'s favorite number is: " + str(number) + ".")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Kangkang's favorite number is: 3.
Jane's favorite number is: 5.
Dudu's favorite number is: 7.

4.嵌套:(字典和列表的相互转换)
a.将字典存储在列表中:

#创建一个用于存储外星人的空列表
aliens = []

#创建10个绿色的外星人
for alien_number in range(0,10):
    new_alien = {'color': 'green', 'points': 4, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['points'] = 5
        alien['speed'] = 'medium'

#显示前5个外星人的信息:
for alien in aliens[0:5]:
    print(alien)
print("...")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
{'color': 'yellow', 'points': 5, 'speed': 'medium'}
{'color': 'yellow', 'points': 5, 'speed': 'medium'}
{'color': 'yellow', 'points': 5, 'speed': 'medium'}
{'color': 'green', 'points': 4, 'speed': 'slow'}
{'color': 'green', 'points': 4, 'speed': 'slow'}
...

b.将列表存储在字典中:

#存储所点披萨的信息
pizza = {
    'crust': 'thick',
    'toppings': ['mushroom', 'extra cheese']
}

#概述所点的披萨
print("You ordered a " + pizza['crust'] + "-crust pizza"
        + "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
You ordered a thick-crust pizza with the following toppings:
	mushroom
	extra cheese

favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
}

for name,languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

Jen's favorite languages are:
	Python
	Ruby

Sarah's favorite languages are:
	C

Edward's favorite languages are:
	Ruby
	Go

Phil's favorite languages are:
	Python
	Haskell

c.在字典中存储字典:

users = {
    'sdfas': {
        'first': 'safds',
        'last': 'asfsad',
        'location': 'dsaf',
    },
    'sdfa': {
        'first': 'saefs',
        'last': 'sadfad',
        'location': 'dfgs',
    },
}

for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + user_info['last']
    location = user_info['location']

    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

Username: sdfas
	Full name: Safdsasfsad
	Location: Dsaf

Username: sdfa
	Full name: Saefssadfad
	Location: Dfgs

六、用户输入和while循环:
1.用int将输入的信息变为数字型,方便后续的操作:

height = input("Tell me your height, and I will tell you something: ")
height = int(height)

if height >= 168:
    print("\nYou're tall enough to ride! ")
else:
    print("\nYou'll be able to ride when you're a little taller")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Tell me your height, and I will tell you something: 167

You'll be able to ride when you're a little taller

2.while循环:

prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
    message = input(prompt)

    if message != 'quit':
        print(message)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

Tell me something, and I will repeat it back to you: 
Enter 'quit' to end the program. dd
dd

Tell me something, and I will repeat it back to you: 
Enter 'quit' to end the program. quit
或者使用标志来简化:
prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "

active = True
while active:
    message = input(prompt)

    if message == 'quit':
        active = False

    else:
        print(message)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

Tell me something, and I will repeat it back to you: 
Enter 'quit' to end the program. dd
dd

Tell me something, and I will repeat it back to you: 
Enter 'quit' to end the program. quit

3.使用break退出循环:(相当于将上面的active = False 换成break!!!直接将它截至了)

在循环中使用continue:

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
1
3
5
7
9

4.使用while循环来处理列表和字典:
(for循环在遍历列表的过程中不应修改列表,while循环遍历列表的同时可以对其进行修改。)
a.在列表之间移动元素

#首先创建一个待验证用户列表

#和一个用于存储已验证用户的空列表

unconfirmed_users = ['alice','michale',
                     'dudu','jifsaokf']
confirmed_users = []

#验证每个用户,直到没有为验证用户为止

#将每个经过验证的列表都移到已验证用户列表中

while unconfirmed_users:
    current_user = unconfirmed_users.pop()

    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)

#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Verifying user: Jifsaokf
Verifying user: Dudu
Verifying user: Michale
Verifying user: Alice

The following users have been confirmed:
Jifsaokf
Dudu
Michale
Alice

b.删除包含特定值的所有列表元素:

pets = ['dog','cat','pig',
        'cat','crarrot','cat']
print(pets)

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

print(pets)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
['dog', 'cat', 'pig', 'cat', 'crarrot', 'cat']
['dog', 'pig', 'crarrot']

c.使用用户输入来填充字典:

responses = {}

#设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
    #提示输入被调查者的名字和回答
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    #将答案存储在字典中
    responses[name] = response

    #看看是否还有人要参与调查
    repeat = input("Would you like to let another person respond?(yse/no) ")
    if repeat == 'no':
        polling_active = False

#调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + " would like to climb " + response + ".")

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

What is your name? kk
Which mountain would you like to climb someday? ll
Would you like to let another person respond?(yse/no) yes

What is your name? dd
Which mountain would you like to climb someday? sdfs
Would you like to let another person respond?(yse/no) no

--- Poll Results ---
kk would like to climb ll.
dd would like to climb sdfs.

七、函数:
1.定义函数:
a.向函数传递信息

def greet_user(username):
    """显示简单的问候语"""
    print("Hello, " + username.title() + "!")

greet_user('jessde')

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Hello, Jessde!

b.实参和形参:
变量username就是形参,‘jessde’是形参。

2.传递实参:
a.位置实参

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('cat','fdsdfda')
describe_pet('dog','adgfg')

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

I have a cat.
My cat's name is Fdsdfda.

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

b.默认值:

def describe_pet(pet_name, animal_type = 'cat'):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(pet_name='fdsdfda')
describe_pet(pet_name='adgfg')

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py

I have a cat.
My cat's name is Fdsdfda.

I have a cat.
My cat's name is Adgfg.

3.返回值:
a.返回简单的值

def get_formatted_name(first_name,last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' '+ last_name
    return full_name.title()

musician = get_formatted_name('adf','asffds')
print(musician)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Adf Asffds

b.让实参变成可选的:

def get_formatted_name(first_name,last_name,middle_name=''):
    """返回整洁的姓名"""
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' '+ last_name
    return full_name.title()

musician = get_formatted_name('adf','asffds')
print(musician)

musician = get_formatted_name('daff','asdf','asfd')
print(musician)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Adf Asffds
Daff Asfd Asdf

c.返回字典

def buid_person(first_name,last_name,age=''):
    """返回一个字典,其中包括有关一个人的信息"""
    person = {'first':first_name,'last':last_name}
    if age :
        person['age'] = age
    return person

musician = buid_person('jimi','hendi',age=28)
print(musician)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
{'first': 'jimi', 'last': 'hendi', 'age': 28}

4.传递列表:

def print_models(unprinted_designs,completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        #模拟根据设计制作3D打印模型的过程
        print("Printing model : " + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case' , 'adssf sf ' , 'adsf asfds']
completed_models = []

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
Printing model : adsf asfds
Printing model : adssf sf 
Printing model : iphone case

The following models have been printed:
adsf asfds
adssf sf 
iphone case

5.将函数存储在模块当中:
a.导入特定函数使,可以用as给函数指定别名:
(Eg:from pizza import make_pizza as mp)
b.导入模块中的所有函数:from pizza import *

八、类:
1.基本的一些操作,类中的函数名称为方法。

class Dog() :
    """一次模拟小狗的简单尝试"""

    def __init__(self,name,age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        """模拟小狗被命令时蹲下"""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """模拟小狗被命令时打滚"""
        print(self.name.title() + " rolled over!")

my_dog = Dog('dafsfd',7)
print("My dog's name is " + my_dog.name.title())
print("My dog's age is " + str(my_dog.age))
my_dog.sit()
my_dog.roll_over()

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
My dog's name is Dafsfd
My dog's age is 7
Dafsfd is now sitting.
Dafsfd rolled over!

2.使用类和实例:
a.给属性指定默认值:

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_odmeter(self):
        """打印一条指出汽车里程的消息"""
        print("This car has " + str(self.odometer_reading) + " miles on it.")

my_new_car = Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odmeter()

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
2016 Audi A4
This car has 0 miles on it.

b.修改属性的值

snip
my_new_car = Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())

my_new_car.read_odmeter()
my_new_car.odometer_reading = 23
my_new_car.read_odmeter()

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
2016 Audi A4
This car has 0 miles on it.
This car has 23 miles on it.

c.因为里程数是无法倒退的,所以我们需要设置里程数不能减少的条件

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_odmeter(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 odemeter!")

my_new_car = Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())

my_new_car.read_odmeter()
my_new_car.update_odometer(25)
my_new_car.read_odmeter()
my_new_car.update_odometer(23)
my_new_car.read_odmeter()

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
2016 Audi A4
This car has 0 miles on it.
This car has 25 miles on it.
You can't roll back an odemeter!
This car has 25 miles on it.

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_odmeter(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 odemeter!")

    def increment_odometer(self,miles):
        self.odometer_reading += miles

class ElectricCar(Car):
    """电动汽车的独特之处"""

    def _init_(self,make,model,year):
        """初始化父类的属性"""
        super.__init__(make,model,year)

my_tesla = ElectricCar('sdafsad','model s',2017)
print(my_tesla.get_descriptive_name())

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
2017 Sdafsad Model S

4.重写父类的方法、将实例用作属性等等:

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_odmeter(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 odemeter!")

    def increment_odometer(self,miles):
        self.odometer_reading += miles

class Baterry():
    """一次模拟电动汽车电瓶的尝试"""

    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):
        """初始化父类的属性"""
        super().__init__(make,model,year)
        self.battery = Baterry()

my_tesla = ElectricCar('sdafsad','model s',2017)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()

D:\Python3\python.exe D:/PyCharm4.5/exercise/first/exercise.py
2017 Sdafsad Model S
This car has a 70-kWh battery.
    super().__init__(make,model,year)处的super()是一个特殊函数,帮助python将父类和子类关联起来;这行代码让python调用ElectricCar的父类的方法_init_(),让ElectricCar实例包含父类的所有属性。

5.导入类

from car import Car

my_new_car = Car('duai','a6',2019)
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 29
my_new_car.read_odometer

目前安装的python有一些问题,还无法进行导入功能,待提升。

九、文件和异常:
1.从文件中读取数据:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

D:\Python3\python.exe D:/pycharm5.0.3/exercise/.idea/exercise/file_reader.py
3.1415926535

2.关于异常:

print("Give me two numbers, and I will divide them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("\nSecond number: ")
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

D:\Python3\python.exe D:/PyCharm4.5/untitled/exercise/addinterest2.py
Give me two numbers, and I will divide them.
Enter 'q' to quit.

First number: 5

Second number: 0
You can't divide by 0!

First number: 5

Second number: 3
1.6666666666666667

First number: q

3.FileNotFoundError:

filename = 'alice.txt'

try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + " does not exist."
    print(msg)

D:\Python3\python.exe D:/PyCharm4.5/untitled/exercise/addinterest2.py
Sorry, the file  does not exist.

其他:
1.求二次方程的两个根及抛出异常的处理:

__author__ = '12957'
import math
def main():
    print("This program finds the real solutions to a quadratic.\n")
    try:
        a,b,c = eval(input("Please enter the coefficients(a,b,c): "))
        discRoot = math.sqrt(b*b-4*a*c)
        root1 = (-b + discRoot) / (2*a)
        root2 = (-b - discRoot) / (2*a)
        print("\nThe solutions are:",root1,root2)
    except ValueError as excObj:
        if str(excObj) == "math domain error":
            print("No Real Roots. ")
        else:
            print("You didn't give me the right number of coefficients.")
    except NameError:
        print("\nYou didn't enter three numbers. ")
    except TypeError:
        print("\nYour inputs were not all numbers ")
    except SyntaxError:
        print("\nYour inputs was not in the correct form. Missing comma?")
    except:
        print("\nSomething went wrong,sorry!")
main()

D:\Python3\python.exe D:/PyCharm4.5/untitled/exercise/fangchengqiujie.py
This program finds the real solutions to a quadratic.

Please enter the coefficients(a,b,c): 1,6,4

The solutions are: -0.7639320225002102 -5.23606797749979

2.求三角形周长(有点问题):

def main():
    print("Please enter (x,y) of three points in turn: ")
    # 获取用户输入的三个坐标点
    x1, y1 = eval(input("Point1:(x,y) = "))
    x2, y2 = eval(input("Point2:(x,y) = "))
    x3, y3 = eval(input("Point3:(x,y) = "))
    # 判断三个点是否构成三角形
    if(isTriangle(x1, y1, x2, y2, x3, y3)):
        perim = distance(x1,y1,x2,y2) + distance(x1,y1,x3,y3) + distance(x2,y2,x3,y3)
        print("The perimeter of the triangle is: {0:0.2f}".format(perim))
    else:
        print("Kidding me? This is not a triangle!")

3.函数的形参只接收了实参的值,给形参赋值并不影响实参?

def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    return newBalance
def main():
    amount = 1000
    rate = 0.05
    amount = addInterest(amount, rate)
    print(amount)
main()
区别:
def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    balance = newBalance 
def main():
    amount = 1000
    rate = 0.05
    amount = addInterest(amount, rate)
    print(amount)
main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值