Python 学习笔记——Code with mash
-
-
- II- Python Basics
-
-
-
- 1- Variables
- 2- Dynamic Typing
- 3- Type Annotation(注释)
- 4- Mutable and Immutable Types
- 5- Strings
- 6- Escape Sequences
- 7- Formatted Strings
- 8- Useful String Methods
- 9- Numbers
- 10- Arithmetic Operators
- 11- Working with Numbers(函数用法搜索)
- 12- Type Conversion
- 13- Conditional Statements
- 14- Logical Operators
- 15- Ternary (三进制,三元的) Operator
- 16- For Loops
- 第五天晚上
- 日结
- 第六天下午
-
-
- III- Data Structures
- IV- Exceptions
- V- Classes
-
-
- 2020/05/07 第十三天下午
- 2020/05/09 第十五天早上,昨天终于把房间安置好了
-
- 7- Comparing Objects
- 8- Performing Arithmetic Operations
- 9- Making Custom Containers
- 10- Private Members
- 11- Properties
- 12- Inheritance
- 13- The Object Class
- 14- Method Overriding
- 15- Multi-level Inheritance
- 16- Multiple Inheritance
- 17- A Good Example of Inheritance
- 18- Abstract Base Classes
- 19- Polymorphism
- 20- Duck Typing
- 21- Extending Built-in Types
- 22- Data Classes
-
-
初学者买的Youtube上的Python教程,因为工作在身,会不定时更新笔记,如果有人需要资源,可以留言,我会共享。
笔记公开,希望有兴趣的同行者,我们一起努力。
第一章是非常基础的东西,所以就没记笔记。
II- Python Basics
1- Variables
#分配变量小技巧
x = 1
y = 2
#上下三组赋值效果一致
x, y = 1, 2
x = y = 1
2- Dynamic Typing
不同于C语言,在python里,某一个变量的种类(class)不是固定的。
3- Type Annotation(注释)
age: int = 20
# int 就是 Annotation,用于标注变量类型
# 如果linter 是 mypy,改变同一变量的类型,mypy就会报错
4- Mutable and Immutable Types
x = 1
print(id(x))
# 140705238406816
x = x + 1
print(id(x))
# 140705238406848
From above results, we can definitely get the conclusion that integer variables are immutable. Moreover, whenever the value of an integer variable is changed, Python will allocate a new memory address for the variable, with the same name, and the former memory will be released as nothing refers to it.
List is changeable.
5- Strings
Index is simply explained in the official tutorial book, and the demonstration is fantastic.
course = 'Python Programming'
print(len(course))
# this function can be used to calculate the length of a string
# or the item number of a set
print(course[0])
print(course[-2])
print(course[0:3])
print(course[:3])
print(course[0:])
print(course[:])
# these above functions are slice function
print(id(course))
print(id(course[0]))
whenever a string is sliced, Python will automatically create a copy of the string with a different type and memory address.
The above two results/addresses are different.
String is immutable variable but list is mutable.
6- Escape Sequences
- \ (backslash) is escape character(转义字符) in Python
- to remove the specialty of \ is to mark r before the string
print(r'D:\BaiduNetdisk\Download')
# in this case, \ will display as wish
- \n new line
7- Formatted Strings
first_name = 'John'
last_name = 'Smith'
full_name = f'Hello, {first_name} {last_name}'
full_name = 'Hello, {} {}'.format(first_name, last_name)
# the result of line 3 is identical to that of line 4
# personally, I prefer the first one; It's much more easy to type
# line 4 has similiar syntax to C#
# in C#, the code is like this:
# console.WriteLine("Hello,{0} {1}", first_name, last_name)
full_name = f'Hello, {len(first_name)} {4+5}'
# You can put any value in curly braces
# it works as if there is no quote.
You can put any value in curly braces, and it works as if there is no quote.
8- Useful String Methods
You can check all the methods within VScode. Follow the steps below
course = 'Python Programming'
course.
course.strip()
# 去前后空格
9- Numbers
Python 支持二进制和十六进制,数字的写法和转化methods如下
x = 0b10
print(bin(x))
y = 0x12c
print(hex(y))
于此同时,Python可以做复数和高数运算
10- Arithmetic Operators
x = 10//3
# 除法求整数
x = 10 % 3
# 余数
x = 10**3
# 指数运算
x = 10**(-3)
# 开方运算
11- Working with Numbers(函数用法搜索)
In Python, unlike languages like JS or C#, there is no constant, so, by convention, we use uppercase letters to tell other developers that the uppercased variable should be considered as a constant and not be modified.
Google “python 3 built-in functions” to get more information.
For the functions of modules, for example, the math module, you can google “python 3 math module.”
12- Type Conversion
x = 1
print(int(x))
print(float(x))
print(bool(x))
# Falsy Vaule in Python(like JS)
# "" is empty string
# 0
# [] is empty list
# None (null in C languages)
13- Conditional Statements
In Python, unlike C languages, we use indentation (缩进) to specify code block( like {} in C#).
Python is a language very sensitive to line and indentation.
if condition:
pass
# pass works like placeholder
elif condition:
pass
else:
pass
14- Logical Operators
In Python, there are three logical operators: and, or, and not
name = ""
if not name:
print("name is empty")
# This is hard to understand at the first glance
# Basically, NOT operator returns a Boolean value
# If the Boolean Value is FASLE
# the condition is met
name = " "
# a space within quote
if not name.strip():
print("name is empty")
# use strip method to remove space to get False value
# Otherwise, it won't work
age = 22
if age > 18 and age < 60:
if 18 < age < 60:
# line 17 and line 18 has the same function in Python.
15- Ternary (三进制,三元的) Operator
类似C#里的问号冒号表达式,Python也有三元表达方式
age = 20
message = "Eligible" if age > 18 else "Not Eligible"
print(message)
16- For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in range(0, 10, 2):
print(x)
# range (起始数,最终数,step)
# 起始数和最终数都是inclusive,step默认是1
# range function is not a list, but a special class called range.
# range class is iterable in Python, and is similiar to list, string etc.
a = "xiaozhan is a good girl"
for x in a:
print(x, end="")
# or
print(a.split())
# in for loop, you don't need to define the x as a vriable
# x will be defined automatically and only works in the loop
第五天晚上
17- For…Else
Else 的理解和C#一样,不必多说
18- While Loops
While Loop 和 For Loop的不同之处
For loop 会依次的把所有的item执行完,如果检索到需要的item,需要用到break命令来退出
while如果要实现上述功能,则不需要,因为它的结束条件是可以自定义的
for loop的优势就在于处理列表的时候,会非常的方便。
19- Functions
def increment(number: int, by: int = 1) -> tuple:
return (number, number + by)
# 可以在函数里,定义输入参数的类型,以及默认值
# 可以在函数里,定义输出的类型
print(increment(3))
20- Arguments- 、*args(* 号形参)
def multiply(*list):
total = 1
for numbers in list:
total *= numbers
return total
print(multiply(2, 3, 4, 5))
# 这种函数能实现任意数字的相乘,不会限制数字的数量
# 原理是用*unpack吗,爱了爱了
日结
忙了一天,抽烟太多,头痛,看不下去,鸽了
第六天下午
21- Arguments- **args
def save_user(**user):
print(user)
save_user(id=1, name='admin')
# **符号似乎是在使用function的时候定义variable的keyword
# Mosh说和JS的object很像,暂时不是很理解,需要后续补充
# 后续补充
# ** 用来unpack一个dictionary
原理查看[Unpacking Operator](#22- Unpacking Operator)
22- Scope
In Python, we have two types of variables: Local in function scope and Global in file scope.
In Python, unlike languages C# or JS, there is no block-level scope , which means we can definitely use a inside-if-clause variable outside the clause.
Specifically, in C# we always use variable i to start a loop, but the variable can’t be use outside this loop
for (int i = 0, i < 5, i ++)
{
console.WriteLine(i)
}
int a = i + 1;
Console.WriteLine(a)
// after this loop is finished, the value of i would be 5.
// but outside the loop, we can't use i because it is defined
// inside of the loop, but in Python, we can
Try this code in Python
for i in range(0, 6):
print(i)
a = i + 1
print(a)
Be ware, don’t change the value of a global variable in a function, otherwise you will get some side-effect.
Below is a bad practice, don’t do it except you have to.
message = 'a'
def greet():
global message
# used to tell Python that you want to change
# the global variable inside a function
message = 'b'
greet()
print(message)
23- Debugging
F9 下断点
F10 下一步
F11 进入函数
24- VSCode Coding Tricks - Windows
几个实用的快捷键:
Home,End:当前行光标控制
ctrl+Home,ctrl+End:全文光标控制
Alt+上下箭头:移动当前选中行
Shift+Alt+上下箭头:选中自动向下当前选中行复制
25- VSCode Coding Tricks - Mac
FUNCTION+左右
FUNCTION+上下
ALT or OPTION +上下
26- Exercise
Fizz Buzz 问题
给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
- 如果这个数被3整除,打印
fizz
. - 如果这个数被5整除,打印
buzz
. - 如果这个数能同时被
3
和5
整除,打印fizz buzz
.
def fizz_buzz(number):
if number % 15 == 0:
return "fizz buzz"
if number % 3 == 0:
return "fizz"
if number % 5 == 0:
return "buzz"
return number
print(fizz_buzz(99