我为什么选择Python???
Python???
为什么要学习Python???
C++它不香吗???
是的,它确实不香了(笑
Java和Python在后台语言上各撑起了一片天
Java的使用时间更久,更成熟;Python则更年轻,更加的便捷,两者各有各的优势所在:
- Python:
- 相比于Java来说,Python上手较快,开发效率高,可能实现同样的功能Java需要上百行代码,但Python只需要几十行便可以解决
- 代码量少,维护和更新起来也就相对容易,表达概念更加清楚
- 人工智能首选语言(爬虫可不是说说的)
- Java重于编程,Python重于解决问题
- Java:
- 安全稳定,发展较成熟,国内受众广
- 容易创建应用,有多种工具进行应用研发
- 发展方向较多
Java在近些年来的表现中规中矩,而Python则是迎上潮流,所以__我全都要__(小孩子才做选择题)
Python学习之路
Hello, World!
首先当然是编写一个Hello,World!了,据说在计算机界有这样的一个传说,当你刚接触一门编程语言时,你第一个程序编写Hello,World!会给你带来好运
message = "Hello Python world!"
print("Hello Python world!")
print(message)
对你没有看错,变量就是这么简单使用,根本就不需要定义的,而且打印变量也不需要C++那么繁琐,最关键的是每行代码后面不需要添加’;',这是多么好多么人性化的一门语言啊!!!
字符串操作
大小写转换
name = "ada lovelace"
print(name.title()) # 首字母大写
print(name.upper()) # 均大写
print(name.lower()) # 均小写
踩坑警告!!!
若要输入中文需要加一行
'# -- coding : utf-8 -- ’ (单引号内)
否则会报错
删除字符串前后空白
favorite_language = 'python '
print(favorite_language)
print(favorite_language.rstrip()) # 末尾
print(favorite_language.lstrip()) # 开头
print(favorite_language.strip()) # 开头和末尾
格式转换
age = 18
message = "Happy " + str(age) + "rd Birthday" # str()用来转换数字与字符串格式,防止语法错误
print(message)
合并字符串
first_name = "Mike"
last_name = "lsilencej"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
message = "Hello, " + full_name.title() + "!"
print(message)
列表(即数组)
访问列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
print(bicycles[3].title())
print(bicycles[-1].title()) #特殊
这里有个索引为负数,代表着与最后一个元素的距离,索引为-1时输出最后一个元素
基本操作
bicycles.append('galaxy') # 添加列表元素至末尾(相当于横过来的栈)
motorcycles = [] # 空列表
motorcycles.insert(0, 'ducati') # 在列表中插入元素,'0'代表索引
del motorcycles[0] # 删除元素,使用del则代表不可继续访问该删除元素
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle) # 也可使用pop()来删除最右端即末尾的元素,可继续使用该元素,类比于栈;pop(0)括号内数字代表索引,不填则默认末尾
bicycles.remove('galaxy') # remove可直接删除元素,元素可继续使用(屁话)
cars.reverse() # 倒着打印列表
print(cars)
print(len(cars))# 打印列表长度
排序
- sort()
# sort()永久排序,即原列表改变
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars.sort(reverse = True) # 按字典序相反排列,注:True一定要大写
print(cars)
- sorted()
# sorted()临时排序,原列表不改变
print(sorted(cars))
print(cars)
print(sorted(cars, reverse = True)) # 按字典序相反排列,注:True一定要大写
print(cars)
遍历列表
# for循环(代码是真的简单)
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title())
print("Thank you, everyone. That was a great magic show!")
print("\n")
创建数值列表(range()函数的使用)
# 直接打印数字,打一个换一行
for value in range(1, 5): # 不会打印数字5
print(value)
# 创建数字列表[1, 2, 3, 4, 5]
numbers = list(range(1, 6))
print(numbers)
# 指定步长,打印10以内的偶数
numbers = list(range(2, 11, 2))
print(numbers)
# 打印11以内的平方数
squares = []
for value in range(1, 11):
squares.append(value ** 2) # **表示乘方运算
print(squares)
# 最小值、最大值、总和
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
# 列表解析, 一行代码生成上述列表
squares = [value ** 2 for value in range(1, 11)]
print(squares)
print("\n")
切片(操作部分列表)
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0 : 3])
print(players[: 3])
print(players[1 : 4])
print(players[2 :])
print(players[-3 :]) # 负索引表示返回末尾相应距离的元素
# 遍历切片
for player in players[: 3]:
print(player)
# 复制列表
my_players = players[:] # 非切片不能用"=","="意味着两个列表指向同一列表,非复制
print(players)
print(my_players)
元祖(不可变的值的列表)
dimensions = (200, 50) # 元祖用()不用[],且值不可修改
print(dimensions[0])
print(dimensions[1])
# 遍历元祖中所有值
for dimension in dimensions:
print(dimension)
# 修改元祖变量(重新定义元祖)
for dimension in dimensions:
print(dimension)
dimensions = (400, 200)
for dimension in dimensions:
print(dimension)
逻辑
Python中的逻辑用的是 and or 和 not
检查元素是否位于列表中可直接用 in (这是我见过最方便的!!!)
#检查特定值是否在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
#检查特定值是否不在列表中
print('pepperoni' not in requested_toppings)
if条件
# 多个if条件
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 $10.")
# 确定列表非空
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza")
else:
print("Are you sure you want a plain pizza?") # 为空执行else
字典(即结构体)
基本操作
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points']) # 打印值
# 添加键-值对
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#修改字典中的值
alien_0['color'] = 'yellow'
print(alien_0)
# 删除键-值对
print(alien_0)
del alien_0['speed']
print(alien_0)
#剔除重复项
for language in set(favorite_languages.values()):
print(language.title())
由类似对象组成的字典(同类型多元素)
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")
# 不同个体同一类型元素包含多个时
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())
遍历
# 遍历所有的键-值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
# 遍历所有键
for name in favorite_languages.keys():
print(name.title())
#遍历指定人的键-值对
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")
# 按顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# 遍历所有值
for language in favorite_languages.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("...")
print("Total number of aliens: " + str(len(aliens)))
# 循环修改
for alien in aliens[: 3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[: 5]:
print(alien)
print("...")
字典存列表(数组结构体)
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)
字典存字典(禁止套娃!!!)
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
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())
输入
name = input("Tell me your name: ")
print("Hello, " + name + "!")
# 储存变量并传递
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name? " # 精髓 +=
name = input(prompt)
print("Hello, " + name + "!")
# 获取数值输入
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride! ")
else:
print("\nYou'll be able to ride when you're a little older.")
# 使用用户输入来填充字典
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? (yes/no) ")
if repeat == 'no':
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
函数
# 问候语
def greet_user(username):
print("Hello, " + username.title() + "! ")
greet_user('lsilencej')
种类
- 位置实参(顺序)
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + " whose name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
describe_pet('dog', 'wille') # 多次调用
- 关键字实参(无序)
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + " whose name is " + pet_name.title() + ".")
describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'dog', animal_type = 'wille') # 多次调用
传递与返回
# 返回值
def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
# 返回字典
def build_person(first_name, last_name):
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
# 传递列表
def greet_user(names):
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_user(usernames)
# 函数中修改列表
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
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', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
# 传递任意数量的形参
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)
类
可以玩各种各样的操作,构建出一个个不存在的实体
# Dog
class Dog():
def __init__(self, name, age): # init前后各有两个_即__
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)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " year old.")
my_dog.sit()
my_dog.roll_over()
your_dog = Dog('lucy', 3)
print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " year old.")
your_dog.sit()
your_dog.roll_over()
print("\n")
# Car
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.read_odometer()
my_new_car.update_odometer(23) # 也可直接修改: my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# Battery(用作属性)
class Battery():
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.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 60:
range = 270
msg = "This car can go approximately " + str(range)
msg += " miles on a full charge"
print(msg)
# ElectricCar(继承)
class ElectricCar(Car):
def __init__(self, make, model, year): # 初始化父类属性
super().__init__(make, model, year) # 初始化
self.battery = Battery()
def update_odometer(self, mileage): # 重写父类的方法
print("Error!")
my_tesla = ElectricCar('tesla', 'model s', '2016')
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.update_odometer(13)
my_tesla.battery.get_range()
最后献上Python之禅:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!
你可以在Python编译器中输入以下内容看见它:
import this