推荐《Python编程:从入门到实践》,很适合Python3入门,但是介绍的不深也不全。对于有经验的程序员一天就可看完,了解下基本语法即可。本文就是我看完对Python的语法的基本总结(只记录了Python的特殊之处),便于以后翻阅。
说下我看完本书对 Python3 语言的感觉:两个字:方便,三个字:真方便。
首先,语法结构简洁。
没有语句结尾的分号,没有包裹代码块的花括号,连注释都是一个字符 #,而不是两个斜线。
作为脚本语言,无需声明变量的类型,无需担心String和StringBuffer的效率问题,只管给变量起名然后赋值就行了。
其次,语法特性丰富。
取字符串最后一个字符:
Python3是
str[-1]
Java是
str.charAt(str.length() - 1)
去掉最后一个字符:
Python3是
str[:-1]
Java是
str.substring(0, str.length() -1)
看到这,我还能说什么呢。很明显,Java语法设计还停留在 C/C++ 的时代,而 Python 语法设计之初就考虑到很多便利性。
Python在大数据、在人工智能热潮中流行是有原因的。我相信这是未来的语言趋势。
人生苦短,我用Python
看来大佬们说的没错,所以我也来了。
================================================
== Python3语法简单说明
== ——针对Java程序员
== 摘自《Python编程:从入门到实践》
================================================
--------------------------------------------------
---- 基本语法
--------------------------------------------------
myVar = 1 #变量声明无需类型
#语句不需要分号 ;结束
# 字符串拼接换行需要缩进
print("AAA and " +
"BBB" +
"CCC")
# if-else语句
if ( name =="Tom" ):
print("Yes")
elif ():
print()
else:
print()
# 函数
def myFunction():
"""显示简单的问候语"""
print("Hello!")
myFunction()
----------------------------------------
---- 主要结构
----------------------------------------
---------列表 list-----------
myList[0]
myList[-2] # 倒数第二个元素
list.append()
list.insert(0,newval)
list.pop()
list.remove(val)
del list[3]
min(list),max(list), sum(list)
#生成列表[1,4,9,16....]
squares = [values**2 for values in range(1,11)]
#列表解析
range(1,3) # 左闭右开 1,2
numList[0:3] # 0,1,2 不返回numList[3]
list[:4] , list[2:]
#列表复制
newList = origalList[:]
#判断列表是否为空
if myList:
xxxx
#检查是否在列表中
'apple' in friut
'desk' not in friut
#for 循环是一种遍历列表的有效方式,但在for 循环中不应修改列表,否则将导致Python难以跟踪其中的元素。
#应使用 while循环修改列表元素。
---------- 元组---------------
#元组 Tuple,不可改变的列表,圆括号
myTuple = (200,50)
print myTuple[0] # 输出200
#元组变列表
list(myTuple)
--------字典,键值对---------
dic = {'color' : 'green', 'num' : 5}
print( dic['color'] )
#添加键值对
#键必须不可变,可以用数字,字符串或元组充当,但不能用列表
dic['newKey'] = 'newValue'
#添加或更新键值对
dic1 = {'color' : 'red', 'num':5}
dic2 = {'length' : '3'}
dic1.update(dic2)
#dic1就变成{'color' : 'red', 'num':5, 'length' : '3'}
#如果是重复键值,则是覆盖更新
#删除键值对
del dic['color']
dic.pop('color')
#多行键值对
mutiline = {
'first' : 'Tom',
'sec' : 'Jay',
}
#可预留最后一个逗号,方便下次增加元素
#遍历
for k,v in myDic:
print()
for k in myDic.keys():
print()
for v in myDic.values():
print()
if 'AAA' not in myDic.keys():
print()
#排序遍历
for name in sorted(myDic.keys()):
print()
#不重复输出值
for myVal in set(myDic.values()):
print(myVal)
---------循环-----------
#循环for语句后需加 冒号 :
for v in range(1,11):
#判断
#if语句后面需要加 冒号:
if (yourname == "Tom"):
xxx
else:
yyy
if () :
xxx
elif ():
yyy
else:
zzz
---- while ----
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
------------函数------------------
def describe_pet(pet_name, animal_type='dog'):
print(animal_type)
#return animal_type
describe_pet()
# 排版,可在函数定义中输入左括号后按回车键,
# 并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。
def function_name(
parameter_0, parameter_1, parameter_2,
parameter_3, parameter_4, parameter_5):
function body...
# 关键字实参
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
# 函数参数传入 列表副本,防止列表被修改
function_name(list_name[:])
# 不固定参数,将实参封装为元组
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)
-----------模块----------------
import myPyFile
myPyFile.myFun()
from myPyFile import myFun1, myFun2
myFun1()
myFun2()
from myPyFile import myFun1 as func
func()
import myPyFile as p
p.myFun()
=============类==============
-----------------【类结构】----------------------
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.")
----------------------------------------------------
#类的首字母大写,驼峰命名法
#方法 __init__() 为必须且首个参数必须为 self
#使用 self. 来引用 实例属性
--------------------【继承】----------------------
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init()__(make, model, year)
self.newAttr = 0
def myNewFun():
print("New Fun.")
----------------------------------------------------
#重名函数会覆盖父类的函数
from car import Car
from car import Car, ElectricCar
import Car
#先导入标准库,再换行导入自己编写的模块
-----------文件-------------
# 输出文件内容
with open('filepath\my.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
# 关键字with 在不再需要访问文件后将其关闭。
# 在这个程序中,注意到我们调用了open() ,但没有调用close() ;
# 你也可以调用open() 和close() 来打开和关闭文件,但
# 这样做时,如果程序存在bug,导致close() 语句未执行,文件将不会关闭。
# 这看似微不足道,但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早地调
# 用close() ,你会发现需要使用文件时它已关闭 (无法访问),这会导致更多的错误。
# 并非在任何情况下都能轻松确定关闭文件的恰当时机,但通过使用前面所示的结构,可
# 让Python去确定:你只管打开文件,并在需要时使用它,Python自会在合适的时候自动将其关闭。
# 因为read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。
# 需要使用 rstrip() 删除多余空行
# 逐行读取
with open('filepath\my.txt') as file_object:
for line in file_object:
print(line.rstrip())
# 因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,
# 因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。
# 要消除这些多余的空白行,可在print 语句中使用rstrip()
# 文件复制到列表中
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
-----------读取多个文件----------
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
----------写文件----------
# 需要手动添加换行符
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
----------异常---------------
try:
answer = int(first_number) / int(second_number)
print( )
except ZeroDivisionError:
print("Error: divide by zero!")
else:
print( answer )
----------存储数据-----------
#将数据保存为json文件存储到硬盘
#读取硬盘上的json文件的内容
import json
numbers = [2,3,5,7]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
-----
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
----------------------------------------
---- 代码案例
----------------------------------------
# 转移列表元素到新列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# 删除列表中指定元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
# Python将非空字符串解读为True
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('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
# 不固定参数,将实参封装为元组
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
是不是很简单,Python的语法对于Java程序员来说真的是简单。但是如果动手写个小工具,就还要需要了解Python的各种库了。Python很方便的在安装时打包了很多有用的库。剩下的可以自己主动去了解下。