Python基础入门:字符串、变量与控制流详解

追风的人
追风的人
发布时间:2026-10-13| 2人浏览过
原创

本文详细解析Python基础语法,涵盖字符串的三种定义方式及转义字符处理,变量类型的动态确定机制,以及基于缩进的代码块结构。重点讲解if、while、for等控制流语句及break、continue的使用,辅以完整代码示例,帮助开发者快速掌握Python核心编程要素。

字符串的定义方法

使用单引号(')

可以通过单引号来定义字符串,例如 'Quote me on this'。在单引号字符串中,所有的空白字符(包括空格和制表符)都会按照原始格式保留。

使用双引号(")

双引号字符串的使用方式与单引号完全一致,例如 "What's your name?"。

使用三引号('''或""")

利用三引号可以定义多行字符串。在三引号内部,可以自由混合使用单引号和双引号,无需转义。例如:

'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''

转义符

使用 \' 来表示字符串中的单引号,注意这里的反斜杠。此时字符串可以表示为 'What\'s your name?'。

另一种表示该字符串的方法是直接使用双引号或三引号,即 "What's your name?"。

在字符串中,行末单独存在的反斜杠表示字符串在下一行继续,而不是开启新行。例如:

"This is the first sentence.\
This is the second sentence."

b、变量

Python中变量的定义方式与其他语言类似,其类型由赋值操作动态确定,无需显式声明。

Int型   Number = 0
字符串型 String = ‘'
Dict型  dict = {}

c、缩进

同一层级的语句必须保持相同的缩进量。每一组具有相同缩进的语句被称为一个代码块。

i = 5
 print 'Value is', i
print 'I repeat, the value is', i

d、运算符

运算符

名称

说明

例子

+

加

两个对象相加

3 + 5得到8。'a' + 'b'得到'ab'。

-

减

得到负数或是一个数减去另一个数

-5.2得到一个负数。50 - 24得到26。

*

乘

两个数相乘或是返回一个被重复若干次的字符串

2 * 3得到6。'la' * 3得到'lalala'。

/

除

x除以y

4/3得到1(整数的除法得到整数结果)。4.0/3或4/3.0得到1.3333333333333333

//

取整除

返回商的整数部分

4 // 3.0得到1.0

%

取模

返回除法的余数

8%3得到2。-25.5%2.25得到1.5

<

小于

返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。

5 < 3返回0(即False)而3 < 5返回1(即True)。比较可以被任意连接:3 < 5 < 7返回True。

>

大于

返回x是否大于y

5 > 3返回True。如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。

<=

小于等于

返回x是否小于等于y

x = 3; y = 6; x <= y返回True。

>=

大于等于

返回x是否大于等于y

x = 4; y = 3; x >= y返回True。

==

等于

比较对象是否相等

x = 2; y = 2; x == y返回True。x = 'str'; y = 'stR'; x == y返回False。x = 'str'; y = 'str'; x == y返回True。

!=

不等于

比较两个对象是否不相等

x = 2; y = 3; x != y返回True。

not

布尔“非”

如果x为True,返回False。如果x为False,它返回True。

x = True; not y返回False。

and

布尔“与”

如果x为False,x and y返回False,否则它返回y的计算值。

x = False; y = True; x and y,由于x是False,返回False。在这里,Python不会计算y,因为它知道这个表达式的值肯定是False(因为x是False)。这个现象称为短路计算。

or

布尔“或”

如果x是True,它返回True,否则它返回y的计算值。

x = True; y = False; x or y返回True。短路计算在这里也适用。

最常用的运算符包括小于(等)、大于(等)、等于(不)等于、not、and 和 or。

e、控制流

if语句

number = 23
guess = int(raw_input('Enter an integer : '))
 
if guess == number:
  print 'Congratulations, you guessed it.' # New block starts here
  print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
  print 'No, it is a little higher than that' # Another block
  # You can do whatever you want in a block ...
else:
  print 'No, it is a little lower than that'
  # you must have guess > number to reach here
 
print 'Done'
# This last statement is always executed, after the if statement is executed
 
if 'a' in name:
  print 'Yes, it contains the string "a"'

elif 和 else 部分是可选的。

while语句

number = 23
running = True
while running:
  guess = int(raw_input('Enter an integer : '))
  if guess == number:
    print 'Congratulations, you guessed it.'
    running = False # this causes the while loop to stop
  elif guess < number:
    print 'No, it is a little higher than that'
  else:
    print 'No, it is a little lower than that'
else:
  print 'The while loop is over.'
  # Do anything else you want to do here
print 'Done'

for语句

for i in range(1, 5):
print i
等价于
for i in range(5):
print i

for 循环在指定范围内递归执行——例如 for i in range(1,5) 等价于 for i in [1, 2, 3, 4]。这表示将序列中的每个元素(或对象)依次赋值给变量 i,然后以当前的 i 值执行代码块。

break语句

while True:
  s = raw_input('Enter something : ')
  if s == 'quit':
    break
  print 'Length of the string is', len(s)
print 'Done'

continue语句

while True:
  s = raw_input('Enter something : ')
  if s == 'quit':
    break
  if len(s) < 3:
    continue
print 'Input is of sufficient length'

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。