【精华帖】一张图学习所有Python常用语法 —— Python Cheat Sheet
在学习Python的时候,是不是经常觉得不够语法系统和凝练,
下面一张图学习所有Python常用语法 —— Python Cheat Sheet来了
涵盖以下内容
1. 基本要点
2. 条件函数 Conditional Statements
3. 列表 Lists
4. 数值 Numbers
5. 字符串 Strings
6. 元组 Tuples
7. 字典 Dictionaries
8. For 循环 For Lops
9. While 循环 While Lops
10. 函数 Functions
11. 类 Class
基本上包括了入门学习的方方面面
首先是基本要点
- 空格和缩进在Python中非常重要,缩进在python中是区别程序结构的唯一方法,所以慎用空格和缩进,同时也可以保持代码整洁。
- 使用import 来导入第三方模块
- 使用#来进行注释
- 使用print(“你好”)来输出内容
- ’ 和 " 和 ‘’’ 和 “”" 是一样的,单引号和双引号和三个单引号和三个双引号的作用一样,都是表示字符串
后面就是一些测试的内容了,大家可以上手多试一试。
测试的话推荐使用Jupyter Notebook,即方便又美观。
一张图学习所有Python常用语法 —— Python Cheat Sheet
条件函数 Conditional Statements
if isSunny: print("It's sunny!")elif 90 <= temp < 100 and bath > 80: print('Bath is hot and full!')elif not ((job == 'qa') or (usr == 'adm')): print('Match if not qa or adm')else: print('No match. Job is ' + job)
列表 Lists
scores = ['A', 'C', 90, 75, 'C']scores[0] # 'A'scores[1:3] # 'C', 90scores[2:] # 90, 75, 'C'scores[:1] # 'A'scores[:-1] # 'A', 'C', 90, 75len(scores) # 5scores.count('C') # 2scores.sort() # 75, 90, 'A', 'C', 'C'scores.remove('A') # removes 'A' scores.append(100) # Adds 100 to listscores.pop() # removes the last itemscores.pop(2) # removes the third item75 in scores # True
数值 Numbers
total = 3 * 3 # 9total = 5 + 2 * 3 # 11cost = 1.50 + 3.75 # 5.25total = int("9") + 1 # 10
字符串 Strings
title = 'Us and them'# most list operations work on stringstitle[0] # 'U'len(title) # 11title.split(' ') # ['Us', 'and', 'them']':'.join(['A','B','C']) # 'A:B:C'nine = str(9) # convert int to stringtitle.replace('them', 'us') # Us and usStringstotal
元组 Tuple
# Like lists, except they cannot be changedtuple1 = (1,2,3,"a","z") # Creates tupletuple1[3] # 'a'
字典 Dictionaries
votes = {'red': 3, 'blue': 5}votes.keys() # ['blue', 'red']votes['gold'] = 4 # add a key/valdel votes['gold'] # deletes keyvotes['blue'] = 6 # change valuelen(votes) # 2votes.values() # [6, 3]'green' in votes # Falsevotes.has_key('red') # TrueDictionaries
For 循环 For Lops
grades = ['A', 'C', 'B', 'F'] for grade in grades: # iterate over all valsprint (grade)for k,v in enumerate(grades): # using key value pair if v=='F': grades[k]='A' # change all Fs to Asinv = {'apples': 7, 'peaches': 4}for fruit, count in inv.items(): # using dictionaries print("We have {} {}".format(count, fruit))for i in range(10): # 0 to 9 counting by 1 stepfor i in range(5, 10): # 5 to 9 counting by 1 stepfor i in range(9, 2, -1): # 9 to 3 decreasing by 1 step
While 循环 While Lops
i = 0while True: i += 1 if i == 3: continue # go to next loop if i == 7: break # end loop print(i) # 1 2 4 5 6votes
函数 Functions
def sumNums(numOne, numTwo = 0): return numOne + numTwoprint(sumNums(3,4)) # 7print(sumNums(3)) # 3
类 Class
class Person: def __init__(self, name, age): self.name = name self.age = age def birthYear(self): return year - self.ageuser = Person('Jimmi', 27)user.name = 'Jim'print(user.name) # prints Jimprint(user.birthYear())
下图欢迎收藏带走