欢迎访问宙启技术站
智能推送

Python函数中常用的控制流语句和操作符

发布时间:2023-06-04 12:18:41

1. if/else语句:if/else用于根据条件是否成立执行不同的代码。if语句用于检查一个条件是否成立,如果成立就执行特定的语句,否则执行else语句中的代码。

例子:

if x > y:
   print('x is larger than y')
else:
   print('y is larger than x')

2. for循环语句:for循环用于迭代遍历一些可迭代对象中的元素。可迭代对象通常是列表、元组、字符串、字典等。

例子:

for i in range(1, 6):
   print(i)

3. while循环语句:while循环用于在条件成立的情况下执行一些代码,直到条件不再成立为止。

例子:

n = 0
while n < 5:
   n += 1
   print(n)

4. break语句:break语句用于在循环中强制结束循环,即使循环条件仍然成立也要跳出循环。

例子:

for i in range(1, 6):
   if i == 3:
      break
   print(i)

5. continue语句:continue语句用于跳过循环体中的某次迭代,继续执行下一次迭代。

例子:

for i in range(1, 6):
   if i == 3:
      continue
   print(i)

6. return语句:return语句用于从函数中返回一个值。当函数调用完成后,返回值可以传递给函数调用者。

例子:

def add_num(x, y):
   return x + y

result = add_num(3, 5)
print(result)

7. try/except语句:try/except语句用于处理异常,即当代码出现错误时,可以通过try/except语句来捕获并处理异常,使程序不会因为错误停止执行。

例子:

try:
   x = 4 / 0
except ZeroDivisionError:
   print('division by zero')

8. and/or操作符:and和or操作符用于组合多个条件。and表示必须所有条件均为真才为真,or表示只需任意一个条件为真就为真。

例子:

if x > 0 and x < 10:
   print('x is between 0 and 10')
if x < 0 or x > 10:
   print('x is not between 0 and 10')

9. not操作符:not操作符用于取反操作,将原始的布尔值取反。如果原始值为真,则返回假,如果原始值为假,则返回真。

例子:

if not x > y:
   print('y is larger than or equal to x')

10. in/not in操作符:in和not in操作符用于判断一个值是否在一个序列中。in表示值在序列内,not in表示值不在序列内。

例子:

if 'apple' in ['orange', 'banana', 'apple']:
   print('apple is in the list')
if 'pear' not in ['orange', 'banana', 'apple']:
   print('pear is not in the list')