banner
NEWS LETTER

INT104-T1-Python

Scroll down

#INT104 #Python

这节课,正式开始了我们本学期的Python学习之旅。Python是一种易于学习的“解释性语言”:不需要预先编译,可以快速开发和测试代码 —— 这也是为什么 Python 文件运行的速度要比 C 为代表的编译型语言快得多的主要原因。

本篇文章总结了 tutorial 1 主要的语法知识点。(因为在这之前相信都有上学期的Java基础,所以以Python的语法特点为重点,对关键字的定义和用途不作过多解释。)
(前排提示老师给的notebook上面有这些知识的汇总,看那个也行)

Variable (变量)

1
2
3
4
5
x = 3
y = 4
z = x * y
answer = True
print(answer)

Types (类型)

types

Casting types (强制转换)

1
2
3
x = 10     # This is an integer
y = "20" # This is a string
z= x + int(y)

Strings (字符串)

1
2
3
4
5
x = "This can be"
y = "repeated "
z = x + " " + y * 3
x = x.upper() #字符串内容大写
x = x.lower() #字符串内容小写

Multiline strings (多行字符串)

1
2
3
4
x = """ To include
multiple lines
you have to do this"""
y = " or you can\ninclude the special\n character`\\n`between lines"

Lists (列表)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# a list of strings
fruits = ["apple", "orange", "tomato", "banana"]
fruits[2] # indexing a list
len(fruits) # the length of a list

# a list with integers
# Syntax : range(start point, end point, step size)
nums = list(range(0, 30, 5))
print(nums) # -> [0, 5, 10, 15, 20, 25] The end point is not included

# Slicing lists
# Syntax: List[start point : end point : step size ]
nums2 = list(range(0, 100, 5))
print(nums)
print(nums2[1:5:2]) # get from item 1(starting point) through item 5(end point, not included) with step size 2
print(nums2[0:3]) # get items 0 through 3
print(nums2[4:]) # get items 4 onwards
print(nums2[-1]) # get the last item
print(nums2[::-1]) # get the whole list backwards

# helpful functions
print(len(nums))
print(max(nums))
print(min(nums))

# lists can be of different types
mixed = [3, "Two", True, None]

Tuples(元组)

1
fruits = ("apple", "orange", "tomato", "banana")

那么问题来了,tuples和lists的区别是什么?
这里有一些解答:
tuplesvslists

Sets (集合)

1
2
3
x = {3, 3, 2, 1}       # a set created directly
y = set([1, 2, 3, 3]) # a set created from a list
x == y # True, x and y are the same object

Dictionaries (字典)

1
2
3
4
5
6
7
8
9
10
11
# Syntax: name = {key: value}
days = {"Monday": "1",
"Tuesday": "2"}
days["Monday"] # 1

days.update({"Saturday": "6"})

days.pop("Monday") # remove a day

print(days.keys()) # dict_keys(['Tuesday', 'Saturday'])
print(days.values()) # dict_values(['2', '6'])

如有错误,请及时指出~评论发邮件均可,欧内盖!

Other Articles
Article table of contents TOP
  1. 1. Variable (变量)
  2. 2. Types (类型)
  3. 3. Casting types (强制转换)
  4. 4. Strings (字符串)
  5. 5. Multiline strings (多行字符串)
  6. 6. Lists (列表)
  7. 7. Tuples(元组)
  8. 8. Sets (集合)
  9. 9. Dictionaries (字典)
Please enter keywords to search