学习python课程_想学习Python吗? 这是我们的免费4小时互动课程

学习python课程

Python is a popular, versatile and easy-to-learn language. It's the go-to language for AI, Machine Learning and Data Science. Some say it's also the easiest programming language to get started with.

Python是一种流行,通用且易于学习的语言。 它是AI,机器学习和数据科学的首选语言。 有人说它也是最容易上手的编程语言。

If this sounds like a programming language you want to learn, keep reading! Over the next few paragraphs, I'll guide you through the free 4-hour interactive Python course that we launched today.

如果这听起来像您想学习的编程语言,请继续阅读! 在接下来的几段中,我将指导您完成我们今天启动的免费的4小时交互式Python课程

This course aims to give you a solid foundation in both Python and basic programming in general. It's great for beginners looking for an interactive and engaging way to learn to code.

本课程旨在为您提供全面的Python和基础编程基础。 对于初学者来说,这是一种寻找互动且引人入胜的方法来学习编码的绝佳选择。

The course has been created by our brilliant teacher Olof Paulson, who's one of the advocates for the Khan Academy in Swedish. Olof has a background in finance, is experienced in writing algorithms, and has a passion for open and accessible education.

该课程是由我们杰出的老师Olof Paulson创建的,他是瑞典可汗学院的倡导者之一。 Olof具有金融背景,在编写算法方面经验丰富,并且热衷于开放式教育。

Now let's have a look at how the course is laid out!

现在让我们看一下课程的布局!

1.课程介绍 (1. Course Introduction)

This course covers all the topics you need to go from a beginner to an intermediate Python developer. It goes through:

本课程涵盖了从初学者到中级Python开发人员所需的所有主题。 它通过:

  • Outputting data and program flow

    输出数据和程序流程
  • Strings, Variables

    字符串,变量
  • Arithmetic operations and comparisons

    算术运算和比较
  • Lists, Tuples, Sets and Dictionaries

    列表,元组,集合和字典
  • Conditionals, if and elifs

    有条件的,如果和省略号
  • While and for loops

    While和for循环
  • Functions / Return Statements

    函数/返回语句
  • Objects, Classes and Inheritance

    对象,类和继承
  • List / Dictionary Comprehensions and Lambda functions

    列表/字典理解和Lambda函数
  • Modules

    模组

2.使用Brython在Scrimba上运行Python (2. Running Python on Scrimba with Brython)

To get a back-end language like Python to run on a front-end platform like Scrimba, we use the Brython plugin in the index.html file to recompile Python code into Javascript.

为了使像Python这样的后端语言能够在像Scrimba这样的前端平台上运行,我们使用index.html文件中的Brython插件将Python代码重新编译为Javascript。

Generally, we'll be using the minimum JS (brython.min.js) version but for more functionality, simply uncomment the standard lib version (brython_stdlib.js).

通常,我们将使用最低的JS( brython.min.js )版本,但要获得更多功能,只需取消注释标准lib版本( brython_stdlib.js )。

<head>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.0/brython.min.js"></script>
	<!--<script type="text/javascript"
     src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.0/brython_stdlib.js"></script>-->
</head>

It's also worth noting a few Brython oddities in Scrimba:

还应注意Scrimba中的一些Brython怪癖:

  1. The input() box is the JS prompt and not seen in the cast but works when you run local code.

    input()框是JS提示符,在强制转换中不可见,但在运行本地代码时有效。

  2. The Scrimba minibrowser sometimes hovers in the corner during some tutorials - you don't have to worry about it.

    在某些教程中,Scrimba微型浏览器有时会在角落徘徊-您不必担心。

3.打印语句和程序流程 (3. Print Statement and Programflow)

When we write Python, we often want to test that it is working as expected. To do this, we use the print() command to output data to the console.

在编写Python时,我们经常要测试它是否按预期工作。 为此,我们使用print()命令将数据输出到控制台。

print('Welcome to Python 101!')

Note: The computer reads code from top to bottom, so it runs commands nearer the top first.

注意:计算机从上到下读取代码,因此它将首先从顶部开始运行命令。

4.变量 (4. Variables)

Variables are used to save data for use later on. We declare variables using their name in lower case followed by the basic assignment operator (=). Note that if the variable name consists of more than one word, they should be separated with an underscore (_).

变量用于保存数据供以后使用。 我们使用小写的变量名声明变量,后跟基本赋值运算符( = )。 请注意,如果变量名包含多个单词,则应使用下划线( _ )分隔它们。

failed_subjects="6"

We use variables in our code by preceding them with a plus sign (+).

我们在代码中使用变量,方法是在变量前加一个加号( + )。

print('Your son Eric is failing' + failed_subjects + ' subjects.')

5.数据类型和类型转换 (5. Datatypes & Typecasting)

The basic datatypes of Python are:

Python的基本数据类型是:

  • Strings - these surrounded by two quotation marks (can be double or single quotes).

    字符串 -这些字符串用两个引号引起来(可以是双引号或单引号)。

  • Integers - these are whole numbers.

    整数 -这些是整数。

  • Floats - numbers with decimal points.

    花车 -用小数点的数字。

  • Booleans - these take on the value true or false.

    布尔值-取值为truefalse

To find out which data type you are using, use type()

要找出您正在使用哪种数据类型,请使用type()

print(type('hello'))

Note: If you want to use quotes or an apostrophe in a string, surround the entire string with double quotes. Alternatively, you can use Python's escape character, which is the backslash (\)

注意:如果要在字符串中使用引号或撇号,请在整个字符串中用双引号引起来。 另外,您可以使用Python的转义字符,即反斜杠( \ )

a="it's"
b='it\'s'

There are rules around mixing data types, for example you can't put numbers inside a string. Typecasting, or changing the type, resolves this.

混合数据类型有一些规则,例如,不能将数字放在字符串中。 Typecasting或更改类型可以解决此问题。

  • str() changes data to a string.

    str()将数据更改为字符串。

  • int() changes data to an integer.

    int()将数据更改为整数。

  • float() changes data to a float.

    float()将数据更改为float。

print('Your son ' + name + ' is failing ' + str(failed_subjects) + ' subjects.')

6.变量和数据类型-练习 (6. Variables & Datatypes - Exercise)

It's time for your very first Scrimba Python challenge! In this cast, you can put your new-found knowledge of variables and datatypes to the test. Try to solve the challenge by yourself, and then check out Olof's solution to see whether you're on the right track.

是时候开始您的第一个Scrimba Python挑战了! 在此转换中,您可以将对变量和数据类型的新发现知识进行测试。 尝试自己解决挑战,然后查看Olof的解决方案 ,看看您是否走在正确的轨道上。

7.算术运算 (7. Arithmetic Operations)

Here, we learn that the basic arithmetic operations in Python are addition, subtraction, multiplication, float division (which returns a floating point number), floor division (which rounds the result down to the nearest integer), modulus (which returns the remainder of the calculation) and exponent (which multiplies a number the to power of another number).

在这里,我们了解到Python中的基本算术运算是加法,减法,乘法,浮点除法(返回浮点数),底数除法(将结果四舍五入到最接近的整数),模数(返回余数)。计算)和指数(将一个数字乘以另一个数字的幂)。

a=10
b=3
print('Addition : ', a + b)
print('Subtraction : ', a - b)
print('Multiplication : ', a * b)
print('Division (float) : ', a / b)
print('Division (floor) : ', a // b)
print('Modulus : ', a % b)
print('Exponent : ', a ** b)

8.字符串-基础知识/切片 (8. Strings - Basics / Slicing)

In this cast, we learn about some of the basic concepts when it comes to using strings.

在此演员表中,我们学习了有关使用字符串的一些基本概念。

  • Multiplying strings allows us to print a string multiple times. There are three ways of doing this (the final one inserts a space between strings):

    乘以字符串可以使我们多次打印字符串。 有三种方法(最后一种在字符串之间插入空格):
print(msg+msg)
print(msg*2)
print(msg,msg)

We can change the case of the strings in a number of ways:

我们可以通过多种方式更改字符串的大小写:

  • upper() changes the string to upper case.

    upper()将字符串更改为大写。

  • lower() changes the string to lower case.

    lower()将字符串更改为小写。

  • capitalize() capitalizes a string's first word.

    capitalize()将字符串的第一个单词大写。

  • title() capitalizes every word in a string.

    title()将字符串中的每个单词大写。

print(msg.upper())
print(msg.lower())
print(msg.capitalize())
print(msg.title())

We can use the following functions to find out information about a string:

我们可以使用以下函数来查找有关字符串的信息:

  • print(len(msg)) tells us how many characters the string has (in this case, msg).

    print(len(msg))告诉我们字符串有多少个字符(在本例中为msg )。

  • print(msg.count('Python')) counts the number of instances of a word or letter - note that this is case sensitive.

    print(msg.count('Python'))计算单词或字母的实例数量-请注意,这区分大小写。

We access strings with square brackets ([]).

我们使用方括号( [] )访问字符串。

print(msg[0])

Note: Python strings are 0-indexed, i.e. the first character is counted as 0 and not 1. Using negative indexes starts the count from the end of the string.

注意: Python字符串的索引为0,即第一个字符被计为0而不是1。使用负索引从字符串的末尾开始计数。

Returning parts of a string is known as slicing. Olof shows us how to slice with some examples:

字符串的返回部分称为切片 。 Olof向我们展示了如何使用一些示例进行切片:

  • print(msg[a:]) returns everything after the character in the position specified.

    print(msg[a:])返回指定位置字符后的所有内容。

  • print(msg[a:b]) returns everything between the positions specified, not including the end position.

    print(msg[a:b])返回指定位置之间的所有内容,不包括结束位置。

  • print(msg[:b]) returns everything until the position specified, again, not including the end position.

    print(msg[:b])返回所有内容,直到指定位置为止(不包括结束位置)。

9.练习-字符串-基础知识/切片 (9. Exercise - Strings - Basics / Slicing)

It's time for an exercise on strings. As well as allowing us to practice the skills we've learned in previous casts, this challenge also gets us thinking about a skill Olof hasn't explicitly told us:

现在该练习弦乐了。 除了使我们能够练习在以前的演习中学到的技能之外,这一挑战还使我们考虑了Olof尚未明确告诉我们的技能:

Click the image to access the challenge.

单击图像以访问挑战。

This is a great intro to life as a bona fide programmer - don't forget that Google is your friend! Check out the rest of the cast to see how Olof did it.

作为真正的程序员,这是对生活的一个伟大的介绍-不要忘记Google是您的朋友! 查看其余演员表 ,看看Olof是如何做到的。

10.字符串-2查找/替换,字符串格式 (10. Strings -2 Find/replace, String Formatting)

This cast teaches us even more about working with strings.

这个演员表教会了我们更多关于弦的知识。

  • We can create multi-line strings with triple quotes:

    我们可以用三引号创建多行字符串:
msg="""Dear Terry,,
You must cut down the mightiest
tree in the forest with…
a herring! <3"""

Olof runs us through some examples of working with strings:

Olof通过一些使用字符串的示例为我们提供了帮助:

print(msg.find('Python')) returns the position of the words or characters we search for (in this case, 'Python').

print(msg.find('Python'))返回我们搜索的单词或字符的位置(在本例中为'Python')。

print(msg.replace('Python','Java')) allows us to replace words or characters in a string. Note that strings are immutable in Python, so to use the result of this function, you need to save it to a variable.

print(msg.replace('Python','Java'))允许我们替换字符串中的单词或字符。 请注意,字符串在Python中是不可变的,因此要使用此函数的结果,需要将其保存到变量中。

msg1=msg.replace('Python','C')

print('Python' in msg) tells us whether a word or character exists in a string by returning true or false.

print('Python' in msg)通过返回truefalse告诉我们字符串中是否存在单词或字符。

msg1 = f'[{name}] loves the color {color}!' allows us to format strings so that they are more readable.

msg1 = f'[{name}] loves the color {color}!' 允许我们格式化字符串,使它们更具可读性。

11.用户输入 (11. User Input)

In Python, we capture user input and print it like this:

在Python中,我们捕获用户输入并像下面这样打印:

name= input('What is your name?: ')
print(name)

This brings up a user input field which looks like this:

这将显示一个用户输入字段,如下所示:

12.用户输入-练习 (12. User Input - Exercise)

It's time to flex our programming muscles with a user input exercise! In this cast, you'll be building a distance converter using the hints below:

现在是时候通过用户输入练习来增强我们的编程能力了! 在此演员表中,您将使用以下提示构建距离转换器:

Click the image to access the challenge.

单击图像以访问挑战。

As usual, give the challenge a go on your own and then check Olof's solution to see whether you got it right.

和往常一样,让挑战自己完成,然后检查Olof的解决方案 ,看看是否正确。

13.列表-基础 (13. Lists - Basics)

Whereas a variable holds one piece of data, a list holds multiples pieces.

变量保存一个数据,而列表保存多个数据。

friends = ['John','Michael','Terry','Eric','Graham']

Lists are also zero-indexed, and can be accessed with square brackets, just like strings:

列表也是零索引的,并且可以用方括号访问,就像字符串一样:

print(friends[1])

We can also use the same commands we used with strings to find out a string's length, find certain data within a string, etc.

我们还可以使用与字符串相同的命令来查找字符串的长度,查找字符串中的某些数据等。

print(friends[1],friends[4])
print(len(friends))
print(friends.coun('Eric'))

14.列表-续 (14. Lists - continued)

This cast takes us through a few essential skills for using lists, such as sorting (sort()), finding the sum, (print(sum()), appending new data (append('')), adding two lists together (.extend()), removing items (.remove('')), popping items (which removes an item but still allows you to return it) (.pop()), and clearing the list (.clear()).

该转换使我们掌握了一些使用列表的基本技能,例如排序( sort() ),求和,( print(sum() ),追加新数据( append('') ),将两个列表加在一起( .extend()删除项目( .remove('')弹出项(删除的项目,但仍然可以让你回到它)( .pop()并清除列表( .clear()

15.清单-练习 (15. Lists - Exercise)

In this exercise, we will be having a go at manipulating lists.

在本练习中,我们将尝试操作列表。

Click the image to check out the solution.

单击图像签出解决方案。

Give it a go by yourself and then check out Olof's solution to check how it went.

自己尝试一下,然后查看Olof的解决方案以查看进展如何。

16.拆分和合并 (16. Split and Join)

This cast looks at splitting and joining parts of strings.

此演员表着眼于字符串的分割和连接。

print(msg.split())
print('-'.join(friends_list))

17.拆分和合并-练习 (17. Split and Join - Exercise)

Here you'll use what you now know about splitting and joining to create a list of friends from a string.

在这里,您将使用您现在了解的有关拆分和合并的知识,从字符串创建好友列表。

As usual, have a go on your own and then check out Olof's solution to check your work.

和往常一样,独自一人,然后查看Olof的解决方案来检查您的工作。

18.元组 (18. Tuples)

Tuples are lists that you can't change. They look the same as lists but are surrounded by parentheses instead of square brackets.

元组是您无法更改的列表。 它们看起来与列表相同,但是用括号而不是方括号括起来。

friends_tuple = ('John','Michael','Terry','Eric','Graham')

You should use tuples instead of lists when you want to make sure that your data won't change in the course of your program running.

当您要确保程序运行过程中数据不会更改时,应使用元组而不是列表。

19.套 (19. Sets)

Sets are similar to lists and tuples but they're unordered and remove duplicates inside themselves. They are also very fast. Sets are surrounded by curly brackets.

集合类似于列表和元组,但是它们是无序的,并且会删除其内部的重复项。 他们也非常快。 集被大括号包围。

friends_set = {'John','Michael','Terry','Eric','Graham','Eric'}

In this cast, Olof takes us through some tips and tricks for using lists. Note: Creating an empty set works differently than creating an empty list or tuple:

在此演员表中,Olof带我们了解了一些使用列表的技巧和窍门。 注意:创建一个空集与创建一个空列表或元组的工作方式不同:

#empty Lists
empty_list = []
empyt_list = list()

#empty Tuple
empty_tuple = ()
empty_tuple = tuple()

#empty Set
empty_set = {} # this is wrong, this is a dictionary
empty_set = set()

20.套装-练习 (20. Sets - Exercise)

Here, we'll put our new-found knowledge of sets to the test. Take a look at the end of the cast to check your answer.

在这里,我们将对集合的新知识进行测试。 看一下演员表结尾,检查您的答案。

21.评论 (21. Comments)

Comments are text in the code that Python ignores. They are mainly used for human-human communication, e.g. notes about the code, debugging or testing, and code documentation. Comments are preceded by the pound sign (#):

注释是Python忽略的代码中的文本。 它们主要用于人与人之间的交流,例如关于代码的注释,调试或测试以及代码文档。 注释前面带有井号( # ):

#Hiding in the comments

22.函数-调用,参数,参数,默认值 (22. Functions - Calling, Parameters, Arguments, Defaults)

In this cast, Olof introduces us to functions - bundles of code which we can reuse later.

在此演员表中,Olof向我们介绍了功能-代码束,我们以后可以重用。

Functions are created (defined) with def and called with the function name plus parentheses ():

使用def创建(定义)函数,并使用函数名称加括号()调用:

def greeting():
    print("Hello Friend!")

greeting()

We also take another look at formatted strings, and how using them makes code more readable and more efficient.

我们还将再来看格式化的字符串,以及如何使用它们使代码更易读和更高效。

def greeting(name,age=28):
    print("Hello " + name + ", you are " + str(age) + "!")
    print(f"Hello {name}, you are {age}!")

23.功能-锻炼 (23. Functions - Exercise)

Here, Olof gives us the task of modifying and extending the functionality of an existing function. Give it a shot and then watch the rest of the cast to see if you're on the right track.

在这里,Olof为我们提供了修改和扩展现有功能的功能的任务。 试一试,然后观看其余的演员表 ,看看自己是否走对了。

24.函数-命名法 (24. Functions - Named Notation)

Named notation is the practice of naming arguments when calling a function so that the function definition understands which argument is which, even if they appear in a different order.

命名表示法是在调用函数时命名参数的一种做法,以便函数定义可以理解哪个参数是哪个参数,即使它们以不同的顺序出现。

Profile(yob=1995,weight=83.5,height=192,eye_color="blue")

25.返回声明 (25. Return statements)

This cast takes us through return statements. A return statement allows us to get back our data after performing a function.

此强制转换带我们通过return语句。 return语句使我们可以在执行函数后取回数据。

def value_added_tax(amount):
    tax = amount * 0.25
    return tax

Olof also takes us through a few handy ways of playing with our returned data, including creating strings, sets and tuples with it.

Olof还带我们通过了一些便捷的方式来处理返回的数据,包括使用它创建字符串,集合和元组。

26.比较和布尔 (26. Comparisons and Booleans)

This tutorial whizzes through some ways of comparing data, including equals (==), is not equal (!=), greater than (>), greater than or equal to (>=), less than (<), less than or equal to (<=), in (in), not in (not in), is (is) and is not (is not).

本教程介绍了一些比较数据的方式,包括等于( == ),不等于( != ),大于( > ),大于或等于( >= ),小于( < ),小于或等于( <= ),in( in )中,not in( not in )中,is( is )and not( is not )。

We also take a look at some Boolean properties and learn that false evaluates to 0 and true evaluates to 1. Empty objects and zeroes evaluate to false and everything else (strings, numbers except 0, and so on) evaluates to true.

我们还研究了一些布尔属性,并了解到false值为0, true值为1。空对象和零的值为false,其他所有内容(字符串,0以外的数字等)的值为true。

27.条件句:If,Else,Elif (27. Conditionals: If, Else, Elif)

Conditionals allow us to run different code for different circumstances. if statements run if the function returns true, elif (else if) statements run if the functions returns true after another statement has returned false, and else statements run if none of the preceding statements have returned true, i.e. in all other eventualities.

条件允许我们针对不同的情况运行不同的代码。 if函数返回true,则运行if语句;如果在另一个语句返回false之后,函数返回true,则运行elif (else if)语句;如果前面的语句均未返回true,即在所有其他情况下, else运行else语句。

is_raining = False
is_cold = False
print("Good Morning")
if is_raining and is_cold:
    print("Bring Umbrella and jacket")
elif is_raining and not(is_cold):
    print("Bring Umbrella")
elif not(is_raining) and is_cold:
    print("Bring Jacket")
else:
    print("Shirt is fine!")

28. If / Elif / Else-练习 (28. If/Elif/Else - Exercise)

It's time to flex our conditional muscles with an exercise. We also get the chance to have a go at some extended functionality with a temperature converter.

是时候通过锻炼来锻炼我们的条件肌肉了。 我们还有机会对温度转换器进行一些扩展功能。

As usual, go ahead and see if you can solve it yourself and check your answer against Olof's solution.

像往常一样,继续进行下去,看看您是否可以自己解决问题,并对照Olof的解决方案检查您的答案。

29.有条件的-锻炼身体 (29. Conditionals - Exercise Improve)

The cast gives us the chance to try out some optimization by shortening code and reducing the number of conditionals it contains.

强制转换为我们提供了机会,可以通过缩短代码并减少其包含的条件数来进行一些优化。

There are many different ways of achieving this, so have a go on your own and then compare your answer to how Olof tackles it at the end of the cast.

有许多不同的方法可以实现这一目标,因此,请自己尝试一下,然后将您的答案与演员阵容(Olof)如何在剧组结束时解决它的方法进行比较。

30. While循环 (30. While Loops)

While loops are code which runs repeatedly until a condition tells it to stop. To create a loop, begin by asking yourself these questions:

While循环是重复运行的代码,直到条件告诉它停止为止。 要创建循环,请先问自己以下问题:

What do I want to repeat?

我想重复什么?

What do I want to change each time?

我每次都要更改什么?

How long should we repeat?

我们应该重复多久?

In the below example, we want to repeat adding one, we want to change i, and we want this to repeat until the number five is reached:

在下面的示例中,我们要重复加一,我们要更改i ,并希望重复此操作直到达到数字5:

i=0
while i < 5:
    i+=1
    print(f"{i}."+ "*"*i + "Loops are awesome" + "*"*i)

31. While循环-练习 (31. While Loops - Exercise)

It's time for an exercise on loops. In this challenge, we'll make a fun guessing game. Don't forget to consider the three loop questions in the previous chapter before you start, and then check the solution at the end of the cast to see how it went.

是时候进行循环练习了。 在这个挑战中,我们将做一个有趣的猜谜游戏。 在开始之前,请不要忘记考虑上一章中的三个循环问题,然后在转换的最后检查解决方案以了解其运行情况。

32.对于循环和嵌套 (32. For Loops and Nesting)

For loops allow us to execute a statement for each item in a string, list, tuple or set. For example, the following code prints every number between two and eight:

For循环使我们可以为字符串,列表,元组或集合中的每个项目执行一条语句。 例如,以下代码显示两个到八个之间的每个数字:

for number in range(2,8):
    print(number)

It is also possible to nest loops inside other loops. The code below prints each of the numbers 1, 2 and 3 for every friend (John 1, John 2, John 3, Terry 1, Terry 2, Terry 3, etc.)

也可以将循环嵌套在其他循环中。 下面的代码为每个朋友(约翰1,约翰2,约翰3,特里1,特里2,特里3等)打印数字1、2和3。

friends = ['John','Terry','Eric']
for friend in friends:
    for number in [1,2,3]:
        print(friend, number)

In this cast, we also learn about a couple for handy for loop keywords, such as break and continue.

在此演员表中,我们还将了解一些方便使用的循环关键字,例如breakcontinue

33. For循环-练习 (33. For loops - Exercise)

It's time to test out what we have learned about for loops with an exercise. This time, we'll be making personalized party invitations. We also have a mini-challenge of including proper capitalization

现在该通过练习来检验我们对循环学习的知识了。 这次,我们将进行个性化的聚会邀请。 我们还有一个小挑战,就是要包含适当的大写字母

Click the image to access the challenge.

单击图像以访问挑战。

As usual, see how it goes on your own and then check the solution to compare your answer.

和往常一样,看看它如何进行,然后检查解决方案以比较您的答案。

34.字典 (34. Dictionaries)

This cast introduces us to dictionaries. Dictionaries are used in Python to store key-value pairs, and they work in a similar way to a physical dictionary. You look up a word (the key) and get a definition or translation (the value) in return.

本演员介绍了字典。 字典在Python中用于存储键值对,它们的工作方式与物理字典类似。 您查找一个单词(键)并获得定义或翻译(值)作为回报。

movie = {
    'title' : 'Life of Brian',
    'year' : 1979,
    'cast' : ['John','Eric','Michael','George','Terry']
}

Olof also runs us through how to change entries in a dictionary and add new ones, as well as how to handle the error message caused by users looking up entries which don't exist and how to run for loops over dictionary data.

Olof还向我们介绍了如何更改字典中的条目并添加新条目,以及如何处理由于用户查找不存在的条目而导致的错误消息,以及如何运行对字典数据的循环。

for key, value in movie.items():
    print(key, value)

35. Sort()和Sorted() (35. Sort() and Sorted())

Here, we learn about the difference between sort() and sorted(). While both functions sort the contents of a list, only sorted() returns the results.

在这里,我们了解sort()sorted()之间的区别。 当两个函数对列表的内容进行sorted() ,只有sorted()返回结果。

We also look at the behavior of dictionaries, tuples and strings when they are sorted and see a brief introduction to lambda functions - one-line convenient throwaway functions, which we will see more on in a later tutorial. The lambda example below sorts the list according to the first entries:

我们还将查看字典,元组和字符串在排序时的行为,并简要介绍lambda函数 -单行便捷的一次性函数,我们将在以后的教程中详细介绍。 下面的lambda示例根据第一个条目对列表进行排序:

my_list=[['car',4,65],['dog',2,30],['add',3,10],['bee',1,24]]
print(sorted(my_list, key = lambda item :item[0]))

36.例外:尝试/例外,加注 (36. Exceptions: Try/Except, Raise)

In this cast, Olof takes us through some techniques for handling errors. We do this with try-except blocks, which look like this:

在此演员表中,Olof带我们了解了一些处理错误的技术。 我们使用try-except块执行此操作,如下所示:

#try:
    #code you want to run
#except:
    #executed if error occurs
#else:
    #executed if no error
#finally:
    #always executed

37.类和对象 (37. Classes and Objects)

Next up, Olof shows us classes and objects. There are four main concepts to understand when it comes to classes. These are classes, objects, attributes and methods.

接下来,Olof向我们展示了类和对象。 关于类,有四个主要概念需要理解。 这些是类,对象,属性和方法。

Classes are blueprints which show us the structure of the data required. Objects contain the actual data we use. Attributes are variables within a class and methods are functions within a class.

类是向我们显示所需数据结构的蓝图。 对象包含我们使用的实际数据。 属性是类中的变量,方法是类中的函数。

We initialize a class with the initialization statement init:

我们使用初始化语句init初始化一个类:

class Movie:
    def __init__(self,title,year,imdb_score,have_seen):
        self.title = title
        self.year = year
        self.imdb_score = imdb_score
        self.have_seen = have_seen

Note: By convention, we use the self keyword when naming attributes.

注意:按照惯例,在命名属性时,我们使用self关键字。

Having done this, we can now create instances of the class, as below:

完成此操作后,我们现在可以创建该类的实例,如下所示:

film_1 = Movie("Life of Brian",1979,8.1,True)
film_2 = Movie("The Holy Grail",1975,8.2,True)

Methods are defined in classes as follows:

方法在类中定义如下:

def nice_print(self):
        print("Title: ", self.title)
        print("Year of production: ", self.year)

There are two ways of calling methods (the output is the same):

调用方法有两种方式(输出是相同的):

film_2.nice_print()
Movie.nice_print(film_2)

38.继承 (38. Inheritance)

In this cast, Olof shows us around the concept of inheritance. Inheritance allows us to use the methods from one class in another class without repeating all the code. We can then add further methods to differentiate the classes from each other.

在此演员表中,Olof向我们展示了继承的概念。 继承使我们可以使用另一类中一个类的方法,而无需重复所有代码。 然后,我们可以添加其他方法来区分类。

class Person:
    def move(self):
        print("Moves 4 paces")
    def rest(self):
        print("Gains 4 health points")
class Doctor(Person):
    def heal(self):
        print("Heals 10 health points")

A class can inherit from multiple other classes. If the classes have different outputs for the same method, the class will choose the inherited method which is declared first.

一个类可以从多个其他类继承。 如果类的相同方法的输出不同,则该类将选择首先声明的继承方法。

In the example below, the Wizard class will inherit any shared methods from the Doctor and not the Fighter.

在下面的示例中,Wizard类将继承Doctor而不是Fighter的所有共享方法。

class Wizard(Doctor,Fighter):
    def cast_spell(self):
        print("Turns invisble")
    def heal(self):
        print("Heals 15 health points")

39.模块 (39. Modules)

Now it's time to look at modules. Modules are code snippets which you can import and use in the code. Some commonly-used ones provided by Python are datetime, random, string, os, math, browser and platform

现在该看一下模块了。 模块是代码片段,您可以将其导入并在代码中使用。 Python提供的一些常用的是datetimerandomstringosmathbrowserplatform

To use modules, we first need to import Brython's standard lib version:

要使用模块,我们首先需要导入Brython的标准lib版本:

<head>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.7.0/brython.min.js"></script>
	<script
		type="text/javascript"
		src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.7.0/brython_stdlib.js"
	></script>
	-->
</head>

Modules are imported with the import keyword and can be given an easier-to-use alias with as:

使用import关键字导入模块,并可以使用as为其提供易于使用的别名:

import platform as pl

print(pl.python_version())

40.压缩/解压缩 (40. Zip / Unzip)

In this cast, Olof shows us how to zip and unzip objects. Zipping allows us to combine two or more iterable objects (strings, tuples, lists, etc.).

在此演员表中,Olof向我们展示了如何压缩和解压缩对象。 压缩允许我们组合两个或多个可迭代对象(字符串,元组,列表等)。

nums = [1,2,3,4]
letters = ['a','b','c','d']
combo = list(zip(nums,letters))
print(combo)

The example above turns the combined iterables into a list, but we could also turn it into a tuple, set or dictionary. Note: A dictionary is unsuitable when zipping more than two objects.

上面的示例将组合的可迭代对象转换为列表,但是我们也可以将其转换为元组,集合或字典。 注意:压缩两个以上的对象时,字典不合适。

Unzipping allows us to assign results into separate variables, in this case num, let and nam.

解压缩使我们可以将结果分配到单独的变量中,在本例中为numletnam

num,let,nam =zip(*combo)

41 Lambda函数第1部分 (41 Lambda Functions part 1)

Here, we take a closer look at lambdas, or anonymous functions, which allow you to write single-line, throwaway function definitions which you might just use once. Compare the following:

在这里,我们仔细看一下lambda或匿名函数,它们使您可以编写单行的,一次性的函数定义,您可能只使用一次。 比较以下内容:

Standard function:

标准功能:

def square(x):
    return x*x
print(square(3))

Lambda:

Lambda:

square1 = lambda x: x*x

Note: The return value in a lambda is implicit.

注意: lambda中的返回值是隐式的。

42. Lambda函数第2部分 (42. Lambda Functions Part 2)

In this cast, we delve a little deeper into lambdas. Although we could always replicate a lambda with a standard function, there are some instances when lambdas are significantly better.

在此演员表中,我们更深入地研究了lambda。 尽管我们总是可以使用标准函数来复制lambda,但在某些情况下,lambda明显更好。

In this example, the return value of the lambda is a function, which gives us the ability to reuse the lambda for multiple different tasks. In the code below, we use a single lambda to multiply by two and five:

在此示例中,lambda的返回值是一个函数,它使我们能够将lambda重用于多个不同的任务。 在下面的代码中,我们使用一个lambda乘以2和5:

def func(n):
    return lambda a: a*n
# a*2
doubler = func(2)
print(doubler(3))
quintipler = func(5)
print(quintipler(3))
print(type(func(3)))

This cast also explains that we can call lambdas as soon as we create them.

此演员表还说明,我们可以在创建lambda之后立即调用它们。

print((lambda a,b,c: a+b+c)(2,3,4))

43 Lambda函数-练习 (43 Lambda Functions - Exercise)

Now it's time to practice creating a few of our own lambdas.

现在是时候练习创建一些自己的lambda了。

See how you get on and check your answers against Olof's solutions as you go along.

了解您的前进方式,并在进行过程中对照Olof的解决方案检查答案。

44.理解-列表 (44. Comprehensions - Lists)

Python comprehensions allow us to create lists, tuples, sets and dictionaries with less code. Note: Anything which can be created in a comprehension can also be created with a for loop, however the for loop requires more code.

Python理解使我们可以用更少的代码来创建列表,元组,集合和字典。 注意:可以在理解中创建的任何内容也可以使用for循环创建,但是for循环需要更多代码。

Olof also provides a handy slide to give as a visual comparison of for loops and comprehensions in two different cases.

Olof还提供了一个方便的幻灯片,以可视方式比较两种不同情况下的for循环和理解力。

Click the slide to access the cast.

单击幻灯片以访问演员表。

45.理解-字典 (45. Comprehensions - Dictionary)

Olof now shows us how to create a new dictionary using a comprehension. Were we to do this with a for loop, the code would look like this:

现在,Olof向我们展示了如何使用理解力来创建新词典。 如果我们使用for循环来执行此操作,则代码如下所示:

new_dict = dict()
for movie, yr in zip(movies,year):
    new_dict[movie] = yr
print(new_dict)

With a comparison, it looks like this:

经过比较,它看起来像这样:

new_dict = {movie:yr for movie,yr in zip(movies,year)}
print(new_dict)

Much more concise and readable!

更简洁易读!

46.随机性 (46. Randomness)

This cast takes us through the random module and teaches us how to generate pseudo-random events. To use the module, we first import it:

该转换将我们带入random模块,并教我们如何生成伪随机事件。 要使用该模块,我们首先将其导入:

import random

We can then use the module to generate pseudo-random numbers:

然后,我们可以使用模块生成伪随机数:

for i in range(5):
    print(random.random()*6)

Olof also shows us a variety of functions we can use with random.

Olof还向我们展示了可以random使用的各种功能。

Use of random is not limited to numbers though. We can also use it with iterables:

但是, random数的使用不限于数字。 我们也可以将其与可迭代对象一起使用:

friends_list =  ['John', 'Eric', 'Michael', 'Terry', 'Graham']
print(random.choice(friends_list))

Lastly, Olof shows us the string modules and we learn how to create pseudo-random words.

最后,Olof向我们展示了string模块,并学习了如何创建伪随机单词。

import random, string

smallcaps = 'abcdefghijklmnopqrstuvwxyz'
largecaps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
letters_numbers = string.ascii_letters + string.digits
word = ''
for i in range(7):
    word += random.choice(letters_numbers)
word1 = ''.join(random.sample(letters_numbers,7))
word = random.choices(letter_numbers, k=7)
print(word)
print(word1)

Note: These words are not truly random and should therefore not be used to generate passwords.

注意:这些单词不是真正随机的,因此不应用于生成密码。

47.项目-加密机 (47. Project - Crypto machine)

Now we are nearing the end of the course, Olof gives us a big project to sink our teeth into. Take a look at the instructions, follow along and attempt to do each step on your own, before checking Olof's solution.

现在我们即将结束课程,Olof为我们提供了一个庞大的项目,让我们全力以赴。 在检查Olof的解决方案之前,请看一看说明,按照步骤尝试自己做每个步骤。

48.专案-数学导师 (48. Project - Math Tutor)

Our second project is to create a Math tutor which tutors us in multiplication tables. Take a look at the instructions below, have a go at the project and then check out how Olof does it.

我们的第二个项目是创建一个数学导师,以乘法表指导我们。 查看下面的说明,进入项目,然后查看Olof的工作方式

Click the image to access the challenge.

单击图像以访问挑战。

49.课程摘要 (49. Course Summary)

Congratulations on making it to the end of the Python 101 course! We have been over outputting data and program flow, strings, variables, arithmetic operations, comparisons, lists, tuples, sets, dictionaries conditionals, loops, functions, objects, classes, inheritance, comprehensions, lambdas and modules - so you should be proud of yourself!

恭喜您完成了Python 101课程的学习! 我们已经过度输出数据和程序流,字符串,变量,算术运算,比较,列表,元组,集合,字典条件,循环,函数,对象,类,继承,理解,lambda和模块-所以您应该为此感到自豪你自己!

Don't forget you can always refer back to the course if you need to, or redo any exercises you felt unsure of them (or just particularly enjoyed!)

不要忘记,如果需要,您可以随时返回本课程 ,或者重做一些您不确定的练习(或者只是特别喜欢!)。

When you're ready to move on, Scrimba has a range of courses to teach you your next coding skill, so check them out!

当您准备好继续学习时, Scrimba会提供一系列课程来教您您的下一个编码技能,因此请务必阅读!

Click the image to see Scrimba's range of courses

点击图片查看Scrimba的课程范围

Happy coding! :)

编码愉快! :)

翻译自: https://www.freecodecamp.org/news/want-to-learn-python-heres-our-free-4-hour-interactive-course/

学习python课程

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值