Variables and Types
Introduction to Python - Beginner's Course | Codefinity
存储数字
问AI :
编程中的变量就像数据的占位符。在上一节中,你计算了一些数字。但是,如果我们以后想再次使用这些数字呢?重新做一遍数学没有多大意义。
为了记住一个值以备后用,我们使用变量为其命名。等号=允许我们为该变量设置一个值。例如,你可以将变量year设置为值2024,然后从那里,你可以显示它或用它做更多的数学运算。
# Create a variable
year = 2024
# Output its value
print(year)
# Perform an addition
print(year + 10)
Output:
2024
2034
Task
我们已进入课程的第七章。设置一个名为chapter的变量,并将其值设置为7。
移动前:
移动后:
Naming Rules
问AI
正如我们在上一章中讨论的那样,变量对于保存我们稍后将使用的值至关重要。在Python中命名变量时,有一些规则和最佳实践需要牢记:
- 变量名可以包含字母、数字或下划线:
myVariable1
;number_2
;data_frame3
;Python4Life
;_underscoreVar
.
- 变量名不能以数字开头:
- variable1 (Correct); 正确
- 1variable (Incorrect - starts with a number). 不正确 -艺术字开头
- 变量名区分大小写:
-
MyVariable and myvariable are different variables; 是不同的变量
-
Data and data are different variables;
-
Number1 and number1 are different variable
-
- 除了下划线_,不允许使用特殊字符:
-
my_variable (Correct);
-
my-variable (Incorrect - contains a hyphen); 不正确-包含连字符
-
variable@name (Incorrect - contains an @); 不正确-包含@
-
data*star (Incorrect - contains an asterisk *). 不正确-包含星号
-
- Python中的保留字不能用作变量名:
- forLoop (Correct - not a reserved word);(正确-不是保留字);
- ifCondition (Correct - not a reserved word);(正确-非保留字);
- for (Incorrect - for is a reserved word);(不正确-for是保留字);
- while (Incorrect - while is a reserved word); (不正确-while是保留字);
- try (Incorrect - try is a reserved word). (不正确-try是一个保留字)。
Using Variables 使用变量
在本节的第一课中,您设置了一个名为chapter的变量。现在,我们如何调整或更改我们已经设置的变量?好消息是,你可以像在上一课中调整价值观一样调整它们。
假设你在价格变量中保存了一件商品的成本,你想申请15%的折扣。您可以简单地重新分配更新后的值,如下所示:
price = 50 # Initial price
price = price * (1 - 0.15) # Applying the discount 应用折扣
print(price)
Output:
42.5
Task
自从你第一次设置章节变量以来,你已经完成了另外两章的学习。将2添加到章节变量中,并将此新值重新分配给它。
Hint 提示
通过将章节+2的结果【chapter = 7】分配给章节变量来更新它。
# Initial variable
chapter = 7
# Reassign the new value
chapter = chapter + 2
print(chapter)
Data Types
在Python中,就像在许多其他编程语言中一样,你可以使用各种类型的对象。了解它们之间的差异至关重要,尤其是在考虑它们如何存储在计算机内存中时。以下是Python中可用的数据类型:
- Text 文本:
str
; - Numeric 数字:
int
,float
,complex
; - Sequence 序列:
list
,tuple
,range
; - Mapping 映射:
dict
; - Set 套装:
set
,frozenset 冷冻套装
; - Boolean 布尔值 :
bool
; - Binary 二进制 :
bytes
,bytearray
,memoryview
.
Note 注:
此刻没有必要记住所有这些。
我们现在不会深入研究这些数据类型中的每一种,因为我们不会立即使用所有数据类型。相反,我们将在接下来的章节中详细介绍每一个。如果你对特定变量的类型很好奇,可以使用type()函数。记住,始终使用print()函数让Python显示结果。
例如:
# Create some variable
var = 12
# Check variable type
print(type(var))
问:What type is the var
variable from the example above?
上面例子中的var变量是什么类型的?
Numbers
Let's dive into numbers first. Python has the following numerical types:
让我们先来看看数字。Python有以下数字类型:
int
- for integer numbers 表示整数 (e.g.,3
,-1
,1003
);float
- for decimal numbers 表示 十进制数 (e.g.,2.8
,3.333
,-3.0
);complex
- for complex numbers 复数 (e.g.,3+2j
).
We'll focus on the first two types since the complex
type is typically reserved for scientific applications. Let's say we want to determine how many days are in 792 hours and how many seconds are in an hour. We'll crunch these numbers and identify their types.
我们将重点介绍前两种类型,因为复杂类型通常用于科学应用。假设我们想确定792小时有多少天,一小时有多少秒。我们将分析这些数字并确定它们的类型。
# Calculating respective numbers
days = 792/24
sec_in_hour = 60*60
# Displaying numbers and their types
print("Numbers:", days, sec_in_hour)
print("Types:", type(days), type(sec_in_hour))
Output
Numbers: 33.0 3600
Types: <class 'float'> <class 'int'>
这是一个古怪的结果!尽管这两个数字都是整数(int类型),但它们的除法结果是浮点类型(产生33.0)。但是为什么呢?33.0本质上不是一个整数吗?在数学中,确实如此。但Python谨慎地认识到,将两个整数除并不总是得到整数结果(与乘法、减法或加法不同)。
其他:
1. 十进制数(浮点数
float
)浮点数表示带有小数部分的数值,比如
3.14
、0.5
等。浮点数使用float()
函数转换,通常用于需要更高精度或小数点后数据的情况。浮点数是用二进制形式在内存中存储的,可能会出现微小的精度误差。2. 复数(
complex
)复数是具有实部和虚部的数,在 Python 中写作
a + bj
,其中a
是实部,b
是虚部(j
是虚数单位)。复数通常用于工程、科学计算中涉及复杂数学操作的场景。你可以用complex()
函数创建复数。num_complex = complex(3, 4) # 生成复数 3 + 4j
print(num_complex) # 输出为 (3+4j)
print(type(num_complex)) # <class 'complex'>注意事项
- 将浮点数转换为整数会去掉小数部分,不进行四舍五入。
- 将整数或浮点数转换为复数时,会将数值设为复数的实部,虚部为
0
。num = 5.6
print(int(num)) # 输出 5(去掉小数部分)
print(complex(num)) # 输出 (5.6+0j)
注:
如果需要在数值类型之间切换,请使用int()转换为整数,float()转换成十进制,complex()转换出复数。当你将小数转换为整数时,Python会删除小数部分而不进行四舍五入。
# Numbers
int_num = 11
real_num = 16.83
# Displaying original and converted numbers (integer - to float, and vice versa)
print(int_num, float(int_num))
print(real_num, int(real_num))
Output:
11 11.0
16.83 16
Note
当将浮点数转换为整数时,该过程通过删除小数部分来截断数字,而不是在数学上对其进行四舍五入。
Challenge
hey , 让我们来处理一项任务!
Task
旧金山和纽约之间的道路距离约为4677.4公里。该距离存储在变量distance_in_kms中。以下是您需要做的事情:
- 将公里(distance_in_kilometers)除以1.609,将其转换为英里。将结果存储在变量distance_in_miles中。
- 显示distance_in_miles的值。
- 将distance_in_miles转换为整数数据类型并显示其值。
# Distance in kilometers
distance_in_kilometers = 4677.4
# Convert to miles
distance_in_miles = ___ / ___
# Output the `distance_in_miles` value
print("San Francisco - New York distance:", ___, "mi")
# Output the `distance_in_miles` value, converted into integer data type
print("Converted distance:", ___(distance_in_miles), "mi")
Storing Text
问AI:
在第一章中,您学习了如何用Python显示消息“Hello world!”。此消息称为字符串。在Python中,字符串用于存储文本,其中也可以包含数字。
要在Python中存储文本,您需要用引号(单引号或双引号)将其括起来。例如,你可以将单词“Python”存储在语言变量中,然后显示它:
# Save string within variable
language = 'Python'
# Output string
print(language)
注:
引号是必填的。如果你忽略它们,你会得到一个错误。
如果你想将对象更改为字符串类型,请使用str()函数。
Task
将课程名称“Python导论”分配给变量course并输出。
填空以完成任务。
String Indexing 字符串索引
问AI
假设我们有一个字符串。让我们深入研究如何使用它。首先,让我们了解如何访问字符串中的特定字符。
要访问字符串中的特定字符,请使用带索引号的方括号。记住,索引号不是字符的实际位置,因为Python中的索引从0开始。为了清楚起见,请考虑下面的示例。
在Python中,索引总是比实际位置少一个。例如,我们可以从上述示例中的单词中检索几个字母。
# Initial string
site = "codefinity"
# Get the letters 'o' and 'y'
print(site[1], site[9])
Output
o y
假设您接受了字符串测试(如下所示)。识别与索引6对应的字符。
test = "Indexing"
Negative Indexing and Length
负索引和长度
您还可以从字符串的末尾开始索引。在这种情况下,最后一个元素的索引为-1,倒数第二个元素为-2,以此类推。
# Initial string
site = "codefinity"
# Get the letters 'o' and 'y'
print(site[1], site[9])
print(site[1], site[-1])
新例 :
# Initial string
site = "codefinity"
# Get the letters 'y' and 'f'
print(site[-1], site[-6])
Output
y f
注:
请记住,-1是访问最后一个元素的首选方式。
既然你已经熟悉了字符串中的引用字符,你可能会想知道如何确定该字符串中的字符总数。幸运的是,Python为此提供了len()函数。只需将字符串或包含字符串的变量作为参数传递即可。
# Initial string
site = "codefinity"
# Get the string length
print(len(site))
Output
10
正如您可能注意到的,字符串的长度对应于其中的字符数。因此,字符串中的字符总数总是比其最后一个字符的索引大一个。例如,如果字符串的长度为10,则其最后一个字符的索引为9。
Note
You can also determine the index of the last character by using len(string) - 1
.
您还可以使用len(string)-1 确定最后一个字符的索引。
对于下面提供的字符串“test”,请在索引“-4”处标识字符。
test = "Indexing"
String Slicing 字符串切片
字符串切片 解读
字符串切片在 Python 中是非常常用的操作,尤其是在处理文本数据时。它可以让我们轻松获取字符串的子字符串,指定从哪个索引开始、结束,以及步长。切片在 Python 中的使用很灵活,常见于数据清洗、文本处理等场景。
基本切片语法
切片语法为:
string[start:end:step]
start
:切片的起始索引(包括该索引)。如果不写,默认为0
。end
:切片的结束索引(不包括该索引)。如果不写,则一直到字符串末尾。step
:步长,默认为1
。如果设为负数,则表示从右向左取值。示例
假设我们有一个字符串:
text = "Hello, Python!"
- 基本切片
print(text[0:5]) # 输出 'Hello'
从索引0开始,到索引5前结束,不包括5
- 省略
start
或end
print(text[:5]) # 输出 'Hello'(从头开始到索引 5 前) print(text[7:]) # 输出 'Python!'(从索引 7 开始到字符串末尾)
- 使用步长
print(text[::2]) # 输出 'Hlo yhn'(每隔一个字符取一个)
- 反向切片
print(text[::-1]) # 输出 '!nohtyP ,olleH'(倒序输出整个字符串)
字符串切片的用途
- 从文本中提取部分内容:如提取前缀、后缀、文件扩展名等。
- 数据清洗:从复杂字符串中获取特定格式的子字符串。
- 倒序操作:反转字符串很简单,如
text[::-1]
。
太好了,现在你已经掌握了如何从字符串中提取单个字符。但是,如果你想提取几个连续的字符呢?当然,你可以逐一挑选,但这似乎有点乏味,不是吗?
确实如此。要一次性检索多个字符,可以使用一种称为切片的技术。为此,请使用方括号,并用冒号表示开始和结束索引:介于两者之间。值得注意的是,最终指数没有包括在内。因此,当你使用[1:5]时,你是在索引1到4处选择字符。看看下面的例子。
正如您所注意到的,结束位置总是比您要包含的最后一个字符的索引多一个。在上述示例中,有10个位置,但最终索引为9。
Note
别忘了空格算作字符,并有自己的索引。为清楚起见,请参阅以下示例。
# Initial strings
site = "codefinity"
greeting = "How are you"
# Slice strings
print(site[0:4], site[6:10])
print(greeting[2:5], greeting[6:11])
代码详细说明:
site[0:4]
:从索引0
开始到索引4
之前结束,所以它包含'c'
、'o'
、'd'
、'e'
,结果是'code'
,而不会包括'f'
。site[6:10]
:从索引6
到索引10
之前,结果是'nity'
。greeting[2:5]
:从索引2
到索引5
之前,结果是'w a'
。greeting[6:11]
:从索引6
到索引11
之前,结果是'e you'
。
Output
code nity
w a e you
Task
给定语言变量中保存的字符串“Python”,您的任务是提取子字符串“tho”和“on”。为了提供帮助,下面概述了此字符串的索引。
填空以完成任务:
输出
tho
on
注:
请记住,切片不包括最终索引。因此,当你使用语言[2:5]时,它包括索引2、3和4处的元素,但不包括索引5处的元素。
Challenge
Task
您会收到存储在变量test_str中的字符串“This is string for learning”。您的任务是:
- 检索并显示test_str的第一个字符(使用first print()函数)。
- 检索并显示test_str的最后一个字符(使用第二个print()函数)。
- 从test_str变量中检索并显示单词字符串。
Hint 提示
- 字符串的第一个字符位于索引0处。
- 字符串的最后一个字符位于索引-1处。
- 单词“string”从索引8开始,到索引13结束。使用冒号(:)对字符串进行切片并抓取所需的部分。请记住,要在切片中包含索引13,必须将14指定为切片端点。
# Create new variable
test_str = "This is string for learning"
# Extract the very first and very last characters of this string
print("The first symbol of string:", ___[___])
print("The last symbol of string:", ___[___])
# Extract the word string using slicing
print("Extracted word:", test_str[___:___])
修改后:
# Create new variable
test_str = "This is string for learning"
# Extract the very first and very last characters of this string
print("The first symbol of string:", test_str[0])
print("The last symbol of string:", test_str[-1])
# Extract the word string using slicing
print("Extracted word:", test_str[8:14])
Concatenation
让我们深入探讨串联。这个过程只是将两个字符串连接在一起。在Python中,您可以使用+运算符连接两个字符串,就像添加数字一样。
注:
连接不会自动在要连接的字符串之间插入空格。
例如,您可以将单词与文章组合在一起:
# Article and word
article = "The"
country = "Netherlands"
# Output result of the concatenations
print(article + country)
print(article + " " + country) # Add blank space between
Output
TheNetherlands
The Netherlands
Note
请记住,您只能将字符串与其他字符串连接起来。换句话说,你不能直接将像“单词”这样的单词与像1这样的数字连接起来。为了实现这一点,首先使用str(1)函数将数字转换为字符串,然后连接起来。
What result will the following code produce?
greeting = "Hello"
language = "Python"
print(language + " " + greeting + "!")
不回答了,你应该猜对了。。。
----------------------------------------------------------------
Quiz for "Introduction to Python" “Python入门”测验
1、 在Python中为变量赋值的正确语法是variable_name=value。
x = 10
10 = x
x := 10
var x = 10
在Python中为变量赋值的正确语法是variable_name=value。
2、 如何将文本“Hello”存储在名为greeting的变量中?
greeting = "Hello" 正确
greeting = Hello
greeting = 'Hello' 正确
greeting = print("Hello")
str greeting = "Hello"
要将文本存储在变量中,请将文本括在引号中并使用=运算符。
3、以下哪个变量名在Python中有效?
THIRDPLACE 正确
2nd_place
first-place
_4thplace 正确
4、x的值是多少?
x = 10
x = 20
x will be 10.
x will be 20. 正确
x will be 30.
The code will generate an error.
5、这段代码将做什么?
print("c<>definity" - "finity")
It will print
"c<>definity"
.It will print
"c<>de"
.It will print
"c<>definityfinity"
.It will generate an error.
在Python中,不能对字符串使用减法运算符。尝试这样做将导致错误。
6、What this code will do?
print("c<>definity" * 2)
It will print
"c<>definity"
.It will print
"c<>definityc<>definity"
. 正确It will print
"c<>definity2"
.It will generate an error.
7、What is the result of type(5)?
<class 'int'> 正确
<class 'str'>
<class 'float'>
The type can give type only for variables. 该类型只能为变量提供类型。
8、以下代码将输出什么?
print("Hello, world!"[-1][-1][-1])
"H"
"!"
"Hello, world!"
It will generate an error. 正确
解释:
代码试图使用[-1]访问字符串“Hello,world!”的最后一个字符,该字符可以正确检索感叹号“!”。然而,第二个[-1]试图访问字符串“!”的最后一个字符(它本身)。最后一个也是如此。
9、len()函数的作用是什么?
Converts a number to a string. 将数字转换为字符串。
Converts a string to a number. 将字符串转换为数字。
Returns the length of a string or list. 返回字符串或列表的长度。==
Returns the last element of a string or list. 返回字符串或列表的最后一个元素。
10、在控制台中输出“c<>definity”的正确方法是什么?
print("c<>definity")
print("c<>de" + "finity")
print("c<>de", "finity")
print("c<>de" & "finity")
解释:
在Python中,+运算符用于连接字符串,其他变体也是在控制台中输出“c<>definity”的一种方式。运算符&不能应用于字符串。
11、如何将字符串“123”转换为整数?
int("123") ===
convert("123")
"123".to_int()
str("123")
12、这个表达有什么问题?
print(3.5 + 2.1)
The float numbers in python go with comma not dot.
You have to convert them to float explicitly before use.
The result will be displayed in scientific notation.
Nothing is wrong with an expressions.
python中的浮点数使用逗号而不是点。
在使用之前,您必须将它们显式转换为浮点数。
结果将以科学符号显示。
表达没有错。 ==
13、这个代码片段将做什么?
b = a + 3
a = 2
print(b)
This code will print 5.
This code will print the value of b in the console.
This code will generate an error.
This code will do nothing.
此代码将打印5。
此代码将在控制台中打印b的值。
此代码将生成错误。
这段代码不会做任何事情。
解释:
代码将生成错误,因为在分配值之前使用了。在Python中,必须先定义变量,然后才能使用它们。
14、What will this code do?
print("Python" + 3)
It will print
"Python3"
.It will print
"Python"
.It will concatenate and print
"Python + 3"
.It will generate an error.
15、What will happen when the following code is executed?
x = int("b245")
x
will be assigned the integer value245
.
x
will be assigned the integer value0
.
x
will be assigned the string value"b245"
.A
ValueError
will be raised. 将引发ValueError。将引发ValueError
解释:
该代码试图将字符串“b245”转换为整数。由于字符串包含非数字字符(“b”),这将引发ValueError,表示该字符串不是整数转换的有效文字。