13个 Python 必备的知识,建议收藏!(下)

上一篇 / 下一篇  2022-07-21 13:42:23

  8、条件语句
  条件语句是用于根据特定条件更改程序流程的代码块。这些语句只有在满足特定条件时才会执行。
  在Python中,我们使用if,if-else,循环(for,while)作为条件语句根据某些条件来改变程序的流程。
  if-else语句。
  >>> num = 5
  >>> if (num > 0):
  >>>    print("Positive integer")
  >>> else:
  >>>    print("Negative integer")
  elif语句。
  >>> name = 'admin'
  >>> if name == 'User1':
  >>>     print('Only read access')
  >>> elif name == 'admin':
  >>>     print('Having read and write access')
  >>> else:
  >>>     print('Invalid user')
  Having read and write access
  9、循环语句
  循环是一个条件语句,用于重复某些语句(在其主体中),直到满足某个条件。
  在Python中,我们通常使用for和while循环。
  for循环。
  >>> # loop through a list
  >>> companies = ["apple", "google", "tcs"]
  >>> for x in companies:
  >>>     print(x)
  apple
  google
  tcs
  >>> # loop through string
  >>> for x in "TCS":
  >>>  print(x)
  T
  C
  S
  range()函数返回一个数字序列,它可以用作for循环控制。
  它基本上需要三个参数,其中第二个和第三个是可选的。参数是开始值、停止值和步进数。步进数是每次迭代循环变量的增量值。
  >>> # loop with range() function
  >>> for x in range(5):
  >>>  print(x)
  0
  1
  2
  3
  4
  >>> for x in range(2, 5):
  >>>  print(x)
  2
  3
  4
  >>> for x in range(2, 10, 3):
  >>>  print(x)
  2
  5
  8
  我们还可以使用else关键字在循环结束时执行一些语句。
  在循环结束时提供else语句以及循环结束时需要执行的语句。
  >>> for x in range(5):
  >>>  print(x)
  >>> else:
  >>>  print("finished")
  0
  1
  2
  3
  4
  finished
  while循环。
  >>> count = 0
  >>> while (count < 5):
  >>>  print(count)
  >>>  count = count + 1
  0
  1
  2
  3
  4
  我们可以在while循环的末尾使用else,类似于for循环,当条件为假时执行一些语句。
  >>> count = 0
  >>> while (count < 5):
  >>>  print(count)
  >>>  count = count + 1
  >>> else:
  >>>  print("Count is greater than 4")
  0
  1
  2
  3
  4
  Count is greater than 4
  10、函数
  函数是用于执行任务的可重用代码块。在代码中实现模块化并使代码可重用,这是非常有用的。
  >>> # This prints a passed string into this function
  >>> def display(str):
  >>>  print(str)
  >>>  return
  >>> display("Hello World")
  Hello World
  11、异常处理
  即使语句在语法上是正确的,它也可能在执行时发生错误。这些类型的错误称为异常。我们可以使用异常处理机制来避免此类问题。  
  在Python中,我们使用try,except和finally关键字在代码中实现异常处理。
  >>> def divider(num1, num2):
  >>>     try:
  >>>         return num1 / num2
  >>>     except ZeroDivisionError as e:
  >>>         print('Error: Invalid argument: {}'.format(e))
  >>>     finally:
  >>>         print("finished")
  >>>
  >>> print(divider(2,1))
  >>> print(divider(2,0))
  finished
  2.0
  Error: Invalid argument: division by zero
  finished
  None
  12、字符串操作
  字符串是用单引号或双引号(',")括起来的字符集合。
  我们可以使用内置方法对字符串执行各种操作,如连接、切片、修剪、反转、大小写更改和格式化,如split()、lower()、upper()、endswith()、join()和ljust()、rjust()、format()。
  >>> msg = 'Hello World'
  >>> print(msg)
  Hello World
  >>> print(msg[1])
  e
  >>> print(msg[-1])
  d
  >>> print(msg[:1])
  H
  >>> print(msg[1:])
  ello World
  >>> print(msg[:-1])
  Hello Worl
  >>> print(msg[::-1])
  dlroW olleH
  >>> print(msg[1:5])
  ello
  >>> print(msg.upper())
  HELLO WORLD
  >>> print(msg.lower())
  hello world
  >>> print(msg.startswith('Hello'))
  True
  >>> print(msg.endswith('World'))
  True
  >>> print(', '.join(['Hello', 'World', '2022']))
  Hello, World, 2022
  >>> print(' '.join(['Hello', 'World', '2022']))
  Hello World 2022
  >>> print("Hello World 2022".split())
  ['Hello', 'World', '2022']
  >>> print("Hello World 2022".rjust(25, '-'))
  ---------Hello World 2022
  >>> print("Hello World 2022".ljust(25, '*'))
  Hello World 2022*********
  >>> print("Hello World 2022".center(25, '#'))
  #####Hello World 2022####
  >>> name = "Codemaker"
  >>> print("Hello %s" % name)
  Hello Codemaker
  >>> print("Hello {}".format(name))
  Hello Codemaker
  >>> print("Hello {0}{1}".format(name, "2022"))
  Hello Codemaker2022
  13、正则表达式
  导入regex模块,import re。
  re.compile()使用该函数创建一个Regex对象。
  将搜索字符串传递给search()方法。
  调用group()方法返回匹配的文本。
  >>> import re
  >>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
  >>> mob = phone_num_regex.search('My number is 996-190-7453.')
  >>> print('Phone number found: {}'.format(mob.group()))
  Phone number found: 996-190-7453
  >>> phone_num_regex = re.compile(r'^\d+$')
  >>> is_valid = phone_num_regex.search('+919961907453.') is None
  >>> print(is_valid)
  True
  >>> at_regex = re.compile(r'.at')
  >>> strs = at_regex.findall('The cat in the hat sat on the mat.')
  >>> print(strs)
  ['cat', 'hat', 'sat', 'mat']
  好了,本期的分享就到此结束了,有兴趣的小伙伴可以自行去实践学习。

TAG: 软件开发 Python

 

评分:0

我来说两句

Open Toolbar