赞
踩
name=" yu xiaohui "
print(f"Hello {name.title().strip()},would you like to learn some Python today?")
name="li wenhao"
print(name.title())
print(name.upper())
print(name.lower())
print("languages:\n\tPython\n\tC\n\tJava")
name=" Albert Einstein "
print(name.lstrip())
print(name.rstrip())
print(name.strip())
整数大家都知道,浮点数其实就是小数点可以出现在数的任意位置。
number=1000_000_000
print(number)
x,y,z=0,1,2
[]:表示列表,并用逗号分隔其中的元素,索引从0而不是1开始
fruits=['apple','orange','banana','pear']
print(fruits) #访问列表
print(fruits[0]) #访问列表第一个元素
fruits=['apple','orange','banana','pear']
fruits.append('strawberry')
print(fruits)
fruits=['apple','orange','banana','pear']
fruits.insert(0,'strawberry') #把'strawberry'添加到第一个元素
print(fruits)
fruits=['apple','orange','banana','pear']
del fruits[0] #删除第一个元素
print(fruits)
fruits=['apple','orange','banana','pear']
fruit=fruits.pop([1]) #删除列表的第二个元素,并返回第二个元素给fruit变量
print(fruit)
print(fruits)
fruits=['apple','orange','banana','pear']
fruit='banana'
fruit=fruits.remove(fruit)
print(fruits)
为了能更好的理解这几条语句,编写了一个大合集
party_participator=['Monica','Phoebe','Ross','Chandler','Joey']
party_participator.insert(0,'Rachel')
party_participator.append('Janice')
del party_participator[1]
party_participator.remove('Chandler')
name=party_participator.pop(-2)
print(party_participator)
fruits=['apple','orange','banana','pear']
print(sorted(fruits)) #临时排序
print(fruits)
fruits.sort() #永久排序
print(fruits)
fruits.reverse() #顺序颠倒
print(fruits)
print(len(fruits))
使用for循环,从列表中从前往后依次取出一个元素赋给fruit,执行相同的操作,注意缩进:
fruits=['apple','orange','banana','pear']
for fruit in fruits:
print(fruit)
for value in range(1,5) #从1到4
print(value)
numbers=list(range(1,6)) #从1到5
print(numbers)
numbers=list(range(1,10,2)) #加入步长,列表相邻的数值相差2
print(numbers)
numbers=[1,2,3,4,5,6,7,8,9,10]
print(min(numbers)) #列表最小值
print(max(numbers)) #列表最大值
print(sum(numbers)) #对列表元素求和
squares=[value**2 for value in range(1,11)]
print(squares)
fruits=['apple','orange','banana','pear']
print(fruits[0:3]) #该切片包含从0到2三个元素
for fruit in fruits[0:3]:
print(fruit)
fruits=['apple','orange','banana','pear']
copy_fruits=fruits[:]
print(copy_fruits)
numbers=(1,2,3,4,5)
for number in numbers:
print(number)
fruits=['apple','orange','banana','pear']
fruit='apple'
if fruit in fruits:
print("Get it!")
else :
print("Error!")
if fruit == 'apple':
print("fruit is apple")
elif fruit == 'orange':
print("fruit is orange")
else:
print("Cannot find it!")
键和值之间用冒号分割,而键值对之间用逗号分隔
alien={'color':'green','point':5}
print(alien['color'])
alien={'color':'green','point':5}
alien['weight']=80
alien['height']=200
print(alien)
alien={'color':'green','point':5}
alien['color']='yellow'
print(alien['color'])
alien={'color':'green','point':5}
del alien['color']
print(alien)
alien={'color':'green','point':5}
value=alien.get('height','No point value assigned.')
print(value)
favorite_languages={
'Bob':'C',
'Alice':'Python',
'Joey':'Java',
}
languages={
'Bob':'Python',
'Alice':'C',
'David':'Java'
}
for name,language in languages.items(): #items()返回一个键值对列表
print(f"\nname:{name}")
print(f"language:{language}")
languages={
'Bob':'Python',
'Alice':'C',
'David':'Java'
}
for name in languages.keys(): #返回所有的键
print(name.title())
languages={
'Bob':'Python',
'Alice':'C',
'David':'Java'
}
for language in languages.values(): #返回所有的值
print(language)
aliens=[] #创建列表
for number in range(30): #批量创建字典
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:3]: #批量修改字典
if alien['color']=='green':
alien['color']='yellow'
alien['points']=10
alien['speed']='medium'
for alien in aliens[:6]: #展示前六个
print(alien)
pizza={
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
print(pizza['crust'])
print(pizza['toppings'])
height=input("How tall are you?")
height=int(height)
if(height>160):
print("\nYou are enough height to ride!")
else:
print("\nYou didn't reach the height to ride!")
number=1
while number<=5:
print(number)
number+=1
sentence='Please enter the name of a city you have visited'
sentence+='\n(Enter "quit" when you want to end):'
while True:
city=input(sentence)
if city=='quit':
break
else:
print(f"I'd like to go to {city.title()}")
number=0
while number<10:
number+=1
if number%2==0:
continue
print(number)
users=['Bob','Alice','Joey']
new_users=[]
while users:
user=users.pop()
new_users.append(user)
print(users)
print(new_users)
pets=['dogs','cat','dog','rabbit','dog','wolf']
while 'dog' in pets:
pets.remove('dog')
print(pets)
responses={}
flag=True
while flag!='no':
name=input("What's your name:")
response=input("Do you like Basketball(yes/no):")
responses[name]=response
flag=input("anyone else?(yes/no):")
print(responses)
函数是带名字的代码块,用于完成具体的工作,使用关键词def来定义。
def greet_user():
print("Hello!")
greet_user() #调用定义的函数
def language(name,language): #形参
print(f"{name} is good at {language}")
language('Bob','Python') #实参
language('Alice','C')
def pet(name,type='dog'): #'type'为默认值
print(f"Its name is {name}\nIts type is {type}")
pet('Dabai')
def format_name(first_name,last_name):
name=f"{first_name.title()} {last_name.title()}"
return name
name=format_name('li','wasai')
print(name)
def make_pizza(size,*toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16,'mushrooms','green peppers','extra cheese')
def build_profile(first,last,**user_info):
user_info['first_name']=first
user_info['last_name']=last
return user_info
user_profile=build_profile('Li','Wasai',
location='Jining',field='computer')
print(user_profile)
from numpy import array,arange
import numpy as np
np.array([1,2,3,4,5])
from numpy as *
array([1,2,3,4,5])
面向对象编程
根据类来创建对象称为实例化
class Dog: def __init__(self, name, age): self.name = name self.age = age self.steps = 0 给属性制定默认值,无需再用形参来定义 def sit(self): print(f"{self.name} is now sitting") def roll_over(self): print(f"{self.name} rolled over") def run(self): print(f"{self.name} have run {self.steps} steps") def update_run(self,steps): #通过方法修改属性的值 self.steps=steps #使用类和实例 my_dog = Dog('Dabai', 6) print(f"its name is {my_dog.name}\nits age is {my_dog.age}") my_dog.sit() #调用方法 my_dog.roll_over() my_dog.run() my_dog.update_run(10000) my_dog.run()
方法__init__()是类必不可少的,每当你根据Dog类创建新实例时,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=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): print(f"This car has {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 on adometer!") def increment_odometer(self,miles): self.odometer_reading+=miles
class Car: --snip-- class ElectricCar(Car): #定义子类时,必须在圆括号内指定父类的办法 def __init__(self,make,model,year): super().__init__(make,model,year) #super()让你能够调用父类的办法 self.battery_size=75 #让子类定义属性 def describe_battery(self): #让子类定义方法 print(f"This car has a {self.battery_size}-kwh battery") def fill_gas_tank(self): #重写父类的方法 print("This car doesn't need a gas tank!") my_tesla=ElectricCar('tesla','model s',2019) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
3.将实例用作属性
class Car: --snip-- class Battery: #定义一个新类,表示电动汽车电瓶的属性和方法 def __init__(self,battery_size=75): self.battery_size def describe_battery(self): print(f"This car has a {self.battery_size}-kwh battery") class ElectricCar(Car): #定义子类时,必须在圆括号内指定父类的办法 def __init__(self,make,model,year): super().__init__(make,model,year) #super()让你能够调用父类的办法 self.battery=Battery() #创建Battery实例赋给属性self.battery def fill_gas_tank(self): #重写父类的方法 print("This car doesn't need a gas tank!") my_tesla=ElectricCar('tesla','model s',2019) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。