查看原文
其他

Python学习笔记之入门

走天涯徐小洋 走天涯徐小洋地理数据科学 2022-05-17


Kaggle上面的Python课程可以一边看教程一边做练习,非常方便,在这里记录一下我的学习过程。点击下面的“阅读原文”即可导航到Kaggle教程页面。

函数

前面简单的就不说了,先记录一下最简单的数学函数:

OperatorNameDescription
a + ba, b相加
a - ba减b
a * ba,b相乘
a / ba除以b
a // b整除a除以b,保留整数
a % b余数a除以b,余下的数
a ** b乘方ab次方
-a负数负 a


自定义函数:

def least_difference(a, b, c): diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3)

这样就创建了一个名为“least_difference”的函数,它有三个变量“a, b, c”,其中“def”是声明函数的关键词,“:”后面的内容是当使用函数时执行的内容,“return”是函数的终止并输出右边的内容。

以一个具体包含数字的函数为例:

print( least_difference(1, 10, 100), least_difference(1, 10, 10), least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?)
输出结果:9 0 1

当函数中没有“return”时:

def least_difference(a, b, c): """Return the smallest difference between any two numbers among a, b and c. """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) min(diff1, diff2, diff3) print( least_difference(1, 10, 100), least_difference(1, 10, 10), least_difference(5, 6, 7),)
输出结果:None None None

当不声明“return”时,最后的返回结果是“None”,结果没有意义。


round函数的妙用:

round函数一般用于保留有效数字,当round为正数,保留小数点后,round为负数,向前取整

num = 5743.141592654round(num,2)5743.14
num = 5743.141592654round(num,-2)5700.0
num = 5753.141592654round(num,-2)5800.0

如上示例,第一个round取了两位有效数字,小数点后保留2位,第二个round参数为负数,向前取整两位,取整都是四舍五入,如后两个所示,第三个5753进行了五入,而第二个是四舍。


条件


Booleans

Python 有一种类型 bool 包含两个值: True 和 False.

x = Trueprint(x)print(type(x))输出:True<class 'bool'>

相比直接将 True 或 False 放到代码中, 我们一般通过 布尔运算 获得布尔值。 这些运算可以用来回答 yes/no 的问题.。以下是一些布尔运算符号。

Comparison Operations

OperationDescription
OperationDescription
a == ba 等于 b
a != ba 不等于 b
a < ba 小于 b
a > ba 大于 b
a <= ba 小于等于 b
a >= ba 大于等于 b
def can_run_for_president(age): """Can someone of the given age run for president in the US?""" # The US Constitution says you must "have attained to the Age of thirty-five Years" return age >= 35
print("Can a 19-year-old run for president?", can_run_for_president(19))print("Can a 45-year-old run for president?", can_run_for_president(45))#输出结果:Can a 19-year-old run for president? FalseCan a 45-year-old run for president? True

Combining Boolean Values

Python 提供合并布尔运算符 "且", "并", and "非"。对应的 Python 运算符是: andor, and not.

def can_run_for_president(age, is_natural_born_citizen): """Can someone of the given age and citizenship status run for president in the US?""" # The US Constitution says you must be a natural born citizen *and* at least 35 years old return is_natural_born_citizen and (age >= 35)
print(can_run_for_president(19, True))print(can_run_for_president(55, False))print(can_run_for_president(55, True))

Boolean conversion

我们知道 int(), 可以把值转换为整形, 以及 float(), 可以转换为浮点型, 同样 Python有一个 bool() 函数可以把其他值转换为布尔值。

print(bool(1)) # all numbers are treated as true, except 0print(bool(0))print(bool("asf")) # all strings are treated as true, except the empty string ""print(bool(""))# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)# are "falsey" and the rest are "truthy"输出结果:TrueFalseTrueFalse


列表


Lists 在 Python 代表了一系列有序的值:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Indexing索引

你可以使用方括号[ ]来索引到列表中单独的元素。 

哪个星球距离太阳最近? Python 索引基于0, 因此第一个元素的索引为0.

planets[0]'Mercury'planets[1]'Venus'

最远的是哪个星球呢?python倒数使用-1

planets[-1]'Neptune

Slicing切片

前三个星球是哪些? 我们可以使用切片slicing来回答这个问题:

planets[0:3]['Mercury', 'Venus', 'Earth']planets[:3]['Mercury', 'Venus', 'Earth']planets[3:]    #从索引3到最后['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']planets[1:-1] #去除首末剩余的元素['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus'planets[-3:]  #最后三个元素['Saturn', 'Uranus', 'Neptune']

Changing lists

列表是可以变的,我们可以按位置修改列表,如下,我们把“Mars”进行修改:

planets[3] = 'Malacandra'planets['Mercury', 'Venus', 'Earth', 'Malacandra', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

List functions列表函数

len 说明一个列表的长度:

# How many planets are there?len(planets)8

sorted生成一个排序后的列表:

# The planets sorted in alphabetical order根据字母顺序排序sorted(planets)['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus']

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存