Table of Contents
1. Built-in functions " > 1. Built-in functions
2、​​​zip​(*iterables,strict=False)" >2、​​zip​(*iterables,strict=False)
3、​​​filter​(function,iterable) " >3、​​filter​(function,iterable)
4、​​isinstance​​(object,classinfo)" >4、​isinstance​​(object,classinfo)
5、​​eval​(expression[,globals[,locals]])" >5、​eval​(expression[,globals[,locals]])
Commonly used sentence patterns" >Commonly used sentence patterns
1. format string formatting " >1. format string formatting
2. Connect strings" >2. Connect strings
3、if...else条件语句" >3、if...else条件语句
4、for...in、while循环语句" >4、for...in、while循环语句
5、import导入其他脚本的功能" >5、import导入其他脚本的功能
6、列表推导式" >6、列表推导式
7、读写文件" >7、读写文件
8、切片和索引" >8、切片和索引
9、使用函数和类" >9、使用函数和类
10、错误异常处理" >10、错误异常处理
小结" >小结
Home Backend Development Python Tutorial What are the most commonly used functions and basic statements in Python?

What are the most commonly used functions and basic statements in Python?

Apr 11, 2023 pm 04:43 PM
python programming language

What are the most commonly used functions and basic statements in Python?

1. Built-in functions

Built-in functions are the function methods that come with python, you can use them as you like, for example zip , filter, isinstance, etc.

The following is a list of built-in functions given in the official Python documentation, which is quite complete.

What are the most commonly used functions and basic statements in Python?

The following are common built-in functions:

1、​​<span style="font-size: 18px;"> enumerate</span>​​(iterable,start=0)

enumerate() is a built-in function of Python, which means enumeration and enumeration. For an iterable (iterable)/Traversable objects (such as lists, strings), enumerate forms an index sequence, which can be used to obtain the index and value at the same time. The usage of enumerate in python is mostly used to get the count in the for loop

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Copy after login

2、​<span style="font-size: 18px;">​zip​</span>(*iterables,strict=False)

zip( ) function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return a list composed of these tuples. If the number of elements in each iterator is inconsistent, the length of the returned list is the same as the shortest object. The tuple can be decompressed into a list using the * operator. zip(iterable1,iterable2, ...)

>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
...     print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')

Copy after login

3、​<span style="font-size: 18px;">​filter​</span>(function,iterable)

Filter filters a sequence, returns an iterator object, and removes sequences that do not meet the conditions. filter(function,data)function serves as a conditional selection function, for example, defining a function to check whether the input number is an even number. It will return True if the number is even, otherwise it will return False.

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

Copy after login

Then use filter to filter a list:

l1 = [1, 2, 3, 4, 5]
fl = filter(is_even, l1)
list(fl)

Copy after login

4、<span style="font-size: 18px;">​isinstance​</span>​(object,classinfo)

『isinstance』 is a function used to determine whether a variable or object belongs to a certain type

If the parameter object is an instance of classinfo, or object is an instance of a subclass of the classinfo class, True is returned. If object is not an object of a given type, the return result is always False

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True

Copy after login

5、​​<span style="font-size: 18px;">eval</span>​​(expression[,globals[,locals]])

eval is used to evaluate the string str as a valid expression and return the calculation result. The expression parses the parameter expression and serves as Python expressions are evaluated (technically a list of conditions), using the globals and locals dictionaries as global and local namespaces.

>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85

Copy after login

Commonly used sentence patterns

In the daily coding process, there are actually many commonly used sentence patterns, which appear very frequently and are also common writing methods.

1. format string formatting

format treats the string as a template and formats it through the passed parameters , very practical and powerful

# 格式化字符串
print('{} {}'.format('hello','world')) 

# 浮点数
float1 = 563.78453
print("{:5.2f}".format(float1))

Copy after login

2. Connect strings

##Use to connect two strings

string1 = "Linux"
string2 = "Hint"
joined_string = string1 + string2
print(joined_string)

Copy after login

3、if...else条件语句

Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。其中if...else语句用来执行需要判断的情形。

# Assign a numeric value
number = 70

# Check the is more than 70 or not
if (number >= 70):
    print("You have passed")
else:
    print("You have not passed")

Copy after login

4、for...in、while循环语句

循环语句就是遍历一个序列,循环去执行某个操作,Python 中的循环语句有 for 和 while。for循环

# Initialize the list
weekdays = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday","Friday", "Saturday"]
print("Seven Weekdays are:n")
# Iterate the list using for loop
for day in range(len(weekdays)):
    print(weekdays[day])

Copy after login

while循环

# Initialize counter
counter = 1
# Iterate the loop 5 times
while counter < 6:
    # Print the counter value
    print ("The current counter value: %d" % counter)
    # Increment the counter
    counter = counter + 1

Copy after login

5、import导入其他脚本的功能

有时需要使用另一个 python 文件中的脚本,这其实很简单,就像使用 import 关键字导入任何模块一样。「vacations.py」

# Initialize values
vacation1 = "Summer Vacation"
vacation2 = "Winter Vacation"

Copy after login

比如在下面脚本中去引用上面vacations.py中的代码

# Import another python script
import vacations as v

# Initialize the month list
months = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"]
# Initial flag variable to print summer vacation one time
flag = 0

# Iterate the list using for loop
for month in months:
    if month == "June" or month == "July":
        if flag == 0:
            print("Now",v.vacation1)
            flag = 1
    elif month == "December":
            print("Now",v.vacation2)
    else:
        print("The current month is",month)

Copy after login

6、列表推导式

Python 列表推导式是从一个或者多个迭代器快速简洁地创建数据类型的一种方法,它将循环和条件判断结合,从而避免语法冗长的代码,提高代码运行效率。能熟练使用推导式也可以间接说明你已经超越了 Python 初学者的水平。

# Create a list of characters using list comprehension
char_list = [ char for char in "linuxhint" ]
print(char_list)

# Define a tuple of websites
websites = ("google.com","yahoo.com", "ask.com", "bing.com")

# Create a list from tuple using list comprehension
site_list = [ site for site in websites ]
print(site_list)

Copy after login

7、读写文件

与计算的交互式Python最常使用的场景之一,比如去读取D盘中CSV文件,然后重新写入数据再保存。这就需要python执行读写文件的操作,这也是初学者要掌握的核心技能。

#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open(filename, "w")

# Add some text
fileHandler.write("Bashn")
fileHandler.write("Pythonn")
fileHandler.write("PHPn")

# Close the file
fileHandler.close()

# Open file for reading
fileHandler = open(filename, "r")

# Read a file line by line
for line in fileHandler:
  print(line)

# Close the file
fileHandler.close()

Copy after login

8、切片和索引

形如列表、字符串、元组等序列,都有切片和索引的需求,因为我们需要从中截取数据,所以这也是非常核心的技能。

What are the most commonly used functions and basic statements in Python?

var1 = 'Hello World!'
var2 = "zhihu"

print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

Copy after login

9、使用函数和类

函数和类是一种封装好的代码块,可以让代码更加简洁、实用、高效、强壮,是python的核心语法之一。定义和调用函数

# Define addition function
def addition(number1, number2):
    result = number1 + number2
    print("Addition result:",result)

# Define area function with return statement
def area(radius):
    result = 3.14 * radius * radius
    return result  

# Call addition function
addition(400, 300)
# Call area function
print("Area of the circle is",area(4))

Copy after login

定义和实例化类

# Define the class
class Employee:
    name = "Mostak Mahmud"
    # Define the method
    def details(self):
        print("Post: Marketing Officer")
        print("Department: Sales")
        print("Salary: $1000")

# Create the employee object    
emp = Employee()
# Print the class variable
print("Name:",emp.name)
# Call the class method
emp.details()

Copy after login

10、错误异常处理

编程过程中难免会遇到错误和异常,所以我们要及时处理它,避免对后续代码造成影响。所有的标准异常都使用类来实现,都是基类Exception的成员,都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。一旦引发而且没有捕捉SystemExit异常,程序执行就会终止。异常的处理过程、如何引发或抛出异常及如何构建自己的异常类都是需要深入理解的。

# Try block
try:
    # Take a number
    number = int(input("Enter a number: "))
    if number % 2 == 0:
        print("Number is even")
    else:
        print("Number is odd")

# Exception block    
except (ValueError):
  # Print error message
  print("Enter a numeric value")

Copy after login

小结

当然Python还有很多有用的函数和方法,需要大家自己去总结,这里抛砖引玉,希望能帮助到需要的小伙伴。

The above is the detailed content of What are the most commonly used functions and basic statements in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles