Python做为一个开源的优秀语言,随着它在数据分析和机器学习方面的优点,已经获得愈来愈多人的喜好。听说小学生都要开始学Python了。python
Python的优秀之处在于能够安装不少很是强大的lib库,从而进行很是强大的科学计算。git
讲真,这么优秀的语言,有没有什么办法能够快速的进行学习呢?github
有的,本文就是python3的基础秘籍,看了这本秘籍python3的核心思想就掌握了,文末还有PDF下载连接哦,欢迎你们下载。编程
python中全部的值均可以被看作是一个对象Object。每个对象都有一个类型。app
下面是三种最最经常使用的类型:less
整数类型,好比: -2, -1, 0, 1, 2, 3, 4, 5机器学习
浮点类型,好比:-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25编程语言
字符串类型,好比:“www.flydean.com”ide
注意,字符串是不可变的,若是咱们使用replace() 或者 join() 方法,则会建立新的字符串。函数
除此以外,还有三种类型,分别是列表,字典和元组。
列表用方括号表示: a_list = [2, 3, 7, None]
元组用圆括号表示: tup=(1,2,3) 或者直接用逗号表示:tup=1,2,3
python中String有三种建立方式,分别能够用单引号,双引号和三引号来表示。
my_string = “Let’s Learn Python!” another_string = ‘It may seem difficult first, but you can do it!’ a_long_string = ‘’‘Yes, you can even master multi-line strings that cover more than one line with some practice’’’
也可使用print来输出:
print(“Let’s print out a string!”)
String可使用加号进行链接。
string_one = “I’m reading “ string_two = “a new great book!” string_three = string_one + string_two
注意,加号链接不能链接两种不一样的类型,好比String + integer,若是你这样作的话,会报下面的错误:
TypeError: Can’t convert ‘int’ object to str implicitly
String可使用 * 来进行复制操做:
‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’
或者直接使用print:
print(“Alice” * 5)
咱们看下python中的数学操做符:
操做符 | 含义 | 举例 |
---|---|---|
** | 指数操做 | 2 * 3 = 8* |
% | 余数 | 22 % 8 = 6 |
// | 整数除法 | 22 // 8 = 2 |
/ | 除法 | 22 / 8 = 2.75 |
***** | 乘法 | 3*3= 9 |
- | 减法 | 5-2= 3 |
+ | 加法 | 2+2= 4 |
咱们前面已经学过了python中内置的函数print(),接下来咱们再看其余的几个经常使用的内置函数:
input用来接收用户输入,全部的输入都是以string形式进行存储:
name = input(“Hi! What’s your name? “) print(“Nice to meet you “ + name + “!”) age = input(“How old are you “) print(“So, you are already “ + str(age) + “ years old, “ + name + “!”)
运行结果以下:
Hi! What’s your name? “Jim” Nice to meet you, Jim! How old are you? 25 So, you are already 25 years old, Jim!
len()用来表示字符串,列表,元组和字典的长度。
举个例子:
# testing len() str1 = “Hope you are enjoying our tutorial!” print(“The length of the string is :”, len(str1))
输出:
The length of the string is: 35
filter从可遍历的对象,好比列表,元组和字典中过滤对应的元素:
ages = [5, 12, 17, 18, 24, 32] def myFunc(x): if x < 18: return False else: return True adults = filter(myFunc, ages) for x in adults: print(x)
python中,函数能够看作是用来执行特定功能的一段代码。
咱们使用def来定义函数:
def add_numbers(x, y, z): a= x + y b= x + z c= y + z print(a, b, c) add_numbers(1, 2, 3)
注意,函数的内容要以空格或者tab来进行分隔。
函数能够传递参数,并能够经过经过命名参数赋值来传递参数:
# Define function with parameters def product_info(productname, dollars): print("productname: " + productname) print("Price " + str(dollars)) # Call function with parameters assigned as above product_info("White T-shirt", 15) # Call function with keyword arguments product_info(productname="jeans", dollars=45)
列表用来表示有顺序的数据集合。和String不一样的是,List是可变的。
看一个list的例子:
my_list = [1, 2, 3] my_list2 = [“a”, “b”, “c”] my_list3 = [“4”, d, “book”, 5]
除此以外,还可使用list() 来对元组进行转换:
alpha_list = list((“1”, “2”, “3”)) print(alpha_list)
咱们使用append() 来添加元素:
beta_list = [“apple”, “banana”, “orange”] beta_list.append(“grape”) print(beta_list)
或者使用insert() 来在特定的index添加元素:
beta_list = [“apple”, “banana”, “orange”] beta_list.insert(“2 grape”) print(beta_list)
咱们使用remove() 来删除元素
beta_list = [“apple”, “banana”, “orange”] beta_list.remove(“apple”) print(beta_list)
或者使用pop() 来删除最后的元素:
beta_list = [“apple”, “banana”, “orange”] beta_list.pop() print(beta_list)
或者使用del 来删除具体的元素:
beta_list = [“apple”, “banana”, “orange”] del beta_list [1] print(beta_list)
咱们可使用+来合并两个list:
my_list = [1, 2, 3] my_list2 = [“a”, “b”, “c”] combo_list = my_list + my_list2 combo_list [1, 2, 3, ‘a’, ‘b’, ‘c’]
咱们还能够在list中建立list:
my_nested_list = [my_list, my_list2] my_nested_list [[1, 2, 3], [‘a’, ‘b’, ‘c’]]
咱们使用sort()来进行list排序:
alpha_list = [34, 23, 67, 100, 88, 2] alpha_list.sort() alpha_list [2, 23, 34, 67, 88, 100]
咱们使用[x:y]来进行list切片:
alpha_list[0:4] [2, 23, 34, 67]
咱们能够经过index来改变list的值:
beta_list = [“apple”, “banana”, “orange”] beta_list[1] = “pear” print(beta_list)
输出:
[‘apple’, ‘pear’, ‘cherry’]
咱们使用for loop 来进行list的遍历:
for x in range(1,4): beta_list += [‘fruit’] print(beta_list)
可使用copy() 来进行list的拷贝:
beta_list = [“apple”, “banana”, “orange”] beta_list = beta_list.copy() print(beta_list)
或者使用list()来拷贝:
beta_list = [“apple”, “banana”, “orange”] beta_list = list (beta_list) print(beta_list)
list还能够进行一些高级操做:
list_variable = [x for x in iterable] number_list = [x ** 2 for x in range(10) if x % 2 == 0] print(number_list)
元组的英文名叫Tuples,和list不一样的是,元组是不能被修改的。而且元组的速度会比list要快。
看下怎么建立元组:
my_tuple = (1, 2, 3, 4, 5) my_tuple[0:3] (1, 2, 3)
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) print(numbers[1:11:2])
输出:
(1,3,5,7,9)
可使用list和tuple进行相互转换:
x = (“apple”, “orange”, “pear”) y = list(x) y[1] = “grape” x = tuple(y) print(x)
字典是一个key-value的集合。
在python中key能够是String,Boolean或者integer类型:
Customer 1= {‘username’: ‘john-sea’, ‘online’: false, ‘friends’:100}
下面是两种建立空字典的方式:
new_dict = {} other_dict= dict()
或者像下面这样来初始赋值:
new_dict = { “brand”: “Honda”, “model”: “Civic”, “year”: 1995 } print(new_dict)
咱们这样访问字典:
x = new_dict[“brand”]
或者使用dict.keys()
,dict.values()
,dict.items()
来获取要访问的元素。
咱们能够这样修改字典的元素:
#Change the “year” to 2020: new_dict= { “brand”: “Honda”, “model”: “Civic”, “year”: 1995 } new_dict[“year”] = 2020
看下怎么遍历字典:
#print all key names in the dictionary for x in new_dict: print(x) #print all values in the dictionary for x in new_dict: print(new_dict[x]) #loop through both keys and values for x, y in my_dict.items(): print(x, y)
和其余的语言同样,python也支持基本的逻辑判断语句:
看下在python中if语句是怎么使用的:
if 5 > 1: print(“That’s True!”)
if语句还能够嵌套:
x = 35 if x > 20: print(“Above twenty,”) if x > 30: print(“and also above 30!”)
elif:
a = 45 b = 45 if b > a: print(“b is greater than a”) elif a == b: print(“a and b are equal”)
if else:
if age < 4: ticket_price = 0 elif age < 18: ticket_price = 10 else: ticket_price = 15
if not:
new_list = [1, 2, 3, 4] x = 10 if x not in new_list: print(“’x’ isn’t on the list, so this is True!”)
Pass:
a = 33 b = 200 if b > a: pass
python支持两种类型的循环,for和while
for x in “apple”: print(x)
for能够遍历list, tuple,dictionary,string等等。
#print as long as x is less than 8 i =1 while i< 8: print(x) i += 1
i =1 while i < 8: print(i) if i == 4: break i += 1
Python做为一个面向对象的编程语言,几乎全部的元素均可以看作是一个对象。对象能够看作是Class的实例。
接下来咱们来看一下class的基本操做。
class TestClass: z =5
上面的例子咱们定义了一个class,而且指定了它的一个属性z。
p1 = TestClass() print(p1.x)
还能够给class分配不一样的属性和方法:
class car(object): “””docstring””” def __init__(self, color, doors, tires): “””Constructor””” self.color = color self.doors = doors self.tires = tires def brake(self): “”” Stop the car “”” return “Braking” def drive(self): “”” Drive the car “”” return “I’m driving!”
每个class均可以子类化
class Car(Vehicle): “”” The Car class “”” def brake(self): “”” Override brake method “”” return “The car class is breaking slowly!” if __name__ == “__main__”: car = Car(“yellow”, 2, 4, “car”) car.brake() ‘The car class is breaking slowly!’ car.drive() “I’m driving a yellow car!”
python有内置的异常处理机制,用来处理程序中的异常信息。
使用try,catch来处理异常:
my_dict = {“a”:1, “b”:2, “c”:3} try: value = my_dict[“d”] except KeyError: print(“That key does not exist!”)
处理多个异常:
my_dict = {“a”:1, “b”:2, “c”:3} try: value = my_dict[“d”] except IndexError: print(“This index does not exist!”) except KeyError: print(“This key is not in the dictionary!”) except: print(“Some other problem happened!”)
try/except else:
my_dict = {“a”:1, “b”:2, “c”:3} try: value = my_dict[“a”] except KeyError: print(“A KeyError occurred!”) else: print(“No error occurred!”)
本文已收录于 http://www.flydean.com/python3-cheatsheet/
最通俗的解读,最深入的干货,最简洁的教程,众多你不知道的小技巧等你来发现!
欢迎关注个人公众号:「程序那些事」,懂技术,更懂你!