51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 888|回复: 1
打印 上一主题 下一主题

[转贴] Python最常用的函数、基础语句有哪些?

[复制链接]
  • TA的每日心情
    无聊
    昨天 11:10
  • 签到天数: 407 天

    连续签到: 1 天

    [LV.9]测试副司令

    跳转到指定楼层
    1#
    发表于 2022-3-25 09:47:13 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    一、内置函数
      内置函数是python自带的函数方法,拿来就可以用,比方说zip、filter、isinstance等。
      下面是Python官档给出的内置函数列表,相当的齐全。

    下面几个是常见的内置函数:
      1、enumerate   (iterable,start=0)
      enumerate()是python的内置函数,是枚举、列举的意思对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值在python中enumerate的用法多用于在for循环中得到计数。
    1. seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    2.   list(enumerate(seasons))
    3.   [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    4.   list(enumerate(seasons, start=1))
    5.   [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
    复制代码
    2、 zip (*iterables,strict=False)
      zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。zip(iterable1,iterable2, ...)
    1. >>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
    2.   ...     print(item)
    3.   ...
    4.   (1, 'sugar')
    5.   (2, 'spice')
    6.   (3, 'everything nice')
    复制代码
    3、 filter (function,iterable)
      filter是将一个序列进行过滤,返回迭代器的对象,去除不满足条件的序列。filter(function,data)function作为条件选择函数比如说定义一个函数来检查输入数字是否为偶数。如果数字为偶数,它将返回True,否则返回False。
    1. def is_even(x):
    2.       if x % 2 == 0:
    3.           return True
    4.       else:
    5.           return False
    复制代码
    然后使用filter对某个列表进行筛选:
    1. l1 = [1, 2, 3, 4, 5]
    2.   fl = filter(is_even, l1)
    3.   list(fl)
    复制代码
    4、 isinstance (object,classinfo)
      「isinstance」是用来判断某一个变量或者是对象是不是属于某种类型的一个函数
      如果参数object是classinfo的实例,或者object是classinfo类的子类的一个实例, 返回True。如果object不是一个给定类型的的对象, 则返回结果总是False。
    1.  >>>a = 2
    2.   >>> isinstance (a,int)
    3.   True
    4.   >>> isinstance (a,str)
    5.   False
    6.   >>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
    7.   True
    复制代码
     5、 eval (expression[,globals[,locals]])
      eval用来将字符串str当成有效的表达式来求值并返回计算结果表达式解析参数expression并作为 Python 表达式进行求值(从技术上说是一个条件列表),采用globals和locals字典作为全局和局部命名空间。
    1. >>>x = 7
    2.   >>> eval( '3 * x' )
    3.   21
    4.   >>> eval('pow(2,2)')
    5.   4
    6.   >>> eval('2 + 2')
    7.   4
    8.   >>> n=81
    9.   >>> eval("n + 4")
    10.   85
    复制代码
    常用句式
      在日常代码过程中,其实有很多常用的句式,出现频率非常高,也是大家约定俗成的写法。
      1、format字符串格式化
      format把字符串当成一个模板,通过传入的参数进行格式化,非常实用且强大。
    1. # 格式化字符串
    2.   print('{} {}'.format('hello','world'))
    3.   # 浮点数
    4.   float1 = 563.78453
    5.   print("{:5.2f}".format(float1))
    复制代码
    2、连接字符串
      使用+连接两个字符串。
    1. string1 = "Linux"
    2.   string2 = "Hint"
    3.   joined_string = string1 + string2
    4.   print(joined_string)
    复制代码
    3、if...else条件语句
      Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。其中if...else语句用来执行需要判断的情形。
    1. # Assign a numeric value
    2.   number = 70
    3.   # Check the is more than 70 or not
    4.   if (number >= 70):
    5.       print("You have passed")
    6.   else:
    7.       print("You have not passed")
    复制代码
     4、for...in、while循环语句
      循环语句就是遍历一个序列,循环去执行某个操作,Python 中的循环语句有 for 和 while。
      for循环
    1.  # Initialize the list
    2.   weekdays = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday","Friday", "Saturday"]
    3.   print("Seven Weekdays are:\n")
    4.   # Iterate the list using for loop
    5.   for day in range(len(weekdays)):
    6.       print(weekdays[day])
    复制代码
    while循环
    1.  # Initialize counter
    2.   counter = 1
    3.   # Iterate the loop 5 times
    4.   while counter < 6:
    5.       # Print the counter value
    6.       print ("The current counter value: %d" % counter)
    7.       # Increment the counter
    8.       counter = counter + 1
    复制代码
    5、import导入其他脚本的功能
      有时需要使用另一个 python 文件中的脚本,这其实很简单,就像使用 import 关键字导入任何模块一样。
      「vacations.py」
    1.  # Initialize values
    2.   vacation1 = "Summer Vacation"
    3.   vacation2 = "Winter Vacation"
    复制代码
    比如在下面脚本中去引用上面vacations.py中的代码:
    1.  # Import another python script
    2.   import vacations as v
    3.   # Initialize the month list
    4.   months = ["January", "February", "March", "April", "May", "June",
    5.             "July", "August", "September", "October", "November", "December"]
    6.   # Initial flag variable to print summer vacation one time
    7.   flag = 0
    8.   # Iterate the list using for loop
    9.   for month in months:
    10.       if month == "June" or month == "July":
    11.           if flag == 0:
    12.               print("Now",v.vacation1)
    13.               flag = 1
    14.       elif month == "December":
    15.               print("Now",v.vacation2)
    16.       else:
    17.           print("The current month is",month)
    复制代码
     6、列表推导式
      Python 列表推导式是从一个或者多个迭代器快速简洁地创建数据类型的一种方法,它将循环和条件判断结合,从而避免语法冗长的代码,提高代码运行效率。能熟练使用推导式也可以间接说明你已经超越了 Python 初学者的水平。
    1.  # Create a list of characters using list comprehension
    2.   char_list = [ char for char in "linuxhint" ]
    3.   print(char_list)
    4.   # Define a tuple of websites
    5.   websites = ("google.com","yahoo.com", "ask.com", "bing.com")
    6.   # Create a list from tuple using list comprehension
    7.   site_list = [ site for site in websites ]
    8.   print(site_list)
    复制代码
    7、读写文件
      与计算的交互式Python最常使用的场景之一,比如去读取D盘中CSV文件,然后重新写入数据再保存。这就需要python执行读写文件的操作,这也是初学者要掌握的核心技能。
    1. #Assign the filename
    2.   filename = "languages.txt"
    3.   # Open file for writing
    4.   fileHandler = open(filename, "w")
    5.   # Add some text
    6.   fileHandler.write("Bash\n")
    7.   fileHandler.write("Python\n")
    8.   fileHandler.write("PHP\n")
    9.   # Close the file
    10.   fileHandler.close()
    11.   # Open file for reading
    12.   fileHandler = open(filename, "r")
    13.   # Read a file line by line
    14.   for line in fileHandler:
    15.     print(line)
    16.   # Close the file
    17.   fileHandler.close()
    复制代码
    8、切片和索引
      形如列表、字符串、元组等序列,都有切片和索引的需求,因为我们需要从中截取数据,所以这也是非常核心的技能。

    1. var1 = 'Hello World!'
    2.   var2 = "zhihu"
    3.   print ("var1[0]: ", var1[0])
    4.   print ("var2[1:5]: ", var2[1:5])
    复制代码
    9、使用函数和类
      函数和类是一种封装好的代码块,可以让代码更加简洁、实用、高效、强壮,是python的核心语法之一。定义和调用函数。
    1. # Define addition function
    2.   def addition(number1, number2):
    3.       result = number1 + number2
    4.       print("Addition result:",result)
    5.   # Define area function with return statement
    6.   def area(radius):
    7.       result = 3.14 * radius * radius
    8.       return result  
    9.   # Call addition function
    10.   addition(400, 300)
    11.   # Call area function
    12.   print("Area of the circle is",area(4))
    复制代码
    定义和实例化类:
    1. # Define the class
    2.   class Employee:
    3.       name = "Mostak Mahmud"
    4.       # Define the method
    5.       def details(self):
    6.           print("Post: Marketing Officer")
    7.           print("Department: Sales")
    8.           print("Salary: $1000")
    9.   # Create the employee object   
    10.   emp = Employee()
    11.   # Print the class variable
    12.   print("Name:",emp.name)
    13.   # Call the class method
    14.   emp.details()
    复制代码
    10、错误异常处理
      编程过程中难免会遇到错误和异常,所以我们要及时处理它,避免对后续代码造成影响。所有的标准异常都使用类来实现,都是基类Exception的成员,都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。一旦引发而且没有捕捉SystemExit异常,程序执行就会终止。异常的处理过程、如何引发或抛出异常及如何构建自己的异常类都是需要深入理解的。
    1.  # Try block
    2.   try:
    3.       # Take a number
    4.       number = int(input("Enter a number: "))
    5.       if number % 2 == 0:
    6.           print("Number is even")
    7.       else:
    8.           print("Number is odd")
    9.   # Exception block   
    10.   except (ValueError):
    11.     # Print error message
    12.     print("Enter a numeric value")
    复制代码
    小结
      当然Python还有很多有用的函数和方法,需要大家自己去总结,这里抛砖引玉,希望能帮助到需要的小伙伴。

















    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    该用户从未签到

    2#
    发表于 2022-4-8 11:50:53 | 只看该作者
    这里抛砖引玉,希望能帮助到需要的小伙伴。
    回复 支持 反对

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-7 07:10 , Processed in 0.065222 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表