变量和简单的数据类型
Java学完学Python 的一些记录。。。。
跟着《Python编程从入门到实践》学习的第一部分内容
- 字符串
title()#以首字母大写的方式显示每个单词,即将每个首字母都改为大写
upper()#整个字母大写
lower()#整个字母小写
使用 + 号来合并字符串
常用符号
#添加换行符
print("Languages:\nPython\nC\nJava");
#制表符
print("Python");
print("\tPython");
删除空白符
favorite_language=' python ';
print(favorite_language);
print(favorite_language.rstrip());#最后的
print(favorite_language.lstrip());#最前面的
print(favorite_language.strip());#同时删除两端
2.数字
使用str()函数避免类型错误
age=23;
message="Happy "+str(age)+"rd Birthday";
print(message);
列表
bicycles=['trek','cannondale','redline','specialized'];
print(bicycles);
print(bicycles[0]);
print(bicycles[0].title());
#访问最后一个列表元素将索引指定为-1
print(bicycles[-1]);
增删改查
#修改
motorcycles=['honda','yamaha','suzuki'];
print(motorcycles);
motorcycles[0]='ducati';
print(motorcycles);
#添加元素
motorcycles.append('honda');#在列表末尾添加
print(motorcycles);
# #插入元素
motorcycles.insert(0,'ducati');
print(motorcycles);
#删除元素
del motorcycles[0];
print(motorcycles);
#pop()元素
pop_motorcycle=motorcycles.pop();
print(motorcycles);
print(pop_motorcycle);
#根据值删除元素
motorcycles.remove('honda');
print(motorcycles);
组织列表
#sort永久排序
cars=['bmw','audi','toyota','subaru'];
cars.sort();
print(cars);
cars.sort(reverse=True);
print(cars);
#临时排序
print(sorted(cars));
#倒着打印列表
cars.reverse();
print(cars);
#列表长度
print(len(cars));
遍历整个列表
magicians=['alice','david','carolina'];
for magician in magicians:
print(magician);
magicians=['alice','david','carolina'];
for magician in magicians:
print(magician.title()+", that was a great trick!");
创建数值列表
for value in range(1,5):
print(value)
#创建列表
numbers=list(range(1,6))
print(numbers)
#偶数
even_numbers=list(range(2,11,2))
print(even_numbers)
squares=[];#创建空列表
for value in range(1,11):
square=value**2
squares.append(square)
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares))
#列表解析
squares=[value**2 for value in range(1,11)]
print(squares)
使用列表的一部分
players=['charles','martina','michael','florence','eli']
print(players[0:3])
for play in players[:3]:
print(play.title())
#复制
players_1=players[:]
print(players_1)
元组
dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension)
if语句
cars=['bmw','audi','toyota','subaru'];
for car in cars:
if car=='bmw':
print(car.upper())
else:
print(car.title())
age=12
if age<4:
print("不花钱")
elif age<18:
print("花钱5")
else:
print("花10块钱")
检查特定值是否不包含在列表中
cars=['bmw','audi','toyota','subaru'];
print('AWM' in cars)
字典
键——值
alien_0={'color':'green','points': 5}
print(alien_0['color'])
print(alien_0['points'])
#添加键值对
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
#修改
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["new x_position"]=alien_0['x_position']+x_increment
print(alien_0["new x_position"])
#删除
del alien_0['x_position']
print(alien_0)
遍历字典
for key,value in user_0.items():
print("\nKey: "+key)
print("Value: "+value)
for name,language in favorite_language.items():
print(name.title()+"'s favorite language is "+language.title()+".")
#遍历字典中的所有键
for name,language in favorite_language.items():
print(name.title())
#用键值判断
if 'erin' not in favorite_language.keys():
print("Erin,please take our poll")
#避免集合重复项,使用set集合
for language in set(favorite_language.values()):
print(language.title())
嵌套
alien_0={'color':'green','points': 5}
alien_1={'color':'yellow','points': 10}
alien_2={'color':'red','points': 15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
aliens=[]
for alien_number in range(30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
for name,languages in favorite_language.items():
print("\n"+name.title()+"'s favorite languages are:")
for language in languages:
print("\t"+language.title())
用户输入和while循环
输入
message=input("Tell me something,and I will repeat it back to you: ")
print(message)
while循环
current_number=1
while current_number<=5:
print(current_number)
current_number+=1
用while循环来处理列表和字典
unconfirmes_users=['alice','brian','candace']
confirmed_users=[]
while unconfirmes_users:
current_users=unconfirmes_users.pop()
print("Verifying user: "+current_users.title())
confirmed_users.append(current_users)
for confirmed_user in confirmed_users:
print(confirmed_user)
responses={}
polling_active=True
while polling_active:
name=input("\nWhat is your name?")
response=input("你想去爬哪座山?")
responses[name]=response
repeat=input("(yes/no)")
if repeat=='no':
polling_active=False
for name,response in responses.items():
print(name+" "+response+".")
函数
def greet_user():
print("hello!")
greet_user()
def greet_user(username):
print(username.title())
greet_user('karry')
def build_person(first_name,last_name):
person={'first':first_name,'last':last_name}
return person
musician=build_person('jimi','hendrix')
print(musician)
##########################################
##############魔术师#######################
def show_magicians(magicians):
for magician in magicians:
print(magician.title())
def show_great(magicians_1):
i=0;
for magician in magicians_1:
magicians_1[i]="the Great "+magician
i=i+1
return magicians_1
magicians=['karry','bob','wjk']
magicians_1=magicians.copy();
magicianss=show_great(magicians_1)
print("原始数据")
show_magicians(magicians)
print("副本")
show_magicians(magicianss)
传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
使用任意数量的关键字实参
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)
类
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()+" rolled over!")
my_dog=Dog('willie',6)
my_dog.sit()
my_dog.roll_over()
print("My dog's name is "+my_dog.name.title()+".")
print("My dog is "+str(my_dog.age)+" years old.")
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
def describe_restaurant(self):
print(self.restaurant_name.title()+" "+self.cuisine_type.title())
def open_restraurant(self):
print(self.restaurant_name.title()+" is open")
my_reataurant=Restaurant("sweet",'Chinese')
print(my_reataurant.restaurant_name)
print(my_reataurant.cuisine_type)
my_reataurant.describe_restaurant()
my_reataurant.open_restraurant()
my_reataurant1=Restaurant('kitty','chongqin')
my_reataurant2=Restaurant('kell','wuhan')
my_reataurant.describe_restaurant()
my_reataurant1.describe_restaurant()
my_reataurant2.describe_restaurant()
给属性指定默认值
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()
修改属性值
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):
self.odometer_reading=mileage
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 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.odometer_reading+=miles
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
def fill_gas_tank(self):
print("This car doesn't need a gas tank")
my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.fill_gas_tank()
文件和异常
读
with open('pi_digits') as file_object:
contents=file_object.read()
print(contents)
filename='pi_digits'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
#############################
filename='pi_digits'
with open(filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
写
filename='programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming")