一、Getting Started
如果使用的是mac或linux系统,需要输入 python3
比如运行 python3 app.py
可以直接在终端的>>>符号后执行python代码
print("*" * 10)
1、实现
在相关终端当运行“python”为CPython,这是python的默认实现
Jython -java
IronPython -C#
PyPy -用python的一部分编写的;Subset of python
二、Primitive Types
python中区分大小写,具有不同含义
布尔值始终以大写开头(FALSE也不可以)
is_published = False
pep8
规则
1、Strings
三引号用来格式化长字符串
message = """
Hi John,
This is Mosh
Blah blah blah
"""
print(message)
效果:
Hi John,
This is Mosh
Blah blah blah
变量[头下标:尾下标](后面那个是开区间)
course = "Python Programming"
print(len(course))
print(course[0])
print(course[-1])
print(course[0:3])
print(course[0:])
print(course[:3])
print(course[:])
效果:
18
P
g
Pyt
Python Programming
Pyt
Python Programming
2、Escape Sequences
course = 'Python "Programming'
print(course)
Python "Programming
course = "Python \"Programming"
print(course)
Python "Programming
\'
\"
\\
\n
3、Formatted Strings
first = "Mosh"
last = "Hamedani"
# full = first + " " + last
full = f"{first} {len(last)}"
print(full)
Mosh 8
也可以{2 + 2}
4、String Methods
python中所有东西都是对象
upper函数返回一个新的字符串,因此原先的字符串没有被改变
course = "Python Programming"
course_capital = course.upper()
print(course_capital)
print(course)
PYTHON PROGRAMMING
Python Programming
同上,lower()
;title()
(将所有单词!的第一个字符大写)
course = "python programming"
print(course.title())
Python Programming
strip()
将开头和结尾的所有空格去除,因此分别有lstrip()
和rstrip()
find("pro")
返回pro的下标,注意python大小写敏感。如果找不到返回-1
replace("p", "j")
将所有p换成j
print("Pro" in course)
返回的是布尔值,“True”;同理还有not in
5、Numbers
python中有三种numbers(第三种是complex number)
x = 1
x = 1.1
x = 1 + 2j # a + bi
print(10 / 3)
print(10 // 3)
print(10 ** 3)
3.3333333333333335
3
100
6、Working with Numbers
import math
print(round(2.9))
print(abs(-2.9))
print(math.ceil(2.2))
7、Type Conversion
用户输入的永远是字符串!
x = input("x: ")
print(type(x))
y = int(x) + 1
print(f"x: {x}, y: {y}")
# int(x)
# float(x)
# bool(x)
# str(x)
x: 2
<class 'str'>
x: 2, y: 3
8、Quiz
fruit = "Apple"
print(fruit[1:-1])
ppl
三、Control Flow
1、Comparison Operators
10 == "10" # False
因为这两个类型不同,而且在计算机内存中存放在不同地方
"bag" > "apple" # True
"bag" == "BAG" # False
ord("b") # 98
ord("B") # 66
2、Conditional Statements
temperature = 35
if temperature > 30:
print("It's warm")
print("Drink Water")
elif temperature > 20:
print("It's nice")
else:
print("It's cold")
print("Done")
3、Ternary Operator
age = 22
message = "Eligible" if age >= 18 else "Not eligible"
4、Logical Operators
and or not
5、Short-circuit Evaluation
in Python logical operators are short circuit
6、Chaining Comparison Operators
age = 22
if 18 <= age < 65:
print("Eligible")
7、For Loops
for number in range(3):
print("Attemp", number)
Attemp 0
Attemp 1
Attemp 2
可以看出print自动换行,range(x)是[0, x - 1]
for number in range(3):
print("Attemp", number + 1, (number + 1) * ".")
for number in range(1, 4):
print("Attemp", number, number * ".")
Attemp 1 .
Attemp 2 ..
Attemp 3 ...
for number in range(1, 10, 2):
print("Attemp", number, number * ".")
Attemp 1 .
Attemp 3 ...
Attemp 5 .....
Attemp 7 .......
Attemp 9 .........
8、For…Else
Note: The else block will NOT be executed if the loop is stopped by a break statement.
successful = False
for number in range(3):
print("Attemp")
if successful:
print("Successful")
break
else:
print("Attempted 3 times and failed")
Attemp
Attemp
Attemp
Attempted 3 times and failed
如果将上述的successful值设置为True:
Attemp
Successful
9、Iterables
print(type(5))
print(type(range(5)))
<class 'int'>
<class 'range'>
# Iterable
for x in "Python":
print(x)
for x in [1, 2, 3, 4]:
print(x)
10、While Loops
number = 100
while number > 0:
print(number)
number //= 2
100
50
25
12
6
3
1
四、Functions
1、Arguments
def greet(first_name, last_name):
print(f"Hi {first_name} {last_name}")
print("Welcome aboard")
greet("Mosh", "Hamedani")
2、Types of Functions
def greet(name):
print(f"Hi {name}")
def get_greeting(name):
return f"Hi {name}"
message = get_greeting("Mosh")
file = open("content.txt", "w")
file.write(message)
open()
返回一个file对象
然后调用file的write方法
3、Default Arguments
def increment(number, by=1):
return number + by
print(increment(2, 5))
7
4、*args
函数中数量可变的arguments
*
产生的是元组
def multiply(*numbers):
print(numbers)
multiply(2, 3, 4, 5)
(2, 3, 4, 5)
def multiply(*numbers):
total = 1
for number in numbers:
total *= number
return total
print(multiply(2, 3, 4, 5))
5、**args
**
产生的是字典
def save_user(**user):
print(user)
print(user["id"])
save_user(id=1, name="John", age=22)
{'id': 1, 'name': 'John', 'age': 22}
1
6、Scope
message = "a"
def greet(name):
global message
message = "b"
greet("Mosh")
print(message)
b
it will realize that in this function we want to use the global message variable, so it will not define a local variable in this function
五、Data Structures
0、Python Collections (Arrays)
There are four collection data types in the Python programming language:
List
is a collection which is ordered and changeable. Allows duplicate members.Tuple
is a collection which is ordered and unchangeable. Allows duplicate members.Set
is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.Dictionary
is a collection which is ordered** and changeable. No duplicate members.
1、Lists
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets []
List items are ordered, changeable, and allow duplicate(items with the same value) values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
numbers = [1, 2, 3, 4, 5]
numbers[0] # returns the first item
numbers[1] # returns the second item
numbers[-1] # returns the first item from the end
numbers[-2] # returns the second item from the end
print(len(numbers))
numbers.append(6) # adds 6 to the end
numbers.insert(0, 6) # adds 6 at index position of 0
numbers.remove(6) # removes 6
numbers.pop() # removes the last item
numbers.clear() # removes all the items
numbers.index(8) # returns the index of first occurrence of 8
numbers.sort() # sorts the list
numbers.reverse() # reverses the list
numbers.copy() # returns a copy of the list
List items can be of any data type:
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
list1 = ["abc", 34, True, 40, "male"]
mylist = ["apple", "banana", "cherry"]
print(type(mylist)) # <class 'list'>
It is also possible to use the list()
constructor when creating a new list.
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)