python基础_第五章_条件和循环语句

本文详细介绍了Python的基础编程概念,包括条件语句(if, elif, else)、循环(while, for)、赋值魔法(序列解包、链式赋值、增强赋值)、代码块缩进、循环中的break和continue,以及pass和del的用法。通过实例解析了如何在Python中进行条件判断和循环控制,帮助初学者更好地理解和运用这些基本语句。" 116783538,8395545,在CentoS系统中安装flair与Python tkinter的问题及解决,"['Python开发', '系统配置', '软件安装', '环境问题']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

条件、循环及其他语句

1 再谈 print 和 import

打印多个参数
你可同时打印多个表达式,条件是用逗号分隔它们:

>>> print('Age:', 42)
Age: 42
>>> name = 'Gumby'
>>> salutation = 'Mr.'
>>> greeting = 'Hello,'
>>> print(greeting, salutation, name)
Hello, Mr. Gumby

如果需要,可自定义分隔符sep=“分隔符”:

>>> print("I", "wish", "to", "register", "a", "complaint", sep="_")
I_wish_to_register_a_complaint

导入时重命名
为导入的函数重新命名,防止函数名重复

>>> import math as foobar
>>> foobar.sqrt(4)
2.0

2 赋值魔法

序列解包
可同时(并行)给多个变量赋值:

>>> x, y, z = 1, 2, 3
>>> print(x, y, z)
1 2 3
>>> x, y = y, x
>>> print(x, y, z)
2 1 3

这里执行的操作称为序列解包(或可迭代对象解包):将一个序列(或任何可迭代对象)解包,并将得到的值存储到一系列变量中。

>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1

要解包的序列包含的元素个数必须与你在等号左边列出的目标个数相同,否则Python将引发异常。

可使用星号运算符( * )来收集多余的值,这样无需确保值和变量的个数相同
( * )收集的值永远是个列表

>>> a, b, *rest = [1, 2, 3, 4]
>>> rest
[3, 4]
>>> name = "Albus Percival Wulfric Brian Dumbledore"
>>> first, *middle, last = name.split()
>>> middle
['Percival', 'Wulfric', 'Brian']

链式赋值

链式赋值是一种快捷方式,用于将多个变量关联到同一个值。

x = y = somefunction()

等于下面的代码

y = somefunction()
x = y

增强赋值
x += 1 :这称为增强赋值,适用于所有标准运算符,如 * 、 / 、 % 等。

>>> x = 2
>>> x += 1
>>>x
3
>>> x *= 2
>>> x
6

3 代码块缩进

代码块是一组语句,可在满足条件时执行( if 语句),可执行多次(循环),等等。代码块是通过缩进代码(即在前面加空格)来创建的。
在同一个代码块中,各行代码的缩进量必须相同。

4 条件和条件语句

用作布尔表达式(如用作 if 语句中的条件)时,下面的值都将被解释器视为假(False,None和各类空值):
False None 0 “” () [] {}

if 语句

name = input('What is your name? ')
if name.endswith('Gumby'):
	print('Hello, Mr. Gumby')

if 语句让你能够有条件地执行代码。这意味着如果条件( if 和冒号之间的表达式)为前面定义的真,就执行后续代码块(这里是一条 print 语句);如果条件为假,就不执行。

else 子句
如果没有执行第一个代码块(因为条件为假),将进入第二个代码块。

name = input('What is your name?')
if name.endswith('Gumby'):
	print('Hello, Mr. Gumby')
else:
	print('Hello, stranger')

if语句的条件表达式

status = "friend" if name.endswith("Gumby") else "stranger"

elif 子句
要检查多个条件,可使用 elif 。

num = int(input('Enter a number: '))
if num > 0:
	print('The number is positive')
elif num < 0:
	print('The number is negative')
else:
	print('The number is zero')

代码块嵌套
可将 if 语句放在其他 if 语句块中

name = input('What is your name? ')
if name.endswith('Gumby'):
	if name.startswith('Mr.'):
		print('Hello, Mr. Gumby')
	elif name.startswith('Mrs.'):
		print('Hello, Mrs. Gumby')
	else:
		print('Hello, Gumby')
else:
	print('Hello, stranger')

复杂的条件

比较运算符
注意:一个“=”是赋值,“==”才是等于
比较运算符

5 循环

while 循环
当while后面的条件成立时才会退出

x = 1
while x <= 100:
	print(x)
	x += 1 # 增强赋值

for 循环

words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
	print(word)

鉴于迭代(也就是遍历)特定范围内的数是一种常见的任务,Python提供了一个创建范围的内置函数

>>> range(0, 10)
range(0, 10)
>>> list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

迭代字典

d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
	print(key, 'corresponds to', d[key]
for key, value in d.items():
	print(key, 'corresponds to', value)

迭代工具

  1. 并行迭代
    同时迭代两个序列
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
for name, age in zip(names, ages):
	print(name, 'is', age, 'years old')
  1. 迭代时获取索引
    这个函数让你能够迭代索引值对,其中的索引是自动提供的。
for index, string in enumerate(strings):
	if 'xxx' in string:
		strings[index] = '[censored]'

跳出循环

  1. break
    运行break后会跳出最近的一个循环
from math import sqrt
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print(n)
break
  1. continue
    跳过循环体中余下的语句,但不结束循环。

  2. while True/break

while True:
	word = input('Please enter a word: ')
	if not word: 
		break #跳出while循环
	#使用这个单词做些事情:
	print('The word was ', word)

循环中的 else 子句

from math import sqrt
for n in range(99, 81, -1):
	root = sqrt(n)
	if root == int(root):
		print(n)
		break
else:
	print("Didn't find it!")

6 简单推导

有点类似于 for 循环。

>>> [x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x*x for x in range(10) if x %3 == 0] 
[0, 9, 36, 81]

7 pass 、 del

pass就是什么都不做,用于占位,等到需要的时候再来写这部分代码。

>>> pass
>>>

用于彻底删除对象名称

>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#255>", line 1, in ?
x
NameError: name 'x' is not defined
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值