This course covers the key Python skills you’ll need so you can start using Python for data science. The course is ideal for someone with some previous coding experience who wants to add Python to their repertoire. (If you're a first-time coder, you are encouraged to check out our Intro to Programming course, which is designed for complete beginners who would like to get started with Python.)
We'll start with a brief overview of Python syntax, variable assignment, and arithmetic operators.
本课程涵盖了您需要的关键 Python 技能,以便您可以开始使用 Python 进行数据科学。 对于具有一定编码经验、想要将 Python 添加到自己的技能库中的人来说,本课程是理想的选择。 (如果您是第一次编码,我们鼓励您查看我们的编程入门课程,该课程是为完全初学者设计的 谁想开始使用 Python。)
我们首先简要概述 Python 语法、变量赋值和算术运算符。
Hello, Python!
Python was named for the British comedy troupe Monty Python, so we'll make our first Python program a homage to their skit about Spam.
Just for fun, try reading over the code below and predicting what it's going to do when run. (If you have no idea, that's fine!)
Then click the "output" button to see the results of our program.
你好,Python!
Python 是以英国喜剧团 Monty Python 命名的,因此我们将让我们的第一个 Python 程序向他们关于 Spam 的短剧致敬。
只是为了好玩,尝试阅读下面的代码并预测它运行时会做什么。 (如果您不知道,那也没关系!)
然后点击“输出”按钮就可以看到我们程序的结果了。
spam_amount = 0
print(spam_amount)
# Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam)
spam_amount = spam_amount + 4
if spam_amount > 0:
print("But I don't want ANY spam!")
viking_song = "Spam " * spam_amount
print(viking_song)
0
But I don't want ANY spam!
Spam Spam Spam Spam
There's a lot to unpack here! This silly program demonstrates many important aspects of what Python code looks like and how it works. Let's review the code from top to bottom.
这里有很多东西需要解压! 这个愚蠢的程序演示了 Python 代码的外观及其工作原理的许多重要方面。 让我们从上到下回顾一下代码。
spam_amount = 0
Variable assignment: Here we create a variable called spam_amount
and assign it the value of 0 using =
, which is called the assignment operator.
Note: If you've programmed in certain other languages (like Java or C++), you might be noticing some things Python doesn't require us to do here:
- we don't need to "declare"
spam_amount
before assigning to it- we don't need to tell Python what type of value
spam_amount
is going to refer to. In fact, we can even go on to reassignspam_amount
to refer to a different sort of thing like a string or a boolean.
变量赋值: 这里我们创建一个名为spam_amount
的变量,并使用=
为其赋值0,这称为赋值运算符。
注意:如果您使用某些其他语言(如 Java 或 C++)进行编程,您可能会注意到 Python 不要求我们在这里做的一些事情:
- 我们不需要在分配之前“声明”
spam_amount
- 我们不需要告诉 Python
spam_amount
将引用什么类型的值。 事实上,我们甚至可以继续重新分配“spam_amount”来引用不同类型的事物,例如字符串或布尔值。
print(spam_amount)
0
Function calls:. print
is a Python function that displays the value passed to it on the screen. We call functions by putting parentheses after their name, and putting the inputs (or arguments) to the function in those parentheses.
函数调用:。 print
是一个 Python 函数,它在屏幕上显示传递给它的值。 我们通过在函数名称后面加上括号来调用函数,并将函数的输入(或参数)放在这些括号中。
# Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam)
spam_amount = spam_amount + 4
The first line above is a comment. In Python, comments begin with the #
symbol.
Next we see an example of reassignment. Reassigning the value of an existing variable looks just the same as creating a variable - it still uses the =
assignment operator.
In this case, the value we're assigning to spam_amount
involves some simple arithmetic on its previous value. When it encounters this line, Python evaluates the expression on the right-hand-side of the =
(0 + 4 = 4), and then assigns that value to the variable on the left-hand-side.
上面的第一行是注释。 在 Python 中,注释以“#”符号开头。
接下来我们看一个重新分配的例子。 重新分配现有变量的值看起来与创建变量一样 - 它仍然使用“=”赋值运算符。
在这种情况下,我们分配给“spam_amount”的值涉及对其先前值的一些简单算术。 当遇到这一行时,Python 会计算“=”右侧的表达式 (0 + 4 = 4),然后将该值赋给左侧的变量。
if spam_amount > 0:
print("But I don't want ANY spam!")
viking_song = "Spam Spam Spam"
print(viking_song)
But I don't want ANY spam!
Spam Spam Spam
We won't talk much about "conditionals" until later, but, even if you've never coded before, you can probably guess what this does. Python is prized for its readability and the simplicity.
Note how we indicated which code belongs to the if
. "But I don't want ANY spam!"
is only supposed to be printed if spam_amount
is positive. But the later code (like print(viking_song)
) should be executed no matter what. How do we (and Python) know that?
The colon (:
) at the end of the if
line indicates that a new code block is starting. Subsequent lines which are indented are part of that code block.
Note: If you've coded before, you might know that some other languages use
{
curly braces}
to mark the beginning and end of code blocks. Python's use of meaningful whitespace can be surprising to programmers who are accustomed to other languages, but in practice it can lead to more consistent and readable code than languages that do not enforce indentation of code blocks.
The later lines dealing with viking_song
are not indented with an extra 4 spaces, so they're not a part of the if
's code block. We'll see more examples of indented code blocks later when we define functions and using loops.
This code snippet is also our first sighting of a string in Python:
"But I don't want ANY spam!"
Strings can be marked either by double or single quotation marks. (But because this particular string contains a single-quote character, we might confuse Python by trying to surround it with single-quotes, unless we're careful.)
稍后我们不会过多讨论“条件”,但是,即使您以前从未编写过代码,您也可能猜到它的作用。 Python 因其可读性和简单性而备受推崇。
请注意我们如何指示哪些代码属于“if”。 “但是我不想要任何垃圾邮件!”仅当“spam_amount”为正时才会被打印。 但无论如何,后面的代码(如“print(viking_song)”)都应该执行。 我们(和 Python)如何知道这一点?
“if”行末尾的冒号(“:”)表示新的代码块正在开始。 缩进的后续行是该代码块的一部分。
注意:如果您以前编码过,您可能知道其他一些语言使用
{
花括号}
来标记代码块的开始和结束。 Python 对有意义的空格的使用可能会让习惯其他语言的程序员感到惊讶,但实际上,与不强制代码块缩进的语言相比,它可以生成更加一致和可读的代码。
后面涉及“viking_song”的行没有缩进额外的 4 个空格,因此它们不是“if”代码块的一部分。 稍后当我们定义函数和使用循环时,我们将看到更多缩进代码块的示例。
这段代码片段也是我们第一次在Python中看到字符串:
"But I don't want ANY spam!"
字符串可以用双引号或单引号标记。 (但是因为这个特定的字符串包含一个单引号字符,所以我们可能会因为尝试用单引号括起来而使 Python 感到困惑,除非我们很小心。)
viking_song = "Spam " * spam_amount
print(viking_song)
Spam Spam Spam Spam
The *
operator can be used to multiply two numbers (3 * 3
evaluates to 9), but we can also multiply a string by a number, to get a version that's been repeated that many times. Python offers a number of cheeky little time-saving tricks like this where operators like *
and +
have a different meaning depending on what kind of thing they're applied to. (The technical term for this is operator overloading.)
*
运算符可用于将两个数字相乘(3 * 3
计算结果为 9),但我们也可以将字符串与数字相乘,以获得已重复多次的版本。 Python 提供了许多厚颜无耻的节省时间的小技巧,比如*
和+
等运算符根据它们所应用的事物类型而具有不同的含义。 (其技术术语是运算符重载。)
Numbers and arithmetic in Python
We've already seen an example of a variable containing a number above:
Python 中的数字和算术
我们已经在上面看到了包含数字的变量的示例:
spam_amount = 0
"Number" is a fine informal name for the kind of thing, but if we wanted to be more technical, we could ask Python how it would describe the type of thing that spam_amount
is:
“Number”是此类事物的一个很好的非正式名称,但如果我们想要更技术化,我们可以询问 Python 它将如何描述“spam_amount”的事物类型:
type(spam_amount)
int
It's an int
- short for integer. There's another sort of number we commonly encounter in Python:
它是一个int
——整数的缩写。 我们在 Python 中经常遇到另一种数字:
type(19.95)
float
A float
is a number with a decimal place - very useful for representing things like weights or proportions.
type()
is the second built-in function we've seen (after print()
), and it's another good one to remember. It's very useful to be able to ask Python "what kind of thing is this?".
浮点数
是带有小数位的数字 - 对于表示重量或比例等内容非常有用。
type()
是我们见过的第二个内置函数(在 print()
之后),它也是一个值得记住的好函数。 能够询问 Python“这是什么东西?”是非常有用的。
A natural thing to want to do with numbers is perform arithmetic. We've seen the +
operator for addition, and the *
operator for multiplication. Python also has us covered for the rest of the basic buttons on your calculator:
Operator | Name | Description |
---|---|---|
|
||
|
||
|
||
|
||
, removing fractional parts |
||
|
||
|
||
|
One interesting observation here is that, whereas your calculator probably just has one button for division, Python can do two kinds. "True division" is basically what your calculator does:
想要对数字做的一件自然的事情就是进行算术运算。 我们已经看到了用于加法的“+”运算符和用于乘法的“*”运算符。 Python 还为我们介绍了计算器上的其余基本按钮:
操作员 | 名称 | 描述 |
---|---|---|
的总和 |
||
的区别 |
||
的乘积 |
||
的商 |
||
的商,删除小数部分 |
||
后的整数余数 |
||
次幂 |
||
的负数 |
这里的一个有趣的观察是,虽然你的计算器可能只有一个除法按钮,但 Python 可以做两种除法。 “真除法”基本上就是计算器的作用:
print(5 / 2)
print(6 / 2)
2.5
3.0
It always gives us a float
.
The //
operator gives us a result that's rounded down to the next integer.
它总是给我们一个浮点数
。
//
运算符给出的结果向下舍入到下一个整数。
print(5 // 2)
print(6 // 2)
2
3
Can you think of where this would be useful? You'll see an example soon in the coding challenges.
你能想到这在哪里有用吗? 您很快就会在编码挑战中看到一个示例。
Order of operations
The arithmetic we learned in primary school has conventions about the order in which operations are evaluated. Some remember these by a mnemonic such as PEMDAS - Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.
Python follows similar rules about which calculations to perform first. They're mostly pretty intuitive.
操作顺序
我们在小学学到的算术对于运算的评估顺序有约定。 有些人通过助记符来记住这些,例如 PEMDAS - Parentheses、Exponents、Multiplication/Division、Addition/Subtraction。
Python 遵循类似的规则来确定首先执行哪些计算。 他们大多非常直观。
8 - 3 + 2
7
-3 + 4 * 2
5
Sometimes the default order of operations isn't what we want:
有时默认的操作顺序并不是我们想要的:
hat_height_cm = 25
my_height_cm = 190
# How tall am I, in meters, when wearing my hat?
total_height_meters = hat_height_cm + my_height_cm / 100
print("Height in meters =", total_height_meters, "?")
Height in meters = 26.9 ?
Parentheses are useful here. You can add them to force Python to evaluate sub-expressions in whatever order you want.
括号在这里很有用。 您可以添加它们以强制 Python 按您想要的任何顺序计算子表达式。
total_height_meters = (hat_height_cm + my_height_cm) / 100
print("Height in meters =", total_height_meters)
Height in meters = 2.15
Builtin functions for working with numbers
min
and max
return the minimum and maximum of their arguments, respectively...
用于处理数字的内置函数
min
和 max
分别返回其参数的最小值和最大值...
print(min(1, 2, 3))
print(max(1, 2, 3))
1
3
abs
returns the absolute value of an argument:
abs
返回参数的绝对值:
print(abs(32))
print(abs(-32))
32
32
In addition to being the names of Python's two main numerical types, int
and float
can also be called as functions which convert their arguments to the corresponding type:
除了作为 Python 两种主要数值类型的名称之外,int
和float
也可以作为将其参数转换为相应类型的函数来调用:
print(float(10))
print(int(3.33))
# They can even be called on strings!
print(int('807') + 1)
10.0
3
808
Your Turn
Now is your chance. Try your first Python programming exercise!
# 到你了
现在是你的机会。 尝试你的 第一个 Python 编程练习!
Have questions or comments? Visit the course discussion forum to chat with other learners.