Python基础

中途退出
exit()
使用缩进来标识代码块,而不是使用{}

空格至少有1个。

if 5 > 2:
  print("Five is greater than two!")
多行注释"""
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
快速赋值
x, y, z = "Orange", "Banana", "Cherry"
不能直接用+拼接数字和字符串
x = 5
y = "John"
print(x + y)#ERROR
内置数据类型
类型 标识
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = ==True== bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
用e或者E来表示底数10
x = 35e3
y = 12E4
z = -87.7e100
随机数
import random

print(random.randrange(1, 10))#a number in [1,10)
flont转int向下取整
y = int(2.8) # y will be 2
String常用的函数
  • strip()去掉字符串首尾空格
  • upper(), lower()大小写转换
  • replace()替换
  • split()分割字符串
  • 判断是否包含字串,innot in,类似Java中的contains()
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
  • +字符串拼接
  • 占位符使用
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
  • 其他常用函数
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

布尔值

首字母大写
True,False

  • 字符串
    不是空串为True,反之为False
  • 数字
    0:False,其他:True
  • 列表,元组,set,字典
    空集合:False,其他:True

总结,下面的代码均会返回False

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Python操作符
** 幂运算

z = x ** y # z = x ^ y

/浮点除法
//结果向下取整

浮点除和整数除

Python不用&&,||!,而是

python逻辑运算符

其他语言没有的操作符
in,not in

x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list

Python数据结构

  • 列表([]来表示)
thislist = ["apple", "banana", "cherry"]
print(thislist)

列表的增删改查

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
thislist.insert(1, "orange")
thislist.remove("banana")
thislist.pop()
del thislist[0]
thislist.clear()
del thislist
#复制list
mylist = thislist.copy()
mylist1 = list(thislist)
#合并list
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

构造函数,注意((,))

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

常用API


list api
  • 元组( 用()来表示)
    unchangeable
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

如果只要有一个元素,注意逗号

thistuple = ("apple",)
print(type(thistuple))#tuple

thistuple = ("apple")
print(type(thistuple))#str

tuple()构造函数

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
  • set
    unordered,unindexed,无序的,定义之后,无法确定它的顺序,所以不能通过下标的方式进行访问。
    set的增删改查
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")#添加单个元素
thisset.update(["orange", "mango", "grapes"])#添加过个元素
#If the item to remove does not exist, discard() ,remove() will NOT raise an error.
thisset.discard("banana")
thisset.remove("banana")
#两个set进行union
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

使用update()合并

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

set()构造函数

thisset = set(("apple", "banana", "cherry")) # 注意是双括号
print(thisset)
  • 字典Dictionary
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)
x = thisdict.get("model")
thisdict["year"] = 2018
#遍历key
for x in thisdict:
  print(x)
#遍历value
for x in thisdict.values():
  print(x)
#同时遍历key和value
for x, y in thisdict.items():
  print(x, y)
#删除
del thisdict["model"]

dict()构造函数

thisdict = dict(brand="Ford", model="Mustang", year=1964)
  • if else语句
    elif
a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

pass(什么都不做,作为占位符)

a = 33
b = 200

if b > a:
  pass
  • 函数
    def
def my_function():
  print("Hello from a function")

my_function()

变长参数的函数

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

带默认值的函数

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
  • Python Lambda
    lambda函数指的是一个小的匿名函数。
#可以有多个参数,但是只能有一个语句
lambda 参数: 语句
# 语句会被执行,然后返回结果

例如:

x = lambda a, b : a * b
print(x(5, 6))
  • 类和对象
class MyClass:
  x = 5

p1 = MyClass()
print(p1.x)

__init__()函数
每个类都有__init__(),初始化函数,(类似Java的构造函数)

class Person:
  def __init__(self, name, age):
# self类似Java的this指针,指向当前对象。
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

对象中添加方法:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
  • 继承
    父类:
class Person:
  def __init__(self, fname, lname):
    self.firstname = fname
    self.lastname = lname

  def printname(self):
    print(self.firstname, self.lastname)

子类:

class Student(Person):
  pass

调用父类的构造函数

class Student(Person):
  def __init__(self, fname, lname):
    super().__init__(fname, lname)#super()
    self.graduationyear = 2019#子类添加graduationyear 域

  def welcome(self):#子类添加方法,同名可以override父类方法。
      print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

  • 迭代器
    python的列表、set和字典都是可以迭代的,iter()返回一个迭代器。
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit)) 
  • Module模块
    module和库函数类似

创建:

#将代码保存为.py文件
#mymodule.py
def greeting(name):
  print("Hello, " + name)

使用:

import mymodule
mymodule.greeting("Jonathan")

重命名模块

import mymodule as mx

python自带

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355