《Python数据分析技术栈》第01章 03 Python基础(Python Basics)

03 Python基础(Python Basics)

《Python数据分析技术栈》第01章 03 Python基础(Python Basics)

In this section, we get familiar with the syntax of Python, commenting, conditional statements, loops, and functions.

在本节中,我们将熟悉 Python 的语法、注释、条件语句、循环和函数。

注释、输入和输出(Comments, print, and input)

In this section, we get familiar with the syntax of Python, commenting, conditional statements, loops, and functions

在本节中,我们将熟悉 Python 的语法、注释、条件语句、循环和函数

注释(Comments)

A comment explains what a line of code does, and is used by programmers to help others understand the code they have written. In Python, a comment starts with the # symbol.

注释解释了一行代码的作用,程序员用它来帮助其他人理解他们编写的代码。在 Python 中,注释以 # 符号开始。

Proper spacing and indentation are critical in Python. While other languages like Java and C++ use brackets to enclose blocks of code, Python uses an indent of four spaces to specify code blocks. One needs to take care of indents to avoid errors. Applications like Jupyter generally take care of indentation and automatically add four spaces at the beginning of a block of code.

适当的间距和缩进在 Python 中至关重要。Java 和 C++ 等其他语言使用括号来括弧代码块,而 Python 则使用四个空格的缩进来指定代码块。我们需要注意缩进以避免错误。像 Jupyter 这样的应用程序通常会注意缩进,并自动在代码块的开头添加四个空格。

输出(Printing)

The print function prints content to the screen or any other output device.

打印功能可将内容打印到屏幕或任何其他输出设备上。

Generally, we pass a combination of strings and variables as arguments to the print function. Arguments are the values included within the parenthesis of a function, which the function uses for producing the result. In the following statement, “Hello!” is the argument to the print function.

一般来说,我们将字符串和变量的组合作为参数传递给打印函数。参数是包含在函数括号内的值,函数使用这些值产生结果。在下面的语句中,"Hello!"是 print 函数的参数。

print("Hello!")

To print multiple lines of code, we use triple quotes at the beginning and end of the string, for example:

例如,要打印多行代码,我们可以在字符串的开头和结尾使用三引号:

print('''Today is a lovely day.
It will be warm and sunny.
It is ideal for hiking.''')

Output:

Today is a lovely day.
It will be warm and sunny.
It is ideal for hiking.

Note that we do not use semicolons in Python to end statements, unlike some other languages.

请注意,与其他一些语言不同,我们在 Pyth 中不使用分号来结束语句。

The format method can be used in conjunction with the print method for embedding variables within a string. It uses curly braces as placeholders for variables that are passed as arguments to the method.

format 方法可与 print 方法结合使用,用于在字符串中嵌入变量。它使用大括号作为变量的占位符,这些变量将作为参数传递给该方法。

Let us look at a simple example where we print variables using the format method.

让我们看一个使用 format 方法打印变量的简单示例。

weight=4.5
name="Simi"
print("The weight of {} is {}".format(name,weight))

Output:

The weight of Simi is 4.5

The preceding statement can also be rewritten as follows without the format method:

前面的语句也可以改写如下,不使用格式方法:

weight=4.5
name="Simi"
print("The weight of",name,"is",weight)

Note that only the string portion of the print argument is enclosed within quotes. The name of the variable does not come within quotes. Similarly, if you have any constants in your print arguments, they also do not come within quotes. In the following example, a Boolean constant (True), an integer constant (1), and strings are combined in a print statement.

请注意,只有打印参数的字符串部分是用引号括起来的。变量名不在引号内。同样,如果在打印参数中包含常量,也不能用引号括起来。在下面的示例中,一个布尔常数 (True)、一个整数常数 (1) 和字符串组合在一条打印语句中。

print("The integer equivalent of",True,"is",1)

Output:

The integer equivalent of True is 1

The format fields can specify precision for floating-point numbers. Floating-point numbers are numbers with decimal points, and the number of digits after the decimal point can be specified using format fields as follows.

格式字段可以指定浮点数的精度。浮点数是带有小数点的数,小数点后的位数可以用格式字段指定,具体如下。

x=91.234566
print("The value of x upto 3 decimal points is {:.3f}".format(x))

Output:

The value of x upto 3 decimal points is 91.235

We can specify the position of the variables passed to the method. In this example, we use position “1” to refer to the second object in the argument list, and position “0” to specify the first object in the argument list.

我们可以指定传递给方法的变量的位置。在本例中,我们使用位置 "1 "来指代参数列表中的第二个对象,而使用位置 "0 "来指代参数列表中的第一个对象。

y='Jack'
x='Jill'
print("{1} and {0} went up the hill to fetch a pail of water".format(x,y))

Output:

Jack and Jill went up the hill to fetch a pail of water

输入(Input)

The input function accepts inputs from the user. The input provided by the user is stored as a variable of type String. If you want to do any mathematical calculations with any numeric input, you need to change the data type of the input to int or float, as follows.

输入函数接受用户的输入。用户提供的输入将存储为字符串类型的变量。如果要对数字输入进行数学计算,则需要将输入的数据类型改为 int 或 float,如下所示。

age=input("Enter your age:")
print("In 2010, you were",int(age)-10,"years old")

Output:

Enter your age:76
In 2010, you were 66 years old

Further reading on Input/Output in Python: https://docs.python.org/3/tutorial/inputoutput.html

有关 Python 输入/输出的更多阅读:https://docs.python.org/3/tutorial/inputoutput.html

变量和常量(Variables and Constants)

A constant or a literal is a value that does not change, while a variable contains a value can be changed. We do not have to declare a variable in Python, that is, specify its data type, unlike other languages like Java and C/C++. We define it by giving the variable a name and assigning it a value. Based on the value, a data type is automatically assigned to it. Values are stored in variables using the assignment operator (=).

常量或字面量是一个不会改变的值,而变量包含一个可以改变的值。在 Python 中,我们不需要声明变量,即指定它的数据类型,这与 Java 和 C/C++ 等其他语言不同。我们通过给变量命名并赋值来定义它。根据变量值,会自动为其分配数据类型。使用赋值运算符 (=) 可以将值存储到变量中。

The rules for naming a variable in Python are as follows:

  • a variable name cannot have spaces
  • a variable cannot start with a number
  • variable name can contain only letters, numbers, and underscore signs (_)
  • a variable cannot take the name of a reserved keyword (for example, words like class, continue, break, print, etc., which are predefined terms in the Python language, have special meanings, and are invalid as variable names)

Python 中变量的命名规则如下:

  • 变量名不能有空格
  • 变量名不能以数字开头
  • 变量名只能包含字母、数字和下划线符号 (_)
  • 变量名不能使用保留关键字的名称(例如,class、continue、break、print 等词,它们是 Python 语言中的预定义词,具有特殊含义,不能作为变量名使用)

运算符(Operators)

The following are some commonly used operators in Python.

下面是 Python 中的一些常用操作符。

Arithmetic operators: Take two integer or float values, perform an operation, and return a value.

算术运算符: 取两个整数或浮点数值,执行运算并返回一个数值。

The following arithmetic operators are supported in Python:
• **(Exponent)
• %(modulo or remainder),
• //(quotient),
• *(multiplication)
• -(subtraction)
• +(addition)

Python 支持以下算术运算符:

  • **(指数)
  • %(模或余数)、
  • //(商)
  • *(乘法)
    -(减法)
  • +(加法)

The order of operations is essential. Parenthesis takes precedence over exponents, which takes precedence over division and multiplication, which takes precedence over addition and subtraction. An acronym was designed - P.E.D.M.A.S.(Please Excuse My Dear Aunt Sally) - that can be used to remember the order of these operations to understand which operator first needs to be applied in an arithmetic expression. An example is given in the following:

运算顺序至关重要。括号优先于指数,指数优先于除法和乘法,除法优先于加法和减法。我们设计了一个首字母缩写词–P.E.D.M.A.S.(请原谅我亲爱的莎莉阿姨),可以用来记住这些运算的顺序,从而了解在算术表达式中首先需要应用哪个运算符。下面是一个例子:

(1+9)/2-3

Output:

2.0

In the preceding expression, the operation inside the parenthesis is performed first, which gives 10, followed by division, which gives 5, and then subtraction, which gives the final output as 2.

在前面的表达式中,先进行括号内的运算,得到 10,然后进行除法运算,得到 5,最后进行减法运算,得到 2。

Comparison operators: These operators compare two values and evaluate to a true or false value. The following comparison operators are supported in Python:
• >: Greater than
• < : Less than
• <=: Less than or equal to
• >=: Greater than or equal to
• == : equality. Please note that this is different from the assignment operator (=)
• !=(not equal to)

比较运算符: 这些运算符对两个值进行比较,得出真值或假值。Python 支持以下比较运算符:

  • >: 大于
  • <: 小于
  • <=: 小于或等于
  • >=: 大于或等于
  • == : 相等。请注意,这不同于赋值运算符 (=)
  • !=: 不等于

Logical (or Boolean) operators: Are similar to comparison operators in that they also evaluate to a true or false value. These operators operate on Boolean variables or expressions. The following logical operators are supported in Python:

逻辑(或布尔)运算符: 与比较运算符类似,它们的运算结果也是 "真 "或 “假”。这些运算符对布尔变量或表达式进行操作。Python 支持以下逻辑运算符:

and operator: An expression in which this operator is used evaluates to True only if all its subexpressions are True. Otherwise, if any of them is False, the expression evaluates to False An example of the usage of the and operator is shown in the following.

and 运算符: 使用该运算符的表达式只有在所有子表达式都为 True 的情况下才会求值为 True。否则,如果其中任何一个子表达式为 “假”,则表达式的值为 “假”。

(2>1) and (1>3)

or operator: An expression in which the or operator is used, evaluates to True if any one of the subexpressions within the expression is True. The expression evaluates to False if all its subexpressions evaluate to False.

or 运算符: 在使用 or 运算符的表达式中,如果表达式中任何一个子表达式的值为 True,则该表达式的值为 True。如果所有子表达式的值都为 “假”,则表达式的值为 “假”。

An example of the usage of the or operator is shown in the following.

下面举例说明或运算符的用法。

(2>1) or (1>3)

not operator: An expression in which the not operator is used, evaluates to True if the expression is False, and vice versa.

not 运算符: 使用 not 运算符的表达式,如果表达式为 False,则其值为 True,反之亦然。

An example of the usage of the not operator is shown in the following.

下面是一个使用 not 操作符的示例。

not(1>2)

赋值运算符(Assignment operators)

These operators assign a value to a variable or an operand. The following is the list of assignment operators used in Python:
• = (assigns a value to a variable)
• += (adds the value on the right to the operand on the left)
• -= (subtracts the value on the right from the operand on the left)
• *= (multiplies the operand on the left by the value on the right)
• %= (returns the remainder after dividing the operand on the left by the value on the right)
• /= (returns the quotient, after dividing the operand on the left by the value on the right)
• //= (returns only the integer part of the quotient after dividing the operand on the left by the value on the right)

这些操作符为变量或操作数赋值。下面是 Python 中使用的赋值操作符列表:

  • = (给变量赋值)
  • +=(将右边的值加到左边的操作数上)
  • -=(从左边的操作数中减去右边的值)
  • *= (将左边的操作数乘以右边的值)
  • %=(返回左边的操作数除以右边的值后的余数)
  • /=(返回左边的操作数除以右边的值后的商数)
  • //=(左边的操作数除以右边的值后,只返回商的整数部分)

Some examples of the usage of these assignment operators are given in the following.

下面举例说明这些赋值操作符的用法。

x=5 #assigns the value 5 to the variable x
x+=1 #statement adds 1 to x (is equivalent to x=x+1)
x-=1 #statement subtracts 1 from x (is equivalent to x=x-1)
x*=2 #multiplies x by 2(is equivalent to x=x*2)
x%=3 #equivalent to x=x%3, returns remainder
x/=3 #equivalent to x=x/3, returns both integer and decimal part of quotient
x//=3 #equivalent to x=x//3, returns only the integer part of quotient after dividing x by 3

判断运算符(Identity operators (is and not is))

These operators check for the equality of two objects, that is, whether the two objects point to the same value and return a Boolean value (True/False) depending on whether they are equal or not. In the following example, the three variables “x”, “y”, and “z” contain the same value, and hence, the identity operator (is) returns True when “x” and “z” are compared.

这些运算符检查两个对象是否相等,即两个对象是否指向相同的值,并根据相等与否返回布尔值(真/假)。在下面的示例中,三个变量 “x”、"y "和 "z "包含相同的值,因此当比较 "x "和 "z "时,同一性运算符(is)返回 True。

Example:

x=3
y=x
z=y
x is z

成员运算符(Membership operators (in and not in))

These operators check if a particular value is present in a string or a container (like lists and tuples, discussed in the next chapter). The in operator returns “True” if the value is present, and the not in operator returns “True” if the value is not present in the string or container.

这些操作符检查特定值是否存在于字符串或容器(如下一章讨论的列表和元组)中。如果值存在,in 操作符返回 “True”;如果值不存在于字符串或容器中,not in 操作符返回 “True”。

'a' in 'and'

数据类型(Data types)

The data type is the category or the type of a variable, based on the value it stores.

数据类型是变量的类别或类型,以其存储的值为基础。

The data type of a variable or constant can be obtained using the type function.

变量或常量的数据类型可通过 type 函数获得。

type(45.33)

Some commonly used data types are given in Table 1-2.

表 1-2 列出了一些常用数据类型。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

表示日期和时间(Representing dates and times)

Python has a module called datetime that allows us to define a date, time, or duration.

Python 有一个名为 datetime 的模块,它允许我们定义日期、时间或持续时间。

We first need to import this module so that we can use the functions available in this module for defining a date or time object, using the following statement.

首先,我们需要导入该模块,以便使用该模块中的函数来定义日期或时间对象,语句如下

import datetime

Let us use the methods that are part of this module to define various date/time objects.

让我们使用该模块中的方法来定义各种日期/时间对象。

Date对象(Date object)

A date consisting of a day, month, and year can be defined using the date method, as shown in the following.

可以使用日期方法定义由日、月和年组成的日期,如下所示。

date=datetime.date(year=1995,month=1,day=1)
print(date)

Output:

1995-01-01

Note that all three arguments of the date method – day, month, and year – are mandatory. If you skip any of these arguments while defining a date object, an error occurs, as shown in the following.

请注意,日期方法的所有三个参数(日、月和年)都是必选参数。如果在定义日期对象时跳过其中任何一个参数,就会出现错误,如下所示。

date=datetime.date(month=1,day=1)
print(date)

Time对象(Time object)

To define an object in Python that stores time, we use the time method.

要在 Python 中定义一个存储时间的对象,我们使用 time 方法。

The arguments that can be passed to this method may include hours, minutes, seconds, or microseconds. Note that unlike the date method, arguments are not mandatory for the time method (they can be skipped).

该方法可传递的参数包括小时、分钟、秒或微秒。需要注意的是,与日期方法不同,时间方法的参数不是必须的(可以省略)。

time=datetime.time(hour=12,minute=0,second=0,microsecond=0)
print("midnight:",time)

Output:

midnight: 00:00:00

Datetime对象(Datetime object)

We can also define a datetime object consisting of both a date and a time, using the datetime method, as follows. For this method, the date arguments – day, month, and year – are mandatory, but the time argument (like hour, minute, etc.) can be skipped.

我们还可以使用 datetime 方法定义一个由日期和时间组成的日期时间对象,如下所示。对于该方法,日期参数(日、月、年)是必须的,但时间参数(如小时、分钟等)可以省略。

datetime1=datetime.datetime(year=1995,month=1,day=1,hour=12,minute=0,second=0,microsecond=0)
print("1st January 1995 midnight:", datetime1)

Output:

1st January 1995 midnight: 1995-01-01 12:00:00

Timedelta对象(Timedelta object)

A timedelta object represents a specific duration of time, and is created using the timedelta method.

timedelta 对象表示特定的时间长度,使用 timedelta 方法创建。

Let us create a timedelta object that stores a period of 17 days.

让我们创建一个存储 17 天的 timedelta 对象。

timedelta1=datetime.timedelta(weeks=2,days=3)
timedelta1

Output:

datetime.timedelta(days=17)

You can also add other arguments like seconds, minutes, and hours, while creating a timedelta object.

在创建 timedelta 对象时,您还可以添加其他参数,如秒、分和小时。

A timedelta object can be added to an existing date or datetime object, but not to a time object

timedelta 对象可以添加到现有的日期或日期时间对象中,但不能添加到时间对象中

Adding a duration (timedelta object) to a date object:

为日期对象添加持续时间(timedelta 对象):

#adding a duration to a date object is supported
date1=datetime.date(year=1995,month=1,day=1)
timedelta1=datetime.timedelta(weeks=2,days=3)
date1+timedelta1

Output:

datetime.date(1995, 1, 18)

Adding a duration (timedelta object) to a datetime object:

为日期时间对象添加持续时间(timedelta 对象):

#adding a duration to a datetime object is supported
datetime1=datetime.datetime(year=1995,month=2,day=3)
timedelta1=datetime.timedelta(weeks=2,days=3)
datetime1+timedelta1

Output:

datetime.datetime(1995, 2, 20, 0, 0)

Adding a duration to a time object leads to an error:

向时间对象添加持续时间会导致错误:

#adding a duration to a time object is not supported
time1=datetime.time(hour=12,minute=0,second=0,microsecond=0)
timedelta1=datetime.timedelta(weeks=2,days=3)
time1+timedelta1

Further reading: Learn more about the Python datetime module https://docs.python.org/3/library/datetime.html

进一步阅读: 进一步了解 Python datetime 模块 https://docs.python.org/3/library/datetime.html

使用字符串类型(Working with Strings)

A string is a sequence of one or more characters enclosed within quotes (both single and double quotes are acceptable). The data type for strings is str. Python does not support the character data type, unlike older languages like Java and C. Even single characters, like ‘a’, ‘b’, are stored as strings. Strings are internally stored as arrays and are immutable (cannot be modified). Let us see how to define a string.

字符串是用引号(单引号和双引号均可)括起来的一个或多个字符的序列。字符串的数据类型是 str。Python 不支持字符数据类型,这一点与 Java 和 C 等老式语言不同。字符串在内部存储为数组,并且是不可变的(不能修改)。让我们看看如何定义字符串。

定义字符串(Defining a string)

Single-line strings can be defined using single or double quotes.

可使用单引号或双引号定义单行字符串。

x='All that glitters is not gold'
#OR
x="All that glitters is not gold"

For multiline strings, use triple quotes:

对于多行字符串,请使用三层引号:

x='''Today is Tuesday.
Tomorrow is Wednesday'''

字符串操作(String operations)

Various functions can be used with strings, some of which are explained in the following.

字符串可以使用多种函数,下文将对其中一些函数进行说明。

Finding the length of a string: The len function can be used to calculate the length of a string, as shown in the following.

查找字符串的长度 len 函数可用于计算字符串的长度,如下所示。

len('Hello')

Accessing individual elements in a string: The individual characters in a string can be extracted using the indexing operator, [].

访问字符串中的单个元素 使用索引操作符 [] 可以提取字符串中的单个字符。

x='Python'
x[3]

Slicing a string: Slicing refers to the extraction of a portion or subset of an object (in this case, the object is a string). Slicing can also be used with other iterable objects like lists and tuples, which we discuss in the next chapter. The colon operator is used for slicing, with an optional start, stop, and step index. Some examples of slicing are provided in the following.

切分字符串 切片是指提取对象的一部分或子集(在本例中,对象是一个字符串)。分片也可用于其他可迭代对象,如列表和元组,我们将在下一章讨论。冒号操作符用于分片,可选择开始、停止和步进索引。下面提供了一些切分示例。

x='Python'
x[1:] #from second character to the end

Some more examples of slicing:

x[:2] #first two characters. The starting index is assumed to be 0
x[::-1]#reversing the string, the last character has an index -1

Justification: To add spaces to the right or left, or center the string, the rjust, ljust, or center method is used. The first argument passed to such a method is the length of the new string, and the optional second argument is the character to be used for padding. By default, spaces are used for padding.

说明理由: 要在字符串左右添加空格或居中,需要使用 rjust、ljust 或 center 方法。传递给这种方法的第一个参数是新字符串的长度,可选的第二个参数是用于填充的字符。默认情况下,填充使用空格。

'123'.rjust(5,"*")

Changing the case: To change the case of the string, the upper or lower method is used, as shown in the following.

更改大小写 要更改字符串的大小写,可使用大写或小写方法,如下所示。

'COLOR'.lower()

Checking what a string contains: In order to check whether a string starts or ends with a given character, the startswith or endswith method is used.

检查字符串包含的内容 为了检查字符串是否以给定字符开始或结束,需要使用 startswith 或 endswith 方法。

'weather'.startswith('w')

Removing whitespaces from a string: To remove spaces from a string, use the strip method (to remove spaces at both ends), rstrip (to remove spaces from the right end), or the lstrip method (to remove spaces from the left end). An example is shown in the following.

删除字符串中的空格: 要删除字符串中的空格,可使用 strip 方法(删除两端的空格)、rstrip 方法(删除右端的空格)或 lstrip 方法(删除左端的空格)。下面是一个示例。

' Hello'.lstrip()

Examining the contents of a string: There are several methods to check what a string contains, like isalpha, isupper, isdigit, isalnum, etc. All these methods return “True” only if all the characters in the string satisfy a given condition.

检查字符串的内容 有多种方法可以检查字符串的内容,如 isalpha、isupper、isdigit、isalnum 等。所有这些方法只有在字符串中的所有字符都满足给定条件时才会返回 “True”。

'981'.isdigit()#to check for digits

#Checks if all characters are in uppercase. Since all letters are not uppercase, the condition is not satisfied
'Abc'.isupper()

Joining a list of strings: The join method combines a list of strings into one string. On the left-hand side of the join method, we mention the delimiter in quotes to be used for joining the strings. On the right-hand side, we pass the list of individual strings.

连接字符串列表 join 方法将字符串列表合并为一个字符串。在 join 方法的左侧,我们用引号指定了用于连接字符串的分隔符。在右侧,我们传递单个字符串的列表。

' '.join(['Python','is','easy','to','learn'])

Splitting a string: The split method does the opposite of what the join method does. It breaks down a string into a list of individual words and returns the list. If we just pass one word to this method, it returns a list containing just one word and does not split the string further.

分割字符串 split 方法的作用与 join 方法相反。它将字符串拆分成一个个单词列表,然后返回列表。如果我们只向该方法传递一个单词,它就会返回一个只包含一个单词的列表,而不会进一步拆分字符串。

'Python is easy to learn'.split()

条件语句(Conditional statements)

Conditional statements, as the name indicates, evaluate a condition or a group of conditions.

条件语句,顾名思义,评估一个或一组条件。

In Python, the if-elif-else construct is used for this purpose. Python does not have the switchcase construct, which is used in some other languages for conditional execution.

在 Python 中,if-elif-else 结构用于此目的。Python 没有 switchcase 结构,而在其他一些语言中,switchcase 结构用于条件执行。

Conditional statements start with the if keyword, and the expression or a condition to be evaluated. This is followed by a block of code that executes only if the condition evaluates to “True”; otherwise it is skipped.

条件语句以 if 关键字和要评估的表达式或条件开始。其后是一个代码块,只有当条件求值为 "True "时才会执行,否则跳过该代码块。

The else statement (which does not contain any condition) is used to execute a block of code when the condition mentioned in the if statement is not satisfied. The elif statements are used to evaluate specific conditions. The order of elif statements matters. If one of the elif statements evaluates to True, the elif statements following it are not executed at all. The if statement can also exist on its own, without mentioning the else or elif statements.

else 语句(不包含任何条件)用于在 if 语句中提及的条件未满足时执行代码块。elif 语句用于评估特定条件。elif 语句的顺序很重要。如果其中一个 elif 语句求值为 True,则后面的 elif 语句根本不会被执行。if 语句也可以单独存在,而不提及 else 或 elif 语句。

The following example demonstrates the if-elif-else construct.

下面的示例演示了 if-elif-else 结构。

#if-elif-else
color=input('Enter one of the following colors - red, orange or blue:')
if color=='red':
	print('Your favorite color is red')
elif color=='orange':
	print('Your favorite color is orange')
elif color=='blue':
	print('Your favorite color is blue')
else:
	print("You entered the wrong color")

Conditional statements can be nested, which means that we can have one conditional statement (inner) within another (outer). You need to be particularly careful with indentation while using nested statements. An example of nested if statements is shown in the following.

条件语句可以嵌套,这意味着我们可以将一个条件语句(内层)放在另一个条件语句(外层)中。在使用嵌套语句时,需要特别注意缩进。下面是嵌套 if 语句的一个示例。

x=20
if x<10:
  if x<5:
  	print("Number less than 5")
  else:
  	print("Number greater than 5")
else:
  print("Number greater than 10")

Further reading: See more on the if statement: https://docs.python.org/3/tutorial/controlflow.html#if-statements

进一步阅读: 查看有关 if 语句的更多信息: https://docs.python.org/3/tutorial/controlflow.html#if-statements

循环语句(Loops)

Loops are used to execute a portion of the code repeatedly. A single execution of a block of code is called an iteration, and loops often go through multiple rounds of iterations. There are two types of loops that are used in Python – the for loop and the while loop.

循环用于重复执行部分代码。代码块的单次执行称为一次迭代,而循环通常要经过多轮迭代。Python 中使用的循环有两种:for 循环和 while 循环。

While循环(While loop)

The while loop is used when we want to execute particular instructions as long as a condition is “True”. After the block of code executes, the execution goes back to the beginning of the block. An example is shown in the following.

当我们想在条件为 "True "时执行特定指令时,就会使用 while 循环。代码块执行完毕后,执行会返回到代码块的起始位置。下面是一个示例。

#while loop with continue statement
while True:
  x=input('Enter the correct color:')
  if(x!='red'):
    print("Color needs to be entered as red")
    continue
  else:
  	break

In the preceding example, the first statement (while True) is used to execute an infinite loop. Once the username entered is of the right length, the break statement takes execution outside the loop; otherwise, a message is displayed to the user asking for a username of the right length. Note that execution automatically goes to the beginning of the loop, after the last statement in the block of code.

在上例中,第一条语句(while True)用于执行一个无限循环。一旦输入的用户名长度合适,break 语句就会将执行带出循环;否则,就会向用户显示一条信息,要求输入长度合适的用户名。请注意,执行会自动回到循环的起点,即代码块中的最后一条语句之后。

The break statement is used to take the control outside the loop. It is useful when we have an infinite loop that we want to break out of.

break 语句用于将控制带出循环。当我们想跳出无限循环时,该语句非常有用。

The continue statement does the opposite - it takes control to the beginning of the loop. The keywords break and continue can be used both with loops and conditional statements, like if/else.

continue 语句的作用正好相反,它将控制权转到循环的起点。关键字 break 和 continue 既可用于循环,也可用于条件语句,如 if/else。

for循环(for loop)

The for loop is used to execute a block of a code a predetermined number of times. The for loop can be used with any kind of iterable object, that is, a sequence of values that can be used by a loop for running repeated instances or iterations. These iterable objects include lists, tuples, dictionaries, and strings.

for 循环用于按预定次数执行代码块。for 循环可用于任何类型的可迭代对象,即循环可用于运行重复实例或迭代的值序列。这些可迭代对象包括列表、元组、字典和字符串。

The for loop is also used commonly in conjunction with the range function. The range function creates a range object, another iterable, which is a sequence of evenly spaced integers. Consider the following example where we calculate the sum of the first five odd integers using a for loop.

for 循环通常与 range 函数结合使用。range 函数会创建一个 range 对象(另一个可迭代对象),它是一个均匀分布的整数序列。在下面的示例中,我们使用 for 循环计算前五个奇数整数之和。

#for loop
sum=0
for i in range(1,10,2):
	sum=sum+i
print(sum)

The range function has three arguments: the start argument, the stop argument, and the step argument. None of these three arguments are mandatory. Numbers from 0 to 9 (both 0 and 9 included) can be generated as range(10), range(0,10), or range(0,10,1). The default start argument is 0, and the default step argument is 1.

range 函数有三个参数:开始参数、停止参数和步长参数。这三个参数都不是必须的。0 至 9 的数字(包括 0 和 9)可以生成 range(10)、range(0,10) 或 range(0,10,1)。默认起始参数为 0,默认步长参数为 1。

For loops can also be nested (with an outer loop and any number of inner loops), as shown in the following.

For 循环也可以嵌套(包含一个外循环和任意数量的内循环),如下所示。

#nested for loop
for i in 'abcd':
  for j in range(4):
  	print(i,end=" ")
  print("\n")

函数(Functions)

A function can be thought of as a “black box” (the user need not be concerned with the internal workings of the function) that takes an input, processes it, and produces an output. A function is essentially a block of statements performing a specific task.

函数可以被看作是一个 “黑盒子”(用户无需关心函数的内部工作原理),它接收输入、处理输入并产生输出。函数本质上是执行特定任务的语句块。

In Python, a function is defined using the def keyword. This is followed by the name of a function and one or more optional parameters. A parameter is a variable that exists only within a function. Variables defined within a function have local scope, which means that they cannot be accessed outside the function. They are also called local variables. External code or functions cannot manipulate the variables defined within a function.

在 Python 中,函数是用 def 关键字定义的。其后是函数名和一个或多个可选参数。参数是一个只存在于函数中的变量。在函数中定义的变量具有局部作用域,这意味着不能在函数之外访问它们。它们也被称为局部变量。外部代码或函数不能操作函数内定义的变量。

A function may have an optional return value. The return value is the output produced by a function that is returned to the main program. Calling a function means giving the function inputs (arguments) to perform its task and produce an output.

函数可以有一个可选的返回值。返回值是函数产生并返回主程序的输出结果。调用函数意味着向函数提供输入(参数)以执行其任务并产生输出。

The utility of functions lies in their reusability. They also help in avoiding redundancy and organizing code into logical blocks. We just need to supply it with the set of inputs it needs to run the instructions. A function can be called repeatedly instead of manually typing out the same lines of code.

函数的效用在于其可重用性。它们还有助于避免冗余,并将代码组织成逻辑块。我们只需向它提供运行指令所需的输入集合。一个函数可以被重复调用,而不是手动键入相同的代码行。

For example, say you want to find out the prime numbers in a given list of numbers. Once you have written a function for checking whether an integer is a prime number, you can simply pass each number in the list as an argument to the function and call it, instead of writing the same lines of code for each integer you want to test.

例如,您想找出给定数字列表中的质数。一旦你编写了一个用于检查某个整数是否是质数的函数,你只需将列表中的每个数字作为参数传递给函数并调用即可,而不必为每个要测试的整数编写相同的代码行。

def checkPrime(i):
  #Assume the number is prime initially
  isPrime=True
  for j in range(2,i):
    # checking if the number is divisible by any number between 2 and i
    if i%j==0:
      #If it is divisible by any number in the j range, it is not prime
      isPrime=False
  # This is the same as writing if isPrime==True
  if isPrime:
  	print(i ,"is prime")
  else:
    print(i, "is not prime")
for i in range(10,20):
  checkPrime(i)

Anonymous or lambda functions are defined using the lambda keyword. They are single-expression functions and provide a compact way of defining a function without binding the function object to a name. The reason these functions are called “anonymous” is that they do not need a name. Consider the following example where we use a lambda function to calculate the sum of two numbers.

匿名函数或 lambda 函数使用 lambda 关键字定义。它们是单表达式函数,提供了一种无需将函数对象与名称绑定的紧凑函数定义方法。这些函数之所以称为 “匿名”,是因为它们不需要名称。请看下面的示例,我们使用 lambda 函数计算两个数字的和。

(lambda x,y:(x+y))(5,4)

Note the syntax of an anonymous function. It starts with the lambda keyword, followed by the parameters (‘x’ and ‘y’, in this case). Then comes the colon, after which there is an expression that is evaluated and returned. There is no need to mention a return statement since there is an implicit return in such a function. Notice that the function also does not have a name.

请注意匿名函数的语法。它以 lambda 关键字开头,然后是参数(本例中为 "x "和 “y”)。然后是冒号,冒号后是一个被求值并返回的表达式。没有必要提及返回语句,因为在这样的函数中存在隐式返回。请注意,函数也没有名称。

(lambda x,y:(x+y))(5,4)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/331940.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

LRU Cache

文章目录 1. 什么是LRU Cache2. LRU Cache的实现3. LRU Cache的OJ题目分析AC代码 1. 什么是LRU Cache LRU是Least Recently Used的缩写&#xff0c;意思是最近最少使用&#xff0c;它是一种Cache替换算法。 什么是Cache&#xff1f; 狭义的Cache指的是位于CPU和主存间的快速RAM…

linux 更新镜像源

打开终端&#xff0c;备份一下旧的 源 文件&#xff0c;以防万一 cd /etc/apt/ ls sudo cp sources.list sources.list.bak ls然后打开清华大学开源软件镜像站 搜索一下你的linux发行版本&#xff0c;我这里是ubuntu发行版本 点击这个上面图中的问号 查看一下自己的版本号&a…

【控制篇 / 分流】(7.4) ❀ 03. 对国内和国际IP网段访问进行分流 ❀ FortiGate 防火墙

【简介】公司有两条宽带用来上网&#xff0c;一条电信&#xff0c;一条IPLS国际专线&#xff0c;由于IPLS仅有2M&#xff0c;且价格昂贵&#xff0c;领导要求&#xff0c;访问国内IP走电信&#xff0c;国际IP走IPLS&#xff0c;那么应该怎么做&#xff1f; 国内IP地址组 我们已…

KubeSphere 开源社区 2023 年度回顾与致谢

2023 年结束了&#xff0c;让我们再一次一起回顾一下 KubeSphere 开源社区在过去一年的变化。更重要的是&#xff0c;本篇文章将会对 2023 年所有参与过 KubeSphere 社区贡献的成员致以最诚挚的感谢&#xff0c;快来看看有没有你&#xff01; 开源项目发展情况 2023 年&#…

黑马 Javaweb - MySQL 精华篇

我是南城余&#xff01;阿里云开发者平台专家博士证书获得者&#xff01; 欢迎关注我的博客&#xff01;一同成长&#xff01; 一名从事运维开发的worker&#xff0c;记录分享学习。 专注于AI&#xff0c;运维开发&#xff0c;windows Linux 系统领域的分享&#xff01; 知…

查询数据库表字段具有某些特征的表

目录 引言举例总结 引言 当我们把一个项目做完以后&#xff0c;客户要求我们把系统中所有的电话&#xff0c;证件号等进行加密处理时&#xff0c;我们难道要一个表一表去查看那些字段是电话和证件号码吗&#xff1f; 这种办法有点费劲&#xff0c;下面我们来探索如何找到想要的…

mybatis分页、延迟加载、立即加载、一级缓存、二级缓存

mybatis分页、延迟加载、立即加载、一级缓存、二级缓存 分页延迟加载和立即加载缓存一级缓存二级缓存 分页 分类&#xff1a; 使用Limit&#xff0c;来进行分页&#xff1b;物理分页使用RowBounds集合来保存分页需要数据&#xff0c;来进行分页;逻辑分页&#xff1b;本质是全…

Air780E开发板开发环境搭建

开发板原理图 开发软件 下载网站 https://luatos.com/luatools/download/last 使用教程 烧录教程 - LuatOS 文档 开发流程 首先下载最新版本的Luatools 然后新建一个Luatools文件夹&#xff0c;将下载的exe文件放入其中后&#xff0c;再打开exe文件&#xff08;会生成目…

《WebKit 技术内幕》之四(2): 资源加载和网络栈

2.Chromium 多进程资源加载 2,1 多进程 资源的实际加载在各个WebKit移植中有不同的实现。Chromium采用的多进程的资源加载机制。 ResourceHandle 类之下的部分是不同移植对获取资源的不同实现&#xff0c;Chromium 中是 多进程资源加载 。主要是多个Renderer进程和Browser进程…

SystemVerilog验证测试平台

2.2定宽数组 相比于 Verilog1995中的一维定宽数组, System verilog提供了更加多样的数组类型,功能上也大大增强。 2.2.1定宽数组的声明和初始化 Verilog要求在声明中必须给出数组的上下界。因为几乎所有数组都使用0作为索引下界,所以 System verilog允许只给出数组宽度的便捷声…

华为DHCP配置

1. 全局地址池和接口地址池的应用场景有什么不同呢&#xff1f; 答&#xff1a;接口地址池适用于当前接口只给DHCP client分配与接口同一网段的IP地址的场景。 全局地址池可以给DHCP Client分配与接口同网段的IP地址&#xff0c;也可以分配不同网段的IP地址&#xff08;DHCP中…

Python爬虫 - 网易云音乐下载

爬取网易云音乐实战&#xff0c;仅供学习&#xff0c;不可商用&#xff0c;出现问题&#xff0c;概不负责&#xff01; 分为爬取网易云歌单和排行榜单两部分。 因为网页中&#xff0c;只能显示出歌单的前20首歌曲&#xff0c;所以仅支持下载前20首歌曲&#xff08;非VIP音乐&…

滑动窗口经典入门题-——长度最小子数组

文章目录 算法原理题目解析暴力枚举法的代码优化第一步初始化第二步right右移第三步left右移 滑动窗口法的代码 算法原理 滑动窗口是一种在序列&#xff08;例如数组或链表&#xff09;上解决问题的算法模式。它通常用于解决子数组或子字符串的问题&#xff0c;其中滑动窗口表示…

【Redis】Redis基础

Redis基础 初识Redis 认识NoSQL SQL&#xff1a;结构化查询语言 > 关系型数据库 NoSQL&#xff1a;非关系型数据库 SQL与NoSQL的差异&#xff1a; 数据结构 SQL结构化&#xff1a;表的信息依赖于表的结构NoSQL非结构化&#xff1a;存储的信息为KV形式 数据关联 SQL关联…

Android NDK Crash信息收集捕获和日志异常定位分析(addr2line)

Android NDK 闪退日志收集与分析 我们在开发过程中,Android JNI层Crash问题或者我们引用的第三方.so库文件报错,都是一个比较头疼的问题。相对Java层来说,由于c/c++造成的crash没有输出如同Java的Exception Strace堆栈信息,所以定位问题也是个比较艰难的事情。 Google Br…

Nomogram文献分析:提取数据

前言 今天教大家如何分析Nomogram类型的文章&#xff0c;并使用我们开发的系统零代码提取数据。 系统地址&#xff1a;https://clinicaldata.fun/ 要分析的文章&#xff1a;https://pubmed.ncbi.nlm.nih.gov/36504658/ 。这是一篇典型的mimic-iii数据分析的套路&#xff0c;…

智能小程序开发项目步骤流程

快速开始 在开发小程序之前&#xff0c;请确保电脑上已经安装node运行环境。可前往Node.js官网(opens in a new tab)下载安装。智能小程序环境搭建和面板小程序一致&#xff0c;请参考面板小程序搭建环境指南。 开发小程序的流程&#xff1a; 使用涂鸦开发者 IoT 账号登录 T…

c语言-结构体内存对齐

文章目录 前言一、结构体内存对齐总结 前言 本篇文章介绍结构体内存对齐。 一、结构体内存对齐 定义两个结构体&#xff1a; struct S1 {char c1;int i;char c2; };struct S2 {char c1;char c2;int i; }; //输出结构体大小 int main() {printf("%u\n", sizeof(st…

未来能源转型之路:2023年第十三届中国国际储能大会启示录

在2023年第十三届中国国际储能大会上&#xff0c;全球各地的能源专家、学者和企业代表齐聚一堂&#xff0c;共同探讨了储能技术在推动能源转型中的重要作用。对于我们普通人来说&#xff0c;从这场大会中可以学到什么呢&#xff1f; 一、储能技术是未来能源发展的关键 随着可再…

李沐《动手学深度学习》线性神经网络 softmax回归

系列文章 李沐《动手学深度学习》预备知识 张量操作及数据处理 李沐《动手学深度学习》预备知识 线性代数及微积分 李沐《动手学深度学习》线性神经网络 线性回归 目录 系列文章一、softmax回归&#xff08;一&#xff09;问题背景&#xff08;二&#xff09;网络架构&#xf…