0%

Mosh的Python课程笔记(2)--基本类型

Mosh的课程网址

Primitive Types

1
2
3
4
students_count = 1000
rating = 4.99
is_published = False # case sensitive (区分大小写)
course_name = "Python Programming"

String

1
2
3
4
5
6
course_name = "Python Programming"
message = """
Hi John
This is Stone from China
blablabla
"""
1
2
3
4
5
6
7
8
course_name = "Python Programming"
print(len(course_name)) # 18
print(course_name[0]) # P
print(course_name[-1]) # g
print(course_name[0:3]) # Pyt
print(course_name[0:]) # Python Programming
print(course_name[:3]) # Pyt
print(course_name[:]) # Python Programming

Escape Sequences

转义字符

1
2
3
course_name = "Python \"Programming"
print(course_name) # Python "Programming
# \" \' \\ \n

Formatted Strings

1
2
3
4
5
first = "Stone"
last = "Purple"
full = f"{first} {last}"
print(full) # Stone Purple
print(f"{len(first)} {2 + 2}") # 5 4

String Methods

1
2
3
4
5
6
7
8
9
course = "  Python Programming"
print(course.upper())
print(course.lower())
print(course.title())
print(course.strip()) # lstrip, rstrip
print(course.find("Pro"))
print(course.replace("P", "J"))
print("Pro" in course)
print("swift" not in course)

输出结果:

1
2
3
4
5
6
7
8
  PYTHON PROGRAMMING
python programming
Python Programming
Python Programming
9
Jython Jrogramming
True
True

Numbers

1
2
3
4
5
6
7
8
9
10
11
12
x = 1
x = 1.1
x = 1 + 2j # complex number

# + - * / % // **
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 ** 3) # 1000

x = 10
x = x + 3
x += 3

Working with Numbers

1
2
3
4
5
6
import math

print(round(2.9)) # 3
print(abs(-2.9)) # 2.9

print(math.ceil(2.2)) # 3

Type Conversion

1
2
3
4
x = input("x: ")
print(type(x))
y = int(x) + 1 # type conversion
print(f"x: {x}, y: {y}")
1
2
3
x: 2
<class 'str'>
x: 2, y: 3

对于bool(x),为 False 的情况只有:“”,0,None

1
print(bool(""))			# False

Quiz

👉 What are the primitive types in Python?

👉 What are the results?

1
2
3
fruit = "Apple"
print(fruit[1])
print(fruit[1:-1])

👉 What are the results?

1
2
print(10 % 3)
print(bool("False"))