【免费分享编程笔记】Python学习笔记(一)+https://developer.aliyun.com/article/1621227
五、if语句
5.1引入例子
cars=['audi','bmw','subaru','toyota'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title())
5.2条件测试
- 每条if语句的核心就是一个值
true
或false
。
5.2.1检查多个条件
- 使用 and检查多个条件,相当于“&&”
age_0=22 age_1=18 print(age_0>=21 and age_1>21)
- 使用 or检查多个条件,相当于“||”
age_0=22 age_1=18 print(age_0>=21 or age_1>21)
5.2.2检查特定值是否包含在列表中
- 关键字
in
requested_toppings=['mushrooms','onions','pineapple'] print('mushrooms' in requested_toppings)
- 在if语句中,缩进的作用与for循环中相同,如果测试通过了,将执行if语句后面所有缩进的代码,否则将忽略他们。
5.3.2if-else语句
age=17 if age>=18: print("you are oil enough to vote") print("you are oil enough to vote123456") else: print("sorry you can ") print("sorry you can please register ")
5.3.3if-elif-else
age=12 if age<4: print("your admission cost is 0$") elif age<18: print("your admission cost is 5$") else: print("your admission cost is 0$")
5.3.4使用多个elif代码块
age=12 if age<14: price=0 elif age<18: price=5 elif age<65: price=10 else: price=5 print("your admission cost is $"+str(price)+".")
六、字典
- 字典就是能够存储互不相联的信息
alien_0={'color':'green','points':5} print(alien_0['color']) print(alien_0['points'])
6.2使用字典
- 字典是一系列的 键------值对 组成的。我们可以通过键访问值,也可以通过值访问键。
6.2.1访问字典中的值
alien_0={'color':'green','points':5} new_points=alien_0['points'] print("you just earned "+str(new_points)+"points!")
6.2.2添加键值对
- 字典是一种动态结构,可以随时添加键值对。
alien_0={'color':'green','points':5} print(alien_0) alien_0['x_position']=0 alien_0['y_position']=25 print(alien_0)
6.2.3创建空字典
alien_0={} alien_0['color']='green' alien_0['points']=5 print(alien_0)
6.2.4修改字典中的值
alien_0={'color':'green'} print("The alien is"+alien_0['color']+".") alien_0['color']='yellow' print("The alien is now"+alien_0['color']+".")
alien_0={'x_position':0,'y_position':25,'speed':'medium'} 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']))
6.2.5删除键值对
alien_0={'color':'green','points':5} print(alien_0) del alien_0['points'] print(alien_0)
6.2.6由类似对象组成的字典
favorite_languagres={ 'jen':'python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } print("Saras facorite language is"+favorite_languagres['sarah'].title()+".")
6.3遍历字典
6.3.1遍历所有的键值对
items()
方法可以返回字典里的键和值得元素
user_0={ 'username':'efermi', 'first':'enrico', 'last':'fermi', } for key,value in user_0.items(): print("\nkey:"+key) print("value:"+value)
6.3.2遍历字典中的所有键
- 在不需要使用字典中的值时,方法
key()
很有用。遍历所有键值。
favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name in favorite_languages.keys(): print(name.title())
favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } friends=['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print("Hi"+name.title()+",I see your favorite languages is"+favorite_languages[name].title()+"!")
6.3.3按顺序遍历字典中的所有键
favoirte_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } for name in sorted(favoirte_languages.keys()): print(name.title()+",thank you for taking the poll")
6.3.4遍历字典中的所有值
favoirte_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } print("The following languages have been menthioned:") for language in favoirte_languages.values(): print(language.title())
6.4嵌套
- 将字典存储在列表中叫做 嵌套
6.4.1字典列表
#字典 alien_0={ 'color':'green', 'points':5, } alien_1={ 'color':'red', 'points':15, } alien_2={ 'color':'yellow', 'points':25, } aliens=[alien_0,alien_1,alien_2]#列表 for alien in aliens: print(alien)
6.4.2在字典中存储列表
pizza={ 'crust':'thick', 'toppings':['mushrooms','extra cheese'], } print("you ordered a "+pizza['crust']+"-crust pizza"+"with the following toppings:") for topping in pizza['toppings']: print("\t"+topping)
6.4.3在字典中存储字典
users={ 'aeinstein':{ 'first':'albert', 'last':'einstein', 'location':'princetion', }, 'mucire':{ 'first':'marie', 'last':'curie', 'location':'princetion', }, } 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())
七、用户输入和while循环
7.1函数input
- 这是一个输入函数
message=input("tell me something and I will repeat it back to you:") print(message)
7.1.1编写清晰的程序
name=input("please enter your name:") print("Hello"+name+"!")
7.1.2使用int()来获取数值输入
int()
可以将字符串转换成数字
age=input("How old are you?") age=int(age) if age>18: print("\n you are tall enough to ride") else: print("\n you .....")
7.1.3求模运算符
number=input("Enter a number ,and I will tell you if it is even or odd") number=int(number) if number%2==0: print("\nThe number"+str(number)+"is even") else: print("\nThe number "+str(number)+"is odd")
7.2while循环简介
7.2.1使用while循环
current_number=1 while current_number<=5: print(current_number) current_number+=1;
7.2.2让用户选择何时退出
- 可以使用while循环让程序在用户愿意时不断运行。我们在其中定义一个退出值,只要用户输入的不是这个值,程序接着运行。
prompt="\n Tell me something and i will repeat it back to you:" prompt+="\n Enter 'quit' to end the program" message="" while message !='quit': message=input(prompt) print(message)
7.2.3使用标志
- 使用标志有点类似与旗帜变量。赋予它一个状态,当状态发生改变时,循环结束。
prompt="\n Tell me something and i will repeat it back to you:" prompt+="\n Enter 'quit' to end the program" active=True while active: message=input(prompt) if message=='quit': active=False else: print(message)
7.2.4适应break退出循环
- 要退出while循环,不在执行接下来的代码,直接使用
break
prompt="\n Tell me something and i will repeat it back to you:" prompt+="\n Enter 'quit' to end the program" while True: city=input(prompt) if city=='quit': break else: print("I love to go to "+city.title()+"!")
7.3使用while循环来处理列表和字典
7.3.1在列表之间移动元素
#首先创建一个带验证的用户列表 #和一个用于存储已经验证的用户列表 unconfirmed_users=['alice','brain','candace'] confirmed_users=[] #验证每个用户,直到没有未验证的用户为止 #将每个经过验证的列表都移动到已经验证后的用户列表中 while unconfirmed_users: current_user=unconfirmed_users.pop() print("Verfing user:"+current_user.title()) confirmed_users.append(current_user) #显示所有已经验证的用户 print("\nThe following users have beeen confimede:") for confirmed_user in confirmed_users: print(confirmed_user.title())
7.3.2删除包含特定值的所有列表
pets=['dog','cat','dog','goldfish','cat','rabbit','cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
八、函数
8.1定义函数
- 使用关键字
def
def greeter_user(): print("Hello!") greeter_user()
8.1.1向函数传递信息
- 函数内可以包含参数,我们 在调用函数的时候可以自定义参数值进行传递
def greeter_user(username): print("Hello!"+username.title()) greeter_user('jesse')
8.1.2实参和形参
- 调用函数传递的参数叫实参,因为它发挥了实际作用。
- 定义函数的参数叫形参,只是一个摆设而已,可有可无,所以叫形参。
def describe_pet(animal_type,pet_name): print("\nI have a "+animal_type+".") print("my"+animal_type+"name is"+pet_name.title()+".") describe_pet('hasmter','harry')
8.2返回值
- 函数并非是直接输出显示,相反,他可以处理一些数据,返回一个或一组值。函数返回的值被称为返回值、
def get_formatted_name(first_name,last_name): full_name=first_name+' '+last_name return full_name.title() muscian=get_formatted_name('jimi','hendix') print(muscian)
8.2.1让实参变成可选
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() muscian=get_formatted_name('jimi','hendrix') print(muscian) muscians=get_formatted_name('jimi','hooker','lee') print(muscians)
8.3传递列表
- 函数实参为列表
def greet_users(names): for name in names: msg="Hello,"+name.title()+"!" print(msg) usernames=['hanana','ty','margot'] greet_users(usernames)
8.3.1在函数中修改列表
#首先创建一个列表,其中一些包含要打印的设计 unprinted_designs=['iphone case','robot pendant','dodecahedron'] completed_models=[] #模拟打印这个设计,知道未打印的设计为止 #打印每个设计后,都将其移动到completed_models中 while unprinted_designs: current_design=unprinted_designs.pop() #模拟根据设计制作3D打印的过程: print("Printing model:"+current_design) completed_models.append(current_design) #显示并打印好所有的模型: print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
8.5传递任意数量的实参
- 形如
*topping
的参数我们称为一个元组。 - 元组可以接受多个实参,这样做的好处就是形参不用写多个来匹配了!
def make_pizza(*toppinhs): print(toppinhs) make_pizza('peperoni') make_pizza('mushrooms','green peppers','extra cheese') def make_pizza(*toppings): print("\n making a pizza with following toppings:") for topping in toppings: print("-"+topping) make_pizza('peperoni') make_pizza('mushrooms','green peppers','extra cheese')
8.6将函数存储在模块中
8.6.1导入整个模块
- 将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。
- 关键字
import
pizza.py:
def make_pizza(size,*toppings): print("\n making a"+str(size)+ "-inch pizza with the following toppings:") for topping in toppings: print("-"+topping)
making_pizzas.py:
import pizza pizza.make_pizza(16,'pepperoni') pizza.make_pizza(12,'mushroom','pepperoni','green peppers','extra cheese')
8.6.2导入特定函数
from
模块名import
函数名
from pizza import make_piza make_pizza(16,"peopperonic") make_pizza(12,'mushroom','pepperoni','green peppers','extra cheese')
8.6.3使用as给函数指定别名
- 将函数进行重命名
from pizza import make_pizza as mp mp(16,'people') mp(12,'mushroom','pepperoni','green peppers','extra cheese')
8.6.4使用as给模块指定别名
- 通过给指定的简短的别名,让我们更轻松的调用模块中的函数。
import pizza as p p.make_pizza(16,'people') p.make_pizza(12,'mushroom','pepperoni','green peppers','extra cheese')
8.6.5导入模块中的所有函数
- 使用
*
运算符可以让 Python导入模块的 所有函数
from pizza import * make_pizza(16,'people') make_pizza(12,'mushroom','pepperoni','green peppers','extra cheese')
九、类
9.1使用和创建类
self
是自动创建的一个形参,可以访问自己创建的属性
class Dog(): def __init__(self,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()+"roll over!")
9.1.1根据类创建实例
class Dog(): my_dog=Dog('willie',6) print("my dog name is"+my_dog.name.title()+".") print("my dog is"+str(my_dog.age)+"year ole ")
- 访问属性
class Dog(): def __init__(self, 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() + "roll over!") my_dog=Dog('willie',6) print("\n"+my_dog.name)
- 调用方法
class Dog(): def __init__(self, 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() + "roll over!") my_dog=Dog('willie',6) my_dog.sit() my_dog.roll_over()
- 创建多个实例
class Dog(): def __init__(self, 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() + "roll over!") my_dog=Dog('willie',6) your_dog=Dog("lucky",3) print("my dog name is"+my_dog.name.title()+".") print("my dog is"+str(my_dog.age)+"years old")
9.2使用类和实例
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") my_new_car=Car('audi','a4',2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
9.2.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") my_new_car=Car('audi','a4',2016) print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading=23 my_new_car.read_odometer()
- 通过方法修改属性值
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 update_odometer(self,mileage): self.odometer_reading=mileage def read_odometer(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.update_odometer(23) my_new_car.read_odometer()
- 通过方法对属性值进行递增
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 update_odometer(self,mileage): self.odometer_reading=mileage def increment_odometer(self,miles): self.odometer_reading+=miles def read_odometer(self): print("This car has"+str(self.odometer_reading)+"miles on it") my_used_car=Car('subaru','outback',2013) print(my_used_car.get_descriptive_name()) my_new_car=Car('audi','a4',2016) print(my_new_car.get_descriptive_name()) my_used_car.update_odometer(23) my_used_car.read_odometer()
9.3继承
- 原有的类称为 父类,新类称为 子类
- 子类继承了父类所有的方法属性,同时还可以定义自己的属性和方法
9.3.1子类方法_init_()
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 roll back an odometer!") 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('tesla','model',2016) print(my_tesla.get_descriptive_name())
9.3.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 roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading+=miles class ElectricCar(Car): def __init__(self,make,model,year): super().__init__(make,model,year) self.battery_size=70 def describe_battery(self): print("This car has a "+str(self.battery_size)+"-kwh battery") my_tesla=ElectricCar('tesla','model',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
an odometer!")
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(‘tesla’,‘model’,2016)
print(my_tesla.get_descriptive_name())
### 9.3.3给子类定义属性和方法 ```python 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 roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading+=miles class ElectricCar(Car): def __init__(self,make,model,year): super().__init__(make,model,year) self.battery_size=70 def describe_battery(self): print("This car has a "+str(self.battery_size)+"-kwh battery") my_tesla=ElectricCar('tesla','model',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()